fix(app): card retry keeps focus and voice when no retry is left

A retry ending on a failure with no retry (network to integrity, engine
stopped for good) keeps the polite region and moves focus to Consulter.
Busy look on Réessayer, error tone once the engine stopped, one attempt
for two calls in one tick; tests for the stopped engine, two core cards
and no blob URL after unmount.
This commit is contained in:
bchanot committed 2026-11-17 00:59:30 +01:00
1 parent 4a7919c763
commit b378cf066f
4 files changed
+97 -15

No files matched your search

+7 -2
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { listSheetVersions, type FaunosteoClient } from '@faunosteo/supabase' import { listSheetVersions, type FaunosteoClient } from '@faunosteo/supabase'
import { coreRuntime } from '@/core/runtime' import { coreRuntime } from '@/core/runtime'
import { getSupabaseClient } from '@/lib/supabase' import { getSupabaseClient } from '@/lib/supabase'
@@ -64,6 +64,9 @@ async function loadCard(
export function useCardDetails(entry: CatalogEntry): { state: CardState; retry: () => void } { export function useCardDetails(entry: CatalogEntry): { state: CardState; retry: () => void } {
const [state, setState] = useState<CardState>({ status: 'loading' }) const [state, setState] = useState<CardState>({ status: 'loading' })
const [attempt, setAttempt] = useState(0) const [attempt, setAttempt] = useState(0)
// Set by the first call, cleared when its attempt settles: two calls in one
// tick start one attempt.
const running = useRef(false)
useEffect(() => { useEffect(() => {
let live = true let live = true
@@ -72,6 +75,7 @@ export function useCardDetails(entry: CatalogEntry): { state: CardState; retry:
if (!client) return if (!client) return
void loadCard(client, entry.sheet_id, entry.version_id).then((load) => { void loadCard(client, entry.sheet_id, entry.version_id).then((load) => {
if (!live) return if (!live) return
running.current = false
if (!load.ok) { if (!load.ok) {
setState({ status: 'failed', failure: load.failure, retrying: false, attempt }) setState({ status: 'failed', failure: load.failure, retrying: false, attempt })
return return
@@ -90,7 +94,8 @@ export function useCardDetails(entry: CatalogEntry): { state: CardState; retry:
const failed = state.status === 'failed' && !state.retrying ? state : null const failed = state.status === 'failed' && !state.retrying ? state : null
// Ignored while an attempt runs; the core may need a restart before the card loads again. // Ignored while an attempt runs; the core may need a restart before the card loads again.
const retry = useCallback(() => { const retry = useCallback(() => {
if (!failed) return if (!failed || running.current) return
running.current = true
setState({ ...failed, retrying: true }) setState({ ...failed, retrying: true })
const restart = const restart =
failed.failure === 'core_unavailable' ? coreRuntime().retry() : Promise.resolve(true) failed.failure === 'core_unavailable' ? coreRuntime().retry() : Promise.resolve(true)
@@ -26,27 +26,30 @@ export interface CardFailureProps {
/** /**
* A catalogue card's failure (board 30, R-1 to R-4): the line (not a live * A catalogue card's failure (board 30, R-1 to R-4): the line (not a live
* region, so several cards failing at load stay quiet), « Réessayer » where a * region, so several cards failing at load stay quiet), in the warning tone
* retry can work, and a polite region that says the line again only after a * where « Réessayer » can work and the error tone where it cannot (a refused
* retry failed (empty at load and while an attempt runs). * version, the engine stopped for good), and a polite region that says the
* line again only after a retry failed (empty at load and while an attempt
* runs). The region stays once a retry ran, even when the new failure offers
* no retry, so the line it ends on is still said.
*/ */
export default function CardFailure({ failed, onRetry, retryRef, children }: CardFailureProps) { export default function CardFailure({ failed, onRetry, retryRef, children }: CardFailureProps) {
const t = useT() const t = useT()
const stopped = useCoreStopped() const stopped = useCoreStopped()
const { failure, retrying, attempt } = failed const { failure, retrying, attempt } = failed
const { integrity, refused, retry } = cardFailure(failure, stopped) const { integrity, retry } = cardFailure(failure, stopped)
const text = failureText(t, failure, integrity) const text = failureText(t, failure, integrity)
return ( return (
<> <>
<Notice <Notice
tone={refused ? 'error' : 'warning'} tone={retry ? 'warning' : 'error'}
icon={failure === 'network' ? 'wifi-off' : 'alert'} icon={failure === 'network' ? 'wifi-off' : 'alert'}
live={false} live={false}
> >
{integrity ? <strong className="font-semibold">{text}</strong> : text} {integrity ? <strong className="font-semibold">{text}</strong> : text}
</Notice> </Notice>
{retry && ( {(retry || attempt > 0) && (
<div aria-live="polite" className="sr-only"> <div aria-live="polite" className="sr-only">
{!retrying && attempt > 0 ? text : ''} {!retrying && attempt > 0 ? text : ''}
</div> </div>
@@ -57,7 +60,7 @@ export default function CardFailure({ failed, onRetry, retryRef, children }: Car
ref={retryRef} ref={retryRef}
type="button" type="button"
variant="secondary" variant="secondary"
className="min-h-11" className="min-h-11 aria-disabled:cursor-wait aria-disabled:opacity-60"
aria-disabled={retrying ? 'true' : undefined} aria-disabled={retrying ? 'true' : undefined}
onClick={onRetry} onClick={onRetry}
> >
@@ -56,8 +56,10 @@ function ConsultLink({ sheetId, name }: { sheetId: string; name: string }) {
} }
/** /**
* After a successful retry, the focus left on the removed « Réessayer » (or on * When a retry settles without its « Réessayer » (success, or a failure with no
* nothing) moves to the card's « Consulter » (R-3); focus elsewhere is kept. * retry left), the focus left on the removed button (or on nothing) moves to
* the card's « Consulter » (R-3); focus elsewhere, or on a « Réessayer » still
* there, is kept.
*/ */
function useFocusAfterRetry(state: CardState) { function useFocusAfterRetry(state: CardState) {
const item = useRef<HTMLLIElement>(null) const item = useRef<HTMLLIElement>(null)
@@ -65,11 +67,17 @@ function useFocusAfterRetry(state: CardState) {
const wasRetrying = useRef(false) const wasRetrying = useRef(false)
useEffect(() => { useEffect(() => {
if (state.status === 'failed') wasRetrying.current = state.retrying if (state.status === 'loading') return
if (state.status !== 'ready' || !wasRetrying.current) return if (state.status === 'failed' && state.retrying) {
wasRetrying.current = true
return
}
if (!wasRetrying.current) return
wasRetrying.current = false wasRetrying.current = false
const button = lastRetry.current
if (button?.isConnected) return
const active = document.activeElement const active = document.activeElement
if (!active || active === document.body || active === lastRetry.current) { if (!active || active === document.body || active === button) {
item.current?.querySelector('a')?.focus() item.current?.querySelector('a')?.focus()
} }
}, [state]) }, [state])
+67 -1
View File
@@ -5,6 +5,7 @@ import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { PreviewState } from '@faunosteo/core-wasm/types' import type { PreviewState } from '@faunosteo/core-wasm/types'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase' import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
import { bundledSheet } from '../helpers/sheet' import { bundledSheet } from '../helpers/sheet'
import { controlStopped } from '../helpers/core'
const mocks = vi.hoisted(() => ({ fake: null as unknown })) const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({ vi.mock('@/lib/supabase', () => ({
@@ -464,6 +465,9 @@ describe('catalogue cards (R4, board 30)', () => {
await userEvent.click(retry) await userEvent.click(retry)
expect(retry).toHaveFocus() expect(retry).toHaveFocus()
expect(retry).toHaveAttribute('aria-disabled', 'true') expect(retry).toHaveAttribute('aria-disabled', 'true')
// The attempt is seen, not only told: greyed with a wait cursor (no new wording).
expect(retry.className).toMatch(/aria-disabled:opacity-60/)
expect(retry.className).toMatch(/aria-disabled:cursor-wait/)
expect(cheval).toHaveAttribute('aria-busy', 'true') expect(cheval).toHaveAttribute('aria-busy', 'true')
expect(polite).toHaveTextContent('') expect(polite).toHaveTextContent('')
await act(async () => release()) await act(async () => release())
@@ -507,6 +511,36 @@ describe('catalogue cards (R4, board 30)', () => {
expect(versionCalls(V3)).toBe(before + 1) expect(versionCalls(V3)).toBe(before + 1)
}) })
it('moves the focus to « Consulter » and says the line when a retry ends with no retry left', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const polite = cheval.querySelector('[aria-live="polite"]')!
serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) })
await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] }))
// The region mounted before the attempt is the one that speaks (never mounted with its text).
await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.card.integrity_failed']))
expect(polite.isConnected).toBe(true)
expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveFocus()
})
it('ignores a second retry call in the same tick', async () => {
vi.spyOn(coreRuntime(), 'ready').mockResolvedValueOnce(false)
const restart = vi.spyOn(coreRuntime(), 'retry')
mount('/app/anatomy')
const cheval = await failedCheval(fr['sheet.core_unavailable'])
const before = versionCalls(V3)
const retry = within(cheval).getByRole('button', { name: fr['sheet.core_retry'] })
act(() => {
fireEvent.click(retry)
fireEvent.click(retry)
})
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(restart).toHaveBeenCalledTimes(1)
expect(versionCalls(V3)).toBe(before + 1)
})
it('drops a retry still running when the card leaves: no update, URLs and previews balanced', async () => { it('drops a retry still running when the card leaves: no update, URLs and previews balanced', async () => {
failNetwork() failNetwork()
mount('/app/anatomy') mount('/app/anatomy')
@@ -526,7 +560,8 @@ describe('catalogue cards (R4, board 30)', () => {
await act(async () => new Promise((resolve) => setTimeout(resolve, 20))) await act(async () => new Promise((resolve) => setTimeout(resolve, 20)))
expect(built.mock.calls.length).toBeGreaterThan(0) expect(built.mock.calls.length).toBeGreaterThan(0)
expect(freed).toHaveBeenCalledTimes(built.mock.calls.length) expect(freed).toHaveBeenCalledTimes(built.mock.calls.length)
expect(created).toHaveBeenCalledTimes(revoked.mock.calls.length) expect(created).not.toHaveBeenCalled()
expect(revoked).not.toHaveBeenCalled()
expect(errors).not.toHaveBeenCalled() expect(errors).not.toHaveBeenCalled()
}) })
@@ -541,6 +576,37 @@ describe('catalogue cards (R4, board 30)', () => {
expect(within(cheval).queryByText(fr['sheet.core_unavailable'])).toBeNull() expect(within(cheval).queryByText(fr['sheet.core_unavailable'])).toBeNull()
}) })
it('says the engine stopped for good in the error tone, with no « Réessayer »', async () => {
const setStopped = controlStopped(coreRuntime(), true)
try {
vi.spyOn(coreRuntime(), 'ready').mockResolvedValue(false)
mount('/app/anatomy')
const cheval = await failedCheval(fr['core.stopped'])
expect(noticeOf(within(cheval).getByText(fr['core.stopped'])).className).toMatch(/color-danger/)
expect(within(cheval).queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toBeInTheDocument()
} finally {
act(() => setStopped(false))
}
})
it('restarts the engine and reloads only the card whose « Réessayer » was pressed (R-7)', async () => {
serveVersions({ [V3]: versionAnswer(V3, 'published'), [DOG]: versionAnswer(DOG, 'published') })
vi.spyOn(coreRuntime(), 'ready').mockResolvedValueOnce(false).mockResolvedValueOnce(false)
const restart = vi.spyOn(coreRuntime(), 'retry')
mount('/app/anatomy')
const cheval = await failedCheval(fr['sheet.core_unavailable'])
const dog = await card('Chien, rachis')
await within(dog).findByText(fr['sheet.core_unavailable'])
const dogCalls = versionCalls(DOG)
await userEvent.click(within(cheval).getByRole('button', { name: fr['sheet.core_retry'] }))
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(restart).toHaveBeenCalledTimes(1)
expect(versionCalls(DOG)).toBe(dogCalls)
expect(within(dog).getByText(fr['sheet.core_unavailable'])).toBeInTheDocument()
expect(within(dog).getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument()
})
it('says an expired session with « Réessayer »', async () => { it('says an expired session with « Réessayer »', async () => {
fake.rpcResults.get_sheet_version = () => ({ error: { message: 'session_expired' } }) fake.rpcResults.get_sheet_version = () => ({ error: { message: 'session_expired' } })
mount('/app/anatomy') mount('/app/anatomy')