diff --git a/apps/app/src/catalogue/failure.ts b/apps/app/src/catalogue/failure.ts index 74304a75..30c743a5 100644 --- a/apps/app/src/catalogue/failure.ts +++ b/apps/app/src/catalogue/failure.ts @@ -58,3 +58,21 @@ export function coreFailure(kind: string): CatalogueFailure { if (kind === 'core_unavailable' || kind === 'internal') return 'core_unavailable' return 'invalid_document' } + +const INTEGRITY: ReadonlySet = new Set([ + 'fingerprint_mismatch', + 'drawing_hash_mismatch', + 'drawing_missing', + 'invalid_document', +]) + +/** + * How a catalogue card treats its failure (board 30, A10, owner D1): never hidden; `refused` when the + * version itself is refused (integrity, or over the size limits), retried only where a retry can work. + */ +export function cardFailure(failure: CatalogueFailure, stopped: boolean) { + const integrity = INTEGRITY.has(failure) + const refused = integrity || failure === 'caps' + const retry = !refused && !(failure === 'core_unavailable' && stopped) + return { integrity, refused, retry } +} diff --git a/apps/app/src/catalogue/useCardDetails.ts b/apps/app/src/catalogue/useCardDetails.ts index b30ba684..9ede8c6d 100644 --- a/apps/app/src/catalogue/useCardDetails.ts +++ b/apps/app/src/catalogue/useCardDetails.ts @@ -1,7 +1,9 @@ -import { useEffect, useState } from 'react' -import { listSheetVersions } from '@faunosteo/supabase' +import { useCallback, useEffect, useState } from 'react' +import { listSheetVersions, type FaunosteoClient } from '@faunosteo/supabase' +import { coreRuntime } from '@/core/runtime' import { getSupabaseClient } from '@/lib/supabase' import { loadVersion, type CatalogEntry } from './catalogue' +import { coreFailure, type CatalogueFailure } from './failure' export interface CardDetails { publishedAt: string | null @@ -9,48 +11,91 @@ export interface CardDetails { zoneCount: number /** Blob URL of the core's composed main view, shown as an image; null when it cannot be drawn. */ thumbnail: string | null + /** The core refused to compose the main view (owner D2): said in the card, counts kept. */ + viewRefused: boolean +} + +export type CardState = + | { status: 'loading' } + | { status: 'ready'; details: CardDetails } + | { status: 'failed'; failure: CatalogueFailure; retrying: boolean; attempt: number } + +type CardLoad = + | { ok: true; details: Omit; svg: string | null } + | { ok: false; failure: CatalogueFailure } + +/** One card's reads; the core handle is freed as soon as the main view is composed. */ +async function loadCard( + client: FaunosteoClient, + sheetId: string, + versionId: string, +): Promise { + const [versions, load] = await Promise.all([ + listSheetVersions(client, sheetId).catch(() => []), + loadVersion(client, versionId), + ]) + if (!load.ok) return load + const { state, preview } = load + const main = state.index ? preview.canvas(state.index.main_view_id) : null + preview.free() + // The engine failing on the view is the engine's failure, not the document's (D2). + if (main && !main.ok && coreFailure(main.kind) === 'core_unavailable') { + return { ok: false, failure: 'core_unavailable' } + } + return { + ok: true, + svg: main?.ok ? main.value : null, + details: { + publishedAt: versions.find((v) => v.id === versionId)?.published_at ?? null, + viewCount: state.document.views.length, + zoneCount: state.document.finding_zones.length, + viewRefused: main !== null && !main.ok, + }, + } } /** * What a catalogue card adds to the list answer: the publication date, the * counts the core read from the document, and a thumbnail of the main view. - * Loaded per card once the list is shown (one version and its drawings each); - * the core handle is freed as soon as the canvas is composed. Any failure - * leaves the card with its name and its link only. + * Loaded per card once the list is shown (one version and its drawings each). + * A failure is the card's to say (board 30); `retry` reloads this card only, + * keeping the failed state (`retrying`) so its line and button stay in place. */ -export function useCardDetails(entry: CatalogEntry): CardDetails | null { - const [details, setDetails] = useState(null) +export function useCardDetails(entry: CatalogEntry): { state: CardState; retry: () => void } { + const [state, setState] = useState({ status: 'loading' }) + const [attempt, setAttempt] = useState(0) useEffect(() => { let live = true let thumbnail: string | null = null const client = getSupabaseClient() if (!client) return - void Promise.all([ - listSheetVersions(client, entry.sheet_id).catch(() => []), - loadVersion(client, entry.version_id), - ]).then(([versions, load]) => { - if (!load.ok) return - const { state, preview } = load - const main = state.index ? preview.canvas(state.index.main_view_id) : null - preview.free() + void loadCard(client, entry.sheet_id, entry.version_id).then((load) => { if (!live) return - if (main?.ok) { - thumbnail = URL.createObjectURL(new Blob([main.value], { type: 'image/svg+xml' })) + if (!load.ok) { + setState({ status: 'failed', failure: load.failure, retrying: false, attempt }) + return } - setDetails({ - publishedAt: - versions.find((v) => v.id === entry.version_id)?.published_at ?? null, - viewCount: state.document.views.length, - zoneCount: state.document.finding_zones.length, - thumbnail, - }) + if (load.svg !== null) { + thumbnail = URL.createObjectURL(new Blob([load.svg], { type: 'image/svg+xml' })) + } + setState({ status: 'ready', details: { ...load.details, thumbnail } }) }) return () => { live = false if (thumbnail) URL.revokeObjectURL(thumbnail) } - }, [entry.sheet_id, entry.version_id]) + }, [entry.sheet_id, entry.version_id, attempt]) - return details + 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 + setState({ ...failed, retrying: true }) + const restart = + failed.failure === 'core_unavailable' ? coreRuntime().retry() : Promise.resolve(true) + void restart.finally(() => setAttempt((n) => n + 1)) + }, [failed]) + + return { state, retry } } diff --git a/apps/app/src/components/catalogue/CardFailure.tsx b/apps/app/src/components/catalogue/CardFailure.tsx new file mode 100644 index 00000000..bc4486fb --- /dev/null +++ b/apps/app/src/components/catalogue/CardFailure.tsx @@ -0,0 +1,71 @@ +import type { ReactNode, Ref } from 'react' +import { cardFailure, type CatalogueFailure } from '@/catalogue/failure' +import type { CardState } from '@/catalogue/useCardDetails' +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import { coreFailureMessage } from '@/core/failure' +import { useCoreStopped } from '@/core/runtime' +import { useT } from '@/i18n/useT' + +type Translate = ReturnType + +function failureText(t: Translate, failure: CatalogueFailure, integrity: boolean): string { + if (integrity) return t('catalogue.card.integrity_failed') + if (failure === 'core_unavailable') return coreFailureMessage(t, 'sheet.core_unavailable') + if (failure === 'denied') return t('access_denied.title') + return t(`catalogue.failure.${failure}`) +} + +export interface CardFailureProps { + failed: Extract + onRetry: () => void + retryRef: Ref + /** The card's « Consulter », kept after « Réessayer » in every state. */ + children: ReactNode +} + +/** + * 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). + */ +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 text = failureText(t, failure, integrity) + + return ( + <> + + {integrity ? {text} : text} + + {retry && ( +
+ {!retrying && attempt > 0 ? text : ''} +
+ )} +
+ {retry && ( + + )} + {children} +
+ + ) +} diff --git a/apps/app/src/components/catalogue/CatalogueCard.tsx b/apps/app/src/components/catalogue/CatalogueCard.tsx index 20f7433d..4b680795 100644 --- a/apps/app/src/components/catalogue/CatalogueCard.tsx +++ b/apps/app/src/components/catalogue/CatalogueCard.tsx @@ -1,11 +1,19 @@ +import { useCallback, useEffect, useRef } from 'react' import type { CatalogEntry } from '@/catalogue/catalogue' -import { useCardDetails } from '@/catalogue/useCardDetails' +import { + useCardDetails, + type CardDetails, + type CardState, +} from '@/catalogue/useCardDetails' import { versionText } from '@/catalogue/versionText' import Badge from '@/components/ui/Badge' import ButtonLink from '@/components/ui/ButtonLink' import Card from '@/components/ui/Card' import Icon from '@/components/ui/Icon' +import Notice from '@/components/ui/Notice' +import CardFailure from './CardFailure' import { pickLabel } from '@/i18n/pickLocaleLabel' +import type { Locale } from '@/i18n/types' import { useLocaleStore } from '@/state/localeStore' import { useT } from '@/i18n/useT' @@ -15,11 +23,112 @@ function counted(count: number, key: string, t: Translate): string { return t(`${key}_${count === 1 ? 'one' : 'other'}`).replace('{count}', String(count)) } +/** The version line, with the counts once the core read them. */ +function versionLine( + entry: CatalogEntry, + details: CardDetails | null, + locale: Locale, + t: Translate, +): string { + return [ + versionText(entry.version_number, details?.publishedAt ?? null, locale, t), + ...(details + ? [ + `${counted(details.viewCount, 'catalogue.card.views', t)}, ${counted(details.zoneCount, 'catalogue.card.zones', t)}`, + ] + : []), + ].join(' · ') +} + +function ConsultLink({ sheetId, name }: { sheetId: string; name: string }) { + const t = useT() + return ( + + + {t('catalogue.view')} + + ) +} + /** - * One published sheet of the catalogue (board 01): species, « Publiée », name, - * version line with the counts the core read, a thumbnail of the main view, - * « Consulter ». Until its details load (or when they cannot), the card keeps - * its name, version and link. + * 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. + */ +function useFocusAfterRetry(state: CardState) { + const item = useRef(null) + const lastRetry = useRef(null) + const wasRetrying = useRef(false) + + useEffect(() => { + if (state.status === 'failed') wasRetrying.current = state.retrying + if (state.status !== 'ready' || !wasRetrying.current) return + wasRetrying.current = false + const active = document.activeElement + if (!active || active === document.body || active === lastRetry.current) { + item.current?.querySelector('a')?.focus() + } + }, [state]) + + // Kept past unmount: the removed button is how the focus is recognised. + const retryRef = useCallback((button: HTMLButtonElement | null) => { + if (button) lastRetry.current = button + }, []) + return { item, retryRef } +} + +interface CardContentProps { + entry: CatalogEntry + name: string + state: CardState + onRetry: () => void + retryRef: (button: HTMLButtonElement | null) => void +} + +/** Below the name: version line, then the thumbnail, or the failure in its place. */ +function CardContent({ entry, name, state, onRetry, retryRef }: CardContentProps) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const details = state.status === 'ready' ? state.details : null + const consult = + + return ( + <> +

+ {versionLine(entry, details, locale, t)} +

+ {details?.thumbnail && ( + + )} + {details?.viewRefused && ( + + {t('catalogue.failure.view')} + + )} + {state.status === 'failed' ? ( + + {consult} + + ) : ( +
{consult}
+ )} + + ) +} + +/** + * One published sheet of the catalogue (boards 01 and 30): species, « Publiée », + * name, version line with the counts the core read, a thumbnail of the main + * view, « Consulter ». A failed load is said in place of the counts and the + * thumbnail, with « Réessayer » where it can help; « Consulter » stays. */ export default function CatalogueCard({ entry, @@ -30,20 +139,17 @@ export default function CatalogueCard({ }) { const t = useT() const locale = useLocaleStore((s) => s.locale) - const details = useCardDetails(entry) + const { state, retry } = useCardDetails(entry) + const { item, retryRef } = useFocusAfterRetry(state) const name = pickLabel(entry.name, locale) - const line = [ - versionText(entry.version_number, details?.publishedAt ?? null, locale, t), - ...(details - ? [ - `${counted(details.viewCount, 'catalogue.card.views', t)}, ${counted(details.zoneCount, 'catalogue.card.zones', t)}`, - ] - : []), - ].join(' · ') return ( -
  • - +
  • +
    {speciesName} @@ -52,25 +158,13 @@ export default function CatalogueCard({

    {name}

    -

    {line}

    - {details?.thumbnail && ( - - )} -
    - - - {t('catalogue.view')} - -
    +
  • ) diff --git a/apps/app/src/components/ui/Card.tsx b/apps/app/src/components/ui/Card.tsx index 1e885b2c..9cdd6d92 100644 --- a/apps/app/src/components/ui/Card.tsx +++ b/apps/app/src/components/ui/Card.tsx @@ -6,6 +6,8 @@ export interface CardProps { as?: 'div' | 'section' | 'article' /** Names a section card by its heading, so it reads as a named region. */ 'aria-labelledby'?: string + /** While the card's content is being loaded again (a retry). */ + 'aria-busy'?: boolean } export default function Card({ @@ -13,10 +15,12 @@ export default function Card({ className = '', as: Tag = 'div', 'aria-labelledby': labelledBy, + 'aria-busy': busy, }: CardProps) { return ( { // The card whose version cannot be read keeps its name, version and link. const dog = screen.getByRole('heading', { level: 2, name: 'Chien, rachis' }).closest('article')! expect(within(dog).getByText('Version 1')).toBeInTheDocument() + // Its refused read is said in the card (F7). + expect(await within(dog).findByText(fr['access_denied.title'])).toBeInTheDocument() }) it('searches by sheet name in either language and filters by species', async () => { @@ -347,3 +350,267 @@ describe('failures', () => { expect(preview.canvas('main')).toEqual({ ok: false, kind: 'core_unavailable' }) }) }) + +describe('catalogue cards (R4, board 30)', () => { + type Rpc = { rpc: (name: string, args?: unknown) => Promise } + + afterEach(() => vi.restoreAllMocks()) + + async function card(name: string): Promise { + return (await screen.findByRole('heading', { level: 2, name })).closest('article')! + } + + /** The element carrying the notice's tone classes around a line of text. */ + function noticeOf(text: HTMLElement): HTMLElement { + return text.closest('div.rounded-lg')! + } + + function versionCalls(id: string): number { + return fake.rpcCalls.filter( + ([n, a]) => n === 'get_sheet_version' && (a as { version_id: string }).version_id === id, + ).length + } + + /** Every `get_sheet_version` fails as a dropped request would. */ + function failNetwork() { + fake.rpcResults.get_sheet_version = () => ({ error: { message: 'network' } }) + } + + /** Holds every later `get_sheet_version` answer until the returned release is called. */ + function holdVersions(): () => void { + let release!: () => void + const gate = new Promise((resolve) => (release = resolve)) + const target = fake.client as unknown as Rpc + const original = target.rpc + target.rpc = async (name, args) => { + if (name === 'get_sheet_version') await gate + return original(name, args) + } + return release + } + + async function failedCheval(text: string): Promise { + const cheval = await card('Cheval') + await within(cheval).findByText(text) + return cheval + } + + it.each([ + [ + 'a drawing whose bytes do not hash to its row', + () => { + const altered = bytes.slice() + altered[200] ^= 1 + fake.storage.download.mockImplementation(async () => ({ data: new Blob([altered]), error: null })) + }, + ], + [ + 'a stored fingerprint the core does not recompute', + () => serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) }), + ], + [ + 'a drawing Storage answers 400 for', + () => + fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 400, name: 'StorageApiError' } })), + ], + [ + 'a drawing Storage answers 404 for', + () => + fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 404, name: 'StorageApiError' } })), + ], + [ + 'an unreadable document', + () => serveVersions({ [V3]: versionAnswer(V3, 'published', { document: { schema_version: 2 } }) }), + ], + ])('says the integrity failure of %s, without retry or live region', async (_case, arrange) => { + arrange() + mount('/app/anatomy') + const cheval = await failedCheval(fr['catalogue.card.integrity_failed']) + expect(noticeOf(within(cheval).getByText(fr['catalogue.card.integrity_failed'])).className).toMatch( + /color-danger/, + ) + expect(within(cheval).queryByRole('alert')).toBeNull() + expect(within(cheval).queryByRole('status')).toBeNull() + expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull() + expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveAttribute('href', `/app/anatomy/${SHEET}`) + expect(within(cheval).getByText(fr['catalogue.status.published'])).toBeInTheDocument() + expect(cheval.querySelector('img')).toBeNull() + }) + + it('says a network failure, retries that card and moves the focus to « Consulter »', async () => { + failNetwork() + mount('/app/anatomy') + const cheval = await failedCheval(fr['catalogue.failure.network']) + expect(noticeOf(within(cheval).getByText(fr['catalogue.failure.network'])).className).toMatch( + /severity-moderate/, + ) + const retries = within(cheval).getAllByRole('button', { name: fr['common.retry'] }) + expect(retries).toHaveLength(1) + serveVersions({ [V3]: versionAnswer(V3, 'published') }) + await userEvent.click(retries[0]) + expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument() + expect(within(cheval).queryByText(fr['catalogue.failure.network'])).toBeNull() + expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveFocus() + }) + + it('keeps « Réessayer » focused during an attempt that fails again, then says the line politely', async () => { + failNetwork() + mount('/app/anatomy') + const cheval = await failedCheval(fr['catalogue.failure.network']) + const polite = cheval.querySelector('[aria-live="polite"]')! + expect(polite).toHaveTextContent('') + const release = holdVersions() + const retry = within(cheval).getByRole('button', { name: fr['common.retry'] }) + await userEvent.click(retry) + expect(retry).toHaveFocus() + expect(retry).toHaveAttribute('aria-disabled', 'true') + expect(cheval).toHaveAttribute('aria-busy', 'true') + expect(polite).toHaveTextContent('') + await act(async () => release()) + await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network'])) + expect(retry).toBeInTheDocument() + expect(retry).toHaveFocus() + expect(retry).not.toHaveAttribute('aria-disabled', 'true') + expect(cheval).not.toHaveAttribute('aria-busy', 'true') + }) + + it('reloads only the card whose « Réessayer » was pressed, with no burst of announcements', async () => { + failNetwork() + mount('/app/anatomy') + const cheval = await failedCheval(fr['catalogue.failure.network']) + const dog = await card('Chien, rachis') + await within(dog).findByText(fr['catalogue.failure.network']) + expect(screen.queryAllByRole('alert')).toHaveLength(0) + expect(within(cheval).queryByRole('status')).toBeNull() + expect(within(dog).queryByRole('status')).toBeNull() + const before = versionCalls(DOG) + const chevalBefore = versionCalls(V3) + await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] })) + const polite = cheval.querySelector('[aria-live="polite"]')! + await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network'])) + expect(versionCalls(V3)).toBe(chevalBefore + 1) + expect(versionCalls(DOG)).toBe(before) + }) + + it('ignores a second click while the attempt runs', async () => { + failNetwork() + mount('/app/anatomy') + const cheval = await failedCheval(fr['catalogue.failure.network']) + const release = holdVersions() + const before = versionCalls(V3) + const retry = within(cheval).getByRole('button', { name: fr['common.retry'] }) + await userEvent.click(retry) + await userEvent.click(retry) + await act(async () => release()) + const polite = cheval.querySelector('[aria-live="polite"]')! + await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network'])) + 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') + const cheval = await failedCheval(fr['catalogue.failure.network']) + const created = vi.spyOn(URL, 'createObjectURL') + const revoked = vi.spyOn(URL, 'revokeObjectURL') + const built = vi.spyOn(CataloguePreview.prototype, 'state') + const freed = vi.spyOn(CataloguePreview.prototype, 'free') + const errors = vi.spyOn(console, 'error') + const release = holdVersions() + serveVersions({ [V3]: versionAnswer(V3, 'published') }) + await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] })) + await userEvent.type(screen.getByRole('searchbox', { name: fr['catalogue.search'] }), 'dog') + expect(screen.queryByRole('heading', { level: 2, name: 'Cheval' })).toBeNull() + await act(async () => release()) + await waitFor(() => expect(freed).toHaveBeenCalled()) + 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(errors).not.toHaveBeenCalled() + }) + + it('says the core failed to load and restarts it on « Réessayer »', async () => { + vi.spyOn(coreRuntime(), 'ready').mockResolvedValueOnce(false) + const restart = vi.spyOn(coreRuntime(), 'retry') + mount('/app/anatomy') + const cheval = await failedCheval(fr['sheet.core_unavailable']) + await userEvent.click(within(cheval).getByRole('button', { name: fr['sheet.core_retry'] })) + expect(restart).toHaveBeenCalledTimes(1) + expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument() + expect(within(cheval).queryByText(fr['sheet.core_unavailable'])).toBeNull() + }) + + it('says an expired session with « Réessayer »', async () => { + fake.rpcResults.get_sheet_version = () => ({ error: { message: 'session_expired' } }) + mount('/app/anatomy') + const cheval = await failedCheval(fr['catalogue.failure.session_expired']) + expect(within(cheval).getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument() + }) + + it('says a refused version read with « Réessayer »', async () => { + mount('/app/anatomy') + const dog = await card('Chien, rachis') + expect(await within(dog).findByText(fr['access_denied.title'])).toBeInTheDocument() + expect(within(dog).getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument() + }) + + it('says a version over the size limits apart from integrity, without retry (D1)', async () => { + vi.spyOn(CataloguePreview.prototype, 'state').mockReturnValueOnce({ ok: false, kind: 'caps' }) + mount('/app/anatomy') + const cheval = await failedCheval(fr['catalogue.failure.caps']) + expect(noticeOf(within(cheval).getByText(fr['catalogue.failure.caps'])).className).toMatch(/color-danger/) + expect(within(cheval).queryByText(fr['catalogue.card.integrity_failed'])).toBeNull() + expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull() + expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toBeInTheDocument() + }) + + it('says the integrity failure in English', async () => { + useLocaleStore.setState({ locale: 'en' }) + serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) }) + mount('/app/anatomy') + const horse = await card('Horse') + expect(await within(horse).findByText(en['catalogue.card.integrity_failed'])).toBeInTheDocument() + }) + + it('classes every failure kind', () => { + const expected: Record = { + fingerprint_mismatch: [true, true], + drawing_hash_mismatch: [true, true], + drawing_missing: [true, true], + invalid_document: [true, true], + caps: [false, true], + denied: [false, false], + network: [false, false], + session_expired: [false, false], + rate_limited: [false, false], + unavailable: [false, false], + core_unavailable: [false, false], + } + for (const [kind, [integrity, refused]] of Object.entries(expected)) { + const failure = kind as CatalogueFailure + expect(cardFailure(failure, false)).toEqual({ integrity, refused, retry: !refused }) + const stoppedRetry = !refused && failure !== 'core_unavailable' + expect(cardFailure(failure, true)).toEqual({ integrity, refused, retry: stoppedRetry }) + } + }) + + it('says a main view the core refuses to compose, with the counts (D2)', async () => { + vi.spyOn(CataloguePreview.prototype, 'canvas').mockReturnValueOnce({ ok: false, kind: 'view_refused' }) + mount('/app/anatomy') + const cheval = await failedCheval(fr['catalogue.failure.view']) + const line = noticeOf(within(cheval).getByText(fr['catalogue.failure.view'])) + expect(line.className).toMatch(/surface-strong/) + expect(within(cheval).queryByRole('status')).toBeNull() + expect(within(cheval).getByText(/2 vues, 27 zones de constats/)).toBeInTheDocument() + expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull() + expect(cheval.querySelector('img')).toBeNull() + }) + + it('says the engine failed while composing the main view, with its retry (D2)', async () => { + vi.spyOn(CataloguePreview.prototype, 'canvas').mockReturnValueOnce({ ok: false, kind: 'core_unavailable' }) + mount('/app/anatomy') + const cheval = await failedCheval(fr['sheet.core_unavailable']) + expect(within(cheval).getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument() + }) +})