Files
faunosteo/apps/app/tests/unit/components.AnatomyCanvas.test.tsx
bchanot 6371523f8c fix(editor): honest stopped state when the draft is unsaved; no dead retry
0279953 chose the stopped message from CoreRuntime.stopped alone: it
promised the report was kept even when the tab's storage refused the
draft (export, the banner's advice, needs the core), four surfaces still
offered a retry that could not work, and a failed recovery below the cap
was a dead end since nothing called retry().

The runtime restarts a failed recovery on the next call (compiled module
reused, cap still counts traps) and notifies status listeners. One
CoreStoppedNotice on the editor, Home, New report and the full-page
notice: reload when saved, else core.stopped_unsaved with a core-free
copy download (also on the storage-full banner) and a beforeunload
guard. Export, import and new report say the stopped message; a core
failure reading an unread draft is FAILED, not held. ESLint census of
the failure keys; core.stopped says "plusieurs erreurs".
2026-10-16 18:26:10 +02:00

253 lines
11 KiB
TypeScript

import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import { coreRuntime } from '@/core/runtime'
import { coreFailureMessage } from '@/core/failure'
import { useReportStore } from '@/state/reportStore'
import { buildViewSvg } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import { controlStopped } from '../helpers/core'
import { bundledSheet, loadTestSheet, minimalReport, sheetFromBundle } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
afterEach(cleanup)
/** The composed view, or a test failure naming why it is missing. */
function svgOf(index: SheetIndex, viewId: string): SVGSVGElement {
const build = buildViewSvg(index, viewId)
if (!build.ok) throw new Error(`${viewId}: ${build.failure}`)
return build.svg
}
/** The bundled sheet with its drawing replaced by `svg` (a hostile asset). */
async function sheetDrawing(svg: string): Promise<SheetIndex> {
const bundle = await bundledSheet()
const assets = Object.fromEntries(Object.keys(bundle.assets).map((id) => [id, svg]))
return sheetFromBundle({ ...bundle, assets })
}
describe('buildViewSvg', () => {
it('frames the main view on the asset box and the head view on its crop of the same drawing', () => {
const main = svgOf(sheet, 'main')
const head = svgOf(sheet, 'head')
expect(main.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
expect(head.getAttribute('viewBox')).toBe('60 100 500 380')
expect(main.querySelectorAll('path').length).toBe(
head.querySelectorAll('path').length,
)
expect(main.querySelectorAll('[data-layer="annotations"]')).toHaveLength(1)
expect(main.querySelectorAll('[data-anno-id="hip"]')).toHaveLength(2)
expect(head.querySelectorAll('[data-anno-id="hip"]')).toHaveLength(0)
expect(head.querySelectorAll('[data-anno-id="atm"]')).toHaveLength(2)
expect(main.hasAttribute('width')).toBe(false)
})
it('composes the view once per sheet (a constant text) and carries no state', () => {
expect(sheet.canvasSvg('main')).toEqual(sheet.canvasSvg('main'))
expect(svgOf(sheet, 'main').querySelector('[data-state]')).toBeNull()
})
it('refuses a drawing the core would have to alter: nothing of it reaches the page (LRN-025)', async () => {
const hostile = await sheetDrawing(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><script>alert(1)</script><g onclick="x()"><a href="javascript:void(0)"><path d="M0 0"/></a></g><foreignObject/></svg>',
)
expect(hostile.canvasSvg('main')).toMatchObject({ ok: false, kind: 'svg_rejected' })
expect(buildViewSvg(hostile, 'main')).toEqual({ ok: false, failure: 'view' })
const malformed = await sheetDrawing('<not svg')
expect(malformed.canvasSvg('main')).toMatchObject({
ok: false,
kind: 'svg_rejected',
detail: 'malformed',
})
})
})
describe('AnatomyCanvas', () => {
it('renders the view and delegates clicks on the generated markers to onZoneClick with the view id', async () => {
const onZoneClick = vi.fn()
const { container } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={onZoneClick}
/>,
)
await waitFor(() =>
expect(
container.querySelector('[data-anno-id="head-trigger"]'),
).not.toBeNull(),
)
const hip = container.querySelector('circle[data-anno-id="hip"]')!
hip.dispatchEvent(new Event('click', { bubbles: true }))
expect(onZoneClick).toHaveBeenCalledWith('hip', 'main')
container
.querySelector('path')!
.dispatchEvent(new Event('click', { bubbles: true }))
expect(onZoneClick).toHaveBeenCalledTimes(1)
})
it('applies the states right after the build, on both elements of a point', async () => {
const { container } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map([['stifle', 'current']])}
onZoneClick={() => undefined}
/>,
)
await waitFor(() =>
expect(container.querySelector('[data-anno-id="stifle"]')).not.toBeNull(),
)
const marked = Array.from(
container.querySelectorAll('[data-state="current"]'),
).map((el) => el.getAttribute('data-anno-id'))
expect(marked).toEqual(['stifle', 'stifle'])
})
it('names a view it cannot draw, offers no retry and keeps the drawing and the draft as they are', async () => {
useLocaleStore.setState({ locale: 'fr' })
const drawing = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'
const hostile = await sheetDrawing(drawing)
sessionStorage.setItem('osteo:draft', '{"kept":true}')
const { container } = render(
<AnatomyCanvas index={hostile} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(fr['canvas.view_unavailable']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
expect(container.querySelector('script, [data-layer], [data-anno-id]')).toBeNull()
// The refused drawing stays the bundle's own text; the session is untouched.
expect(hostile.canvasSvg('main')).toMatchObject({ ok: false, kind: 'svg_rejected' })
expect(sessionStorage.getItem('osteo:draft')).toBe('{"kept":true}')
})
it('offers a retry when the engine did not run, and draws the view once it does', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
let engineDown = true
const flaky = Object.create(sheet) as SheetIndex
flaky.canvasSvg = (viewId: string) =>
engineDown ? { ok: false, kind: 'core_unavailable' } : sheet.canvasSvg(viewId)
const { container } = render(
<AnatomyCanvas index={flaky} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(fr['sheet.core_unavailable']!)
expect(screen.queryByText(fr['canvas.view_unavailable']!)).toBeNull()
engineDown = false
const retry = vi.spyOn(coreRuntime(), 'retry')
await user.click(screen.getByRole('button', { name: fr['sheet.core_retry'] }))
// The engine is restarted first, then the view is built again.
expect(retry).toHaveBeenCalledTimes(1)
await waitFor(() => expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull())
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
retry.mockRestore()
})
it('after the recoveries are spent, shows the final state with no retry; alerts say the same', async () => {
useLocaleStore.setState({ locale: 'fr' })
const setStopped = controlStopped(coreRuntime(), true)
try {
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'internal' })
render(<AnatomyCanvas index={down} viewId="main" states={new Map()} onZoneClick={() => undefined} />)
await screen.findByText(fr['core.stopped']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.stopped'])
} finally {
setStopped(false)
}
expect(coreFailureMessage((k: string) => fr[k]!)).toBe(fr['core.action_failed'])
expect(coreFailureMessage((k: string) => fr[k]!, 'editor.export_failed')).toBe(
fr['editor.export_failed'],
)
})
it('switches a shown engine failure to the stopped text when the engine stops, per save state', async () => {
useLocaleStore.setState({ locale: 'fr' })
const setStopped = controlStopped(coreRuntime(), false)
try {
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'core_unavailable' })
render(<AnatomyCanvas index={down} viewId="main" states={new Map()} onZoneClick={() => undefined} />)
await screen.findByText(fr['sheet.core_unavailable']!)
expect(screen.getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument()
act(() => setStopped(true))
await screen.findByText(fr['core.stopped']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
// The draft mirror hits a full storage: the report only lives in memory.
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => useReportStore.setState({ report: minimalReport(sheet) }))
expect(useReportStore.getState().saveFailed).toBe(true)
await screen.findByText(fr['core.stopped_unsaved']!)
expect(screen.queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(
coreFailureMessage((k: string) => fr[k]!, 'editor.export_failed'),
).toBe(fr['core.stopped_unsaved'])
} finally {
setStopped(false)
vi.restoreAllMocks()
useReportStore.setState({ report: null, saveFailed: false })
}
})
it('words both failures in English too', async () => {
useLocaleStore.setState({ locale: 'en' })
const hostile = await sheetDrawing('<svg xmlns="http://www.w3.org/2000/svg"><script/></svg>')
const first = render(
<AnatomyCanvas index={hostile} viewId="main" states={new Map()} onZoneClick={() => undefined} />,
)
await screen.findByText(en['canvas.view_unavailable']!)
first.unmount()
const down = Object.create(sheet) as SheetIndex
down.canvasSvg = () => ({ ok: false, kind: 'internal' })
render(<AnatomyCanvas index={down} viewId="main" states={new Map()} onZoneClick={() => undefined} />)
await screen.findByText(en['sheet.core_unavailable']!)
expect(screen.getByRole('button', { name: en['sheet.core_retry'] })).toBeInTheDocument()
useLocaleStore.setState({ locale: 'fr' })
})
it('restyles in place when the states change', async () => {
const { container, rerender } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={() => undefined}
/>,
)
await waitFor(() =>
expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull(),
)
rerender(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map([['hip', 'current']])}
onZoneClick={() => undefined}
/>,
)
expect(
container.querySelectorAll('[data-anno-id="hip"][data-state="current"]'),
).toHaveLength(2)
rerender(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={() => undefined}
/>,
)
expect(container.querySelectorAll('[data-state="current"]')).toHaveLength(0)
})
})