feat(app): catalogue cards say an integrity or load failure (board 30)

This commit is contained in:
bchanot committed 2026-11-17 00:14:14 +01:00
1 parent f061111e25
commit 6ad8d8347c
8 files changed
+564 -63

No files matched your search

+18
View File
@@ -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<CatalogueFailure> = 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 }
}
+71 -26
View File
@@ -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<CardDetails, 'thumbnail'>; 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<CardLoad> {
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<CardDetails | null>(null)
export function useCardDetails(entry: CatalogEntry): { state: CardState; retry: () => void } {
const [state, setState] = useState<CardState>({ 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 }
}
@@ -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<typeof useT>
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<CardState, { status: 'failed' }>
onRetry: () => void
retryRef: Ref<HTMLButtonElement>
/** 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 (
<>
<Notice
tone={refused ? 'error' : 'warning'}
icon={failure === 'network' ? 'wifi-off' : 'alert'}
live={false}
>
{integrity ? <strong className="font-semibold">{text}</strong> : text}
</Notice>
{retry && (
<div aria-live="polite" className="sr-only">
{!retrying && attempt > 0 ? text : ''}
</div>
)}
<div className="mt-auto flex flex-wrap gap-2">
{retry && (
<Button
ref={retryRef}
type="button"
variant="secondary"
className="min-h-11"
aria-disabled={retrying ? 'true' : undefined}
onClick={onRetry}
>
{failure === 'core_unavailable' ? t('sheet.core_retry') : t('common.retry')}
</Button>
)}
{children}
</div>
</>
)
}
@@ -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 (
<ButtonLink
to={`/app/anatomy/${sheetId}`}
variant="secondary"
className="min-h-11 gap-2"
aria-label={t('catalogue.view_sheet').replace('{name}', name)}
>
<Icon name="eye" size={18} />
{t('catalogue.view')}
</ButtonLink>
)
}
/**
* 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<HTMLLIElement>(null)
const lastRetry = useRef<HTMLButtonElement | null>(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 = <ConsultLink sheetId={entry.sheet_id} name={name} />
return (
<>
<p className="text-sm text-[var(--color-ink-muted)]">
{versionLine(entry, details, locale, t)}
</p>
{details?.thumbnail && (
<img
src={details.thumbnail}
alt=""
className="aspect-[16/9] w-full rounded-xl bg-[var(--color-surface-strong)] object-contain"
/>
)}
{details?.viewRefused && (
<Notice tone="info" live={false}>
{t('catalogue.failure.view')}
</Notice>
)}
{state.status === 'failed' ? (
<CardFailure failed={state} onRetry={onRetry} retryRef={retryRef}>
{consult}
</CardFailure>
) : (
<div className="mt-auto">{consult}</div>
)}
</>
)
}
/**
* 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 (
<li>
<Card as="article" className="flex h-full flex-col gap-3 p-5">
<li ref={item}>
<Card
as="article"
className="flex h-full flex-col gap-3 p-5"
aria-busy={(state.status === 'failed' && state.retrying) || undefined}
>
<div className="flex items-center justify-between gap-2">
<Badge>{speciesName}</Badge>
<span className="inline-flex items-center gap-1 rounded-md bg-[color-mix(in_srgb,var(--severity-mild)_14%,white)] px-2 py-0.5 text-xs font-medium text-[#3f5e3f]">
@@ -52,25 +158,13 @@ export default function CatalogueCard({
</span>
</div>
<h2 className="font-serif text-xl text-[var(--color-ink)]">{name}</h2>
<p className="text-sm text-[var(--color-ink-muted)]">{line}</p>
{details?.thumbnail && (
<img
src={details.thumbnail}
alt=""
className="aspect-[16/9] w-full rounded-xl bg-[var(--color-surface-strong)] object-contain"
/>
)}
<div className="mt-auto">
<ButtonLink
to={`/app/anatomy/${entry.sheet_id}`}
variant="secondary"
className="min-h-11 gap-2"
aria-label={t('catalogue.view_sheet').replace('{name}', name)}
>
<Icon name="eye" size={18} />
{t('catalogue.view')}
</ButtonLink>
</div>
<CardContent
entry={entry}
name={name}
state={state}
onRetry={retry}
retryRef={retryRef}
/>
</Card>
</li>
)
+4
View File
@@ -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 (
<Tag
aria-labelledby={labelledBy}
aria-busy={busy}
className={[
'rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] shadow-sm',
className,
+1
View File
@@ -1160,6 +1160,7 @@ export const en: Dict = {
'catalogue.card.views_other': '{count} views',
'catalogue.card.zones_one': '1 finding zone',
'catalogue.card.zones_other': '{count} finding zones',
'catalogue.card.integrity_failed': 'Integrity check failed: this version cannot be displayed.',
'catalogue.view': 'View',
'catalogue.view_sheet': 'View {name}',
'catalogue.loading_sheet': 'Loading the sheet…',
+1
View File
@@ -1191,6 +1191,7 @@ export const fr: Dict = {
'catalogue.card.views_other': '{count} vues',
'catalogue.card.zones_one': '1 zone de constats',
'catalogue.card.zones_other': '{count} zones de constats',
'catalogue.card.integrity_failed': "Contrôle d'intégrité échoué : cette version ne peut pas être affichée.",
'catalogue.view': 'Consulter',
'catalogue.view_sheet': 'Consulter {name}',
'catalogue.loading_sheet': 'Chargement de la fiche…',
+269 -2
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { PreviewState } from '@faunosteo/core-wasm/types'
@@ -16,11 +16,12 @@ import CatalogRoute from '@/app/routes/app/anatomy/CatalogRoute'
import SheetRoute from '@/app/routes/app/anatomy/SheetRoute'
import { coreRuntime } from '@/core/runtime'
import { CataloguePreview } from '@/catalogue/preview'
import { coreFailure, serverFailure } from '@/catalogue/failure'
import { cardFailure, coreFailure, serverFailure, type CatalogueFailure } from '@/catalogue/failure'
import { SheetFailure } from '@faunosteo/supabase'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
/**
* The catalogue screens (V1-2.5 slice I, boards 01 to 03) on a fake client and
@@ -139,6 +140,8 @@ describe('/app/anatomy', () => {
// 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<unknown> }
afterEach(() => vi.restoreAllMocks())
async function card(name: string): Promise<HTMLElement> {
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<void>((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<HTMLElement> {
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<CatalogueFailure, [integrity: boolean, refused: boolean]> = {
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()
})
})