diff --git a/apps/app/src/catalogue/useCardDetails.ts b/apps/app/src/catalogue/useCardDetails.ts index 9ede8c6d..bd48b6b8 100644 --- a/apps/app/src/catalogue/useCardDetails.ts +++ b/apps/app/src/catalogue/useCardDetails.ts @@ -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 { coreRuntime } from '@/core/runtime' import { getSupabaseClient } from '@/lib/supabase' @@ -64,6 +64,9 @@ async function loadCard( export function useCardDetails(entry: CatalogEntry): { state: CardState; retry: () => void } { const [state, setState] = useState({ status: 'loading' }) 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(() => { let live = true @@ -72,6 +75,7 @@ export function useCardDetails(entry: CatalogEntry): { state: CardState; retry: if (!client) return void loadCard(client, entry.sheet_id, entry.version_id).then((load) => { if (!live) return + running.current = false if (!load.ok) { setState({ status: 'failed', failure: load.failure, retrying: false, attempt }) return @@ -90,7 +94,8 @@ export function useCardDetails(entry: CatalogEntry): { state: CardState; retry: 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. const retry = useCallback(() => { - if (!failed) return + if (!failed || running.current) return + running.current = true setState({ ...failed, retrying: true }) const restart = failed.failure === 'core_unavailable' ? coreRuntime().retry() : Promise.resolve(true) diff --git a/apps/app/src/components/catalogue/CardFailure.tsx b/apps/app/src/components/catalogue/CardFailure.tsx index bc4486fb..17cae87d 100644 --- a/apps/app/src/components/catalogue/CardFailure.tsx +++ b/apps/app/src/components/catalogue/CardFailure.tsx @@ -26,27 +26,30 @@ export interface CardFailureProps { /** * 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 - * retry can work, and a polite region that says the line again only after a - * retry failed (empty at load and while an attempt runs). + * region, so several cards failing at load stay quiet), in the warning tone + * where « Réessayer » can work and the error tone where it cannot (a refused + * 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) { const t = useT() const stopped = useCoreStopped() const { failure, retrying, attempt } = failed - const { integrity, refused, retry } = cardFailure(failure, stopped) + const { integrity, retry } = cardFailure(failure, stopped) const text = failureText(t, failure, integrity) return ( <> {integrity ? {text} : text} - {retry && ( + {(retry || attempt > 0) && (
{!retrying && attempt > 0 ? text : ''}
@@ -57,7 +60,7 @@ export default function CardFailure({ failed, onRetry, retryRef, children }: Car ref={retryRef} type="button" variant="secondary" - className="min-h-11" + className="min-h-11 aria-disabled:cursor-wait aria-disabled:opacity-60" aria-disabled={retrying ? 'true' : undefined} onClick={onRetry} > diff --git a/apps/app/src/components/catalogue/CatalogueCard.tsx b/apps/app/src/components/catalogue/CatalogueCard.tsx index 4b680795..c30f1308 100644 --- a/apps/app/src/components/catalogue/CatalogueCard.tsx +++ b/apps/app/src/components/catalogue/CatalogueCard.tsx @@ -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 - * nothing) moves to the card's « Consulter » (R-3); focus elsewhere is kept. + * When a retry settles without its « Réessayer » (success, or a failure with no + * 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) { const item = useRef(null) @@ -65,11 +67,17 @@ function useFocusAfterRetry(state: CardState) { const wasRetrying = useRef(false) useEffect(() => { - if (state.status === 'failed') wasRetrying.current = state.retrying - if (state.status !== 'ready' || !wasRetrying.current) return + if (state.status === 'loading') return + if (state.status === 'failed' && state.retrying) { + wasRetrying.current = true + return + } + if (!wasRetrying.current) return wasRetrying.current = false + const button = lastRetry.current + if (button?.isConnected) return const active = document.activeElement - if (!active || active === document.body || active === lastRetry.current) { + if (!active || active === document.body || active === button) { item.current?.querySelector('a')?.focus() } }, [state]) diff --git a/apps/app/tests/unit/routes.catalogue.test.tsx b/apps/app/tests/unit/routes.catalogue.test.tsx index 9e1a64b6..d714986a 100644 --- a/apps/app/tests/unit/routes.catalogue.test.tsx +++ b/apps/app/tests/unit/routes.catalogue.test.tsx @@ -5,6 +5,7 @@ import { MemoryRouter, Route, Routes } from 'react-router-dom' import type { PreviewState } from '@faunosteo/core-wasm/types' import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase' import { bundledSheet } from '../helpers/sheet' +import { controlStopped } from '../helpers/core' const mocks = vi.hoisted(() => ({ fake: null as unknown })) vi.mock('@/lib/supabase', () => ({ @@ -464,6 +465,9 @@ describe('catalogue cards (R4, board 30)', () => { await userEvent.click(retry) expect(retry).toHaveFocus() 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(polite).toHaveTextContent('') await act(async () => release()) @@ -507,6 +511,36 @@ describe('catalogue cards (R4, board 30)', () => { 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 () => { failNetwork() mount('/app/anatomy') @@ -526,7 +560,8 @@ describe('catalogue cards (R4, board 30)', () => { await act(async () => new Promise((resolve) => setTimeout(resolve, 20))) expect(built.mock.calls.length).toBeGreaterThan(0) 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() }) @@ -541,6 +576,37 @@ describe('catalogue cards (R4, board 30)', () => { 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 () => { fake.rpcResults.get_sheet_version = () => ({ error: { message: 'session_expired' } }) mount('/app/anatomy')