feat(editor): the canvas tells an engine failure (retry) from a view it cannot draw (no retry)
This commit is contained in:
1 parent
6882c6da4a
commit
c0a5c8c7ce
8 files changed
+182
-36
No files matched your search
@@ -4,17 +4,36 @@ import type { SheetIndex } from '@/services/sheetIndex'
|
||||
* The inline SVG of one view, as the core composed it (R3): the sheet's drawing, read and
|
||||
* sanitised by the core's allowlist at load, framed on the view, with the annotation layer
|
||||
* last (docs/ANNOTATION-RENDERING.md). The browser only parses the text (`DOMParser` never
|
||||
* runs scripts) and imports the tree into the page. `null` when the core or the parse
|
||||
* fails: the canvas shows its degraded notice.
|
||||
* runs scripts) and imports the tree into the page.
|
||||
*/
|
||||
|
||||
export type ViewStates = ReadonlyMap<string, 'current'>
|
||||
|
||||
export function buildViewSvg(index: SheetIndex, viewId: string): SVGSVGElement | null {
|
||||
/**
|
||||
* Why a view cannot be drawn: the engine did not run (a retry may succeed), or the view
|
||||
* itself cannot be drawn (a refused drawing, a view the core cannot compose: retrying
|
||||
* changes nothing). The technical kind stays in the core's outcome and the DEV console.
|
||||
*/
|
||||
export type ViewFailure = 'engine' | 'view'
|
||||
|
||||
export type ViewBuild = { ok: true; svg: SVGSVGElement } | { ok: false; failure: ViewFailure }
|
||||
|
||||
const ENGINE_KINDS: ReadonlySet<string> = new Set(['core_unavailable', 'internal'])
|
||||
|
||||
function failed(failure: ViewFailure, kind: string, detail?: string): ViewBuild {
|
||||
if (import.meta.env.DEV) console.warn(`canvas: ${kind}`, detail ?? '')
|
||||
return { ok: false, failure }
|
||||
}
|
||||
|
||||
export function buildViewSvg(index: SheetIndex, viewId: string): ViewBuild {
|
||||
const text = index.canvasSvg(viewId)
|
||||
if (!text.ok) return null
|
||||
if (!text.ok) {
|
||||
return failed(ENGINE_KINDS.has(text.kind) ? 'engine' : 'view', text.kind, text.detail)
|
||||
}
|
||||
const parsed = new DOMParser().parseFromString(text.value, 'image/svg+xml')
|
||||
const root = parsed.documentElement
|
||||
if (parsed.querySelector('parsererror') || root.localName !== 'svg') return null
|
||||
return document.importNode(root, true) as unknown as SVGSVGElement
|
||||
if (parsed.querySelector('parsererror') || root.localName !== 'svg') {
|
||||
return failed('view', 'parse')
|
||||
}
|
||||
return { ok: true, svg: document.importNode(root, true) as unknown as SVGSVGElement }
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { buildViewSvg, type ViewStates } from '@/anatomy/drawing'
|
||||
import { buildViewSvg, type ViewFailure, type ViewStates } from '@/anatomy/drawing'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
@@ -26,8 +26,9 @@ function annotatedTarget(event: Event): Element | null {
|
||||
* One view of the sheet: the drawing plus the annotation layer, composed by
|
||||
* the core (R3), rebuilt when the view changes and restyled in place when the
|
||||
* selection changes (the restyle runs right after every build). Clicks are
|
||||
* delegated on `data-anno-id`. When the core cannot compose the view, the
|
||||
* canvas shows the degraded notice with a retry.
|
||||
* delegated on `data-anno-id`. When the engine cannot run, the canvas shows the
|
||||
* degraded notice with a retry; when the view itself cannot be drawn (a drawing
|
||||
* refused or impossible to compose), a notice without retry: nothing would change.
|
||||
*/
|
||||
export default function AnatomyCanvas({
|
||||
index,
|
||||
@@ -43,14 +44,14 @@ export default function AnatomyCanvas({
|
||||
const t = useT()
|
||||
// Each retry builds again; a failed build leaves the canvas empty behind the notice.
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [failure, setFailure] = useState<ViewFailure | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const host = svgRef.current
|
||||
if (!host) return
|
||||
const svg = buildViewSvg(index, viewId)
|
||||
setFailed(svg === null)
|
||||
host.replaceChildren(...(svg ? [svg] : []))
|
||||
const build = buildViewSvg(index, viewId)
|
||||
setFailure(build.ok ? null : build.failure)
|
||||
host.replaceChildren(...(build.ok ? [build.svg] : []))
|
||||
}, [index, viewId, attempt])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -129,13 +130,17 @@ export default function AnatomyCanvas({
|
||||
className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto"
|
||||
/>
|
||||
<div ref={tooltipRef} className="zone-tooltip" style={{ opacity: 0 }} />
|
||||
{failed && (
|
||||
{failure && (
|
||||
<div className="absolute inset-0 grid place-items-center p-4">
|
||||
<div className="space-y-3 max-w-sm">
|
||||
<Notice tone="error">{t('sheet.core_unavailable')}</Notice>
|
||||
<Button onClick={() => setAttempt((n) => n + 1)}>
|
||||
{t('sheet.core_retry')}
|
||||
</Button>
|
||||
<Notice tone="error">
|
||||
{t(failure === 'engine' ? 'sheet.core_unavailable' : 'canvas.view_unavailable')}
|
||||
</Notice>
|
||||
{failure === 'engine' && (
|
||||
<Button onClick={() => setAttempt((n) => n + 1)}>
|
||||
{t('sheet.core_retry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -201,6 +201,8 @@ export const en: Dict = {
|
||||
'sheet.core_unavailable':
|
||||
"Faunosteo's computation engine could not be loaded. Your session data is kept.",
|
||||
'sheet.core_retry': 'Retry',
|
||||
'canvas.view_unavailable':
|
||||
"This anatomical view cannot be displayed: its drawing was refused by the safety checks or could not be composed. Your report is not changed.",
|
||||
'core.action_failed':
|
||||
'This action could not be applied. Try again; your report was not changed.',
|
||||
|
||||
|
||||
@@ -215,6 +215,8 @@ export const fr: Dict = {
|
||||
'sheet.core_unavailable':
|
||||
"Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées.",
|
||||
'sheet.core_retry': 'Réessayer',
|
||||
'canvas.view_unavailable':
|
||||
"Cette vue anatomique ne peut pas être affichée : son dessin a été refusé par les contrôles de sécurité ou n'a pas pu être composé. Votre bilan n'est pas modifié.",
|
||||
'core.action_failed':
|
||||
"Cette action n'a pas pu être appliquée. Réessayez ; votre bilan n'a pas été modifié.",
|
||||
|
||||
|
||||
@@ -52,12 +52,52 @@ export const R3_GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/r3')
|
||||
/** `MAKE_R3_GOLDEN=1` writes the R3 freeze; never set it without the owner's decision once frozen. */
|
||||
export const MAKE_R3_GOLDEN = process.env.MAKE_R3_GOLDEN === '1'
|
||||
|
||||
export function checkR3Golden(name: string, actual: unknown): void {
|
||||
/**
|
||||
* Compares `actual` with the frozen R3 golden `name`. `declared` applies an owner-validated
|
||||
* change to the frozen value before comparing (the file itself never changes); with one,
|
||||
* rewriting the golden is refused.
|
||||
*/
|
||||
export function checkR3Golden(
|
||||
name: string,
|
||||
actual: unknown,
|
||||
declared?: (frozen: unknown) => unknown,
|
||||
): void {
|
||||
const file = resolve(R3_GOLDEN_DIR, name)
|
||||
if (MAKE_R3_GOLDEN && declared) throw new Error(`${name}: frozen, a declared change applies`)
|
||||
if (MAKE_R3_GOLDEN) {
|
||||
mkdirSync(R3_GOLDEN_DIR, { recursive: true })
|
||||
writeFileSync(file, `${JSON.stringify(actual, null, 1)}\n`)
|
||||
return
|
||||
}
|
||||
expect(actual, name).toEqual(JSON.parse(readFileSync(file, 'utf8')))
|
||||
const frozen: unknown = JSON.parse(readFileSync(file, 'utf8'))
|
||||
expect(actual, name).toEqual(declared ? declared(frozen) : frozen)
|
||||
}
|
||||
|
||||
export interface ViewName {
|
||||
id: string
|
||||
fr: string
|
||||
en: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner decision 2026-10-15 (R3): a trigger without a name of its own carries the opened
|
||||
* view's name in each language; the TypeScript freeze carries the French name twice. Applied
|
||||
* to a frozen tree (a deep copy): `data-anno-name-en` takes the English name and the title
|
||||
* text reads "FR / EN". Mirrors `crates/core/tests/common/svg_tree.rs`.
|
||||
*/
|
||||
export function withTriggerNamesPerLanguage(tree: unknown, views: readonly ViewName[]): unknown {
|
||||
const copy = structuredClone(tree)
|
||||
const visit = (node: unknown): void => {
|
||||
if (typeof node !== 'object' || node === null) return
|
||||
const n = node as { attrs?: Record<string, string>; text?: string; children?: unknown[] }
|
||||
const view = views.find((v) => v.id === n.attrs?.['data-anno-opens-view'])
|
||||
if (view && n.attrs?.['data-anno-name-en'] === view.fr) n.attrs['data-anno-name-en'] = view.en
|
||||
for (const v of views) {
|
||||
if (n.text === `${v.fr} / ${v.fr}`) n.text = `${v.fr} / ${v.en}`
|
||||
}
|
||||
n.children?.forEach(visit)
|
||||
if (!('attrs' in n) && !('children' in n)) Object.values(n).forEach(visit)
|
||||
}
|
||||
visit(copy)
|
||||
return copy
|
||||
}
|
||||
@@ -18,7 +18,12 @@ import {
|
||||
GOLDEN_REPORTS,
|
||||
type GoldenReports,
|
||||
} from '../helpers/goldenReports'
|
||||
import { checkR3Golden, treeOf, type TreeNode } from '../helpers/svgTree'
|
||||
import {
|
||||
checkR3Golden,
|
||||
treeOf,
|
||||
withTriggerNamesPerLanguage,
|
||||
type TreeNode,
|
||||
} from '../helpers/svgTree'
|
||||
|
||||
let sheet: SheetIndex
|
||||
let golden: GoldenReports
|
||||
@@ -56,6 +61,12 @@ function layerOf(tree: TreeNode): TreeNode {
|
||||
return last
|
||||
}
|
||||
|
||||
/** The declared change of the owner's decision 2026-10-15, on the draft's views. */
|
||||
function declared(frozen: unknown): unknown {
|
||||
const views = sheet.sheet.document.views.map((v) => ({ id: v.id, ...v.name }))
|
||||
return withTriggerNamesPerLanguage(frozen, views)
|
||||
}
|
||||
|
||||
async function mountedLayer(viewId: string, states: ViewStates): Promise<TreeNode> {
|
||||
const { container, unmount } = render(
|
||||
<AnatomyCanvas index={sheet} viewId={viewId} states={states} onZoneClick={() => undefined} />,
|
||||
@@ -68,9 +79,9 @@ async function mountedLayer(viewId: string, states: ViewStates): Promise<TreeNod
|
||||
|
||||
describe.each(VIEWS)('the %s canvas', (viewId) => {
|
||||
it('builds the frozen tree with no state', () => {
|
||||
const svg = buildViewSvg(sheet, viewId)
|
||||
expect(svg).not.toBeNull()
|
||||
checkR3Golden(`canvas.${viewId}.json`, treeOf(svg!))
|
||||
const build = buildViewSvg(sheet, viewId)
|
||||
if (!build.ok) throw new Error(`canvas ${viewId}: ${build.failure}`)
|
||||
checkR3Golden(`canvas.${viewId}.json`, treeOf(build.svg), declared)
|
||||
})
|
||||
|
||||
it('shows the frozen layer for every state set of the reference reports', async () => {
|
||||
@@ -79,6 +90,6 @@ describe.each(VIEWS)('the %s canvas', (viewId) => {
|
||||
layers[name] = await mountedLayer(viewId, states)
|
||||
}
|
||||
expect(Object.keys(layers).length).toBeGreaterThan(8)
|
||||
checkR3Golden(`canvas.${viewId}.layers.json`, layers)
|
||||
checkR3Golden(`canvas.${viewId}.layers.json`, layers, declared)
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,12 @@
|
||||
import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest'
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
|
||||
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 { bundledSheet, loadTestSheet, sheetFromBundle } from '../helpers/sheet'
|
||||
|
||||
let sheet: SheetIndex
|
||||
@@ -13,6 +15,13 @@ beforeAll(async () => {
|
||||
})
|
||||
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()
|
||||
@@ -22,8 +31,8 @@ async function sheetDrawing(svg: string): Promise<SheetIndex> {
|
||||
|
||||
describe('buildViewSvg', () => {
|
||||
it('frames the main view on the asset box and the head view on its crop of the same drawing', () => {
|
||||
const main = buildViewSvg(sheet, 'main')!
|
||||
const head = buildViewSvg(sheet, 'head')!
|
||||
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(
|
||||
@@ -38,7 +47,7 @@ describe('buildViewSvg', () => {
|
||||
|
||||
it('composes the view once per sheet (a constant text) and carries no state', () => {
|
||||
expect(sheet.canvasSvg('main')).toEqual(sheet.canvasSvg('main'))
|
||||
expect(buildViewSvg(sheet, 'main')!.querySelector('[data-state]')).toBeNull()
|
||||
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 () => {
|
||||
@@ -46,7 +55,7 @@ describe('buildViewSvg', () => {
|
||||
'<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')).toBeNull()
|
||||
expect(buildViewSvg(hostile, 'main')).toEqual({ ok: false, failure: 'view' })
|
||||
const malformed = await sheetDrawing('<not svg')
|
||||
expect(malformed.canvasSvg('main')).toMatchObject({
|
||||
ok: false,
|
||||
@@ -99,17 +108,55 @@ describe('AnatomyCanvas', () => {
|
||||
expect(marked).toEqual(['stifle', 'stifle'])
|
||||
})
|
||||
|
||||
it('shows the degraded notice for a drawing it cannot draw, and nothing of the drawing', async () => {
|
||||
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 hostile = await sheetDrawing(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
|
||||
)
|
||||
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['sheet.core_unavailable']!)
|
||||
expect(screen.getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument()
|
||||
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
|
||||
await user.click(screen.getByRole('button', { name: fr['sheet.core_retry'] }))
|
||||
await waitFor(() => expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull())
|
||||
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
|
||||
})
|
||||
|
||||
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 () => {
|
||||
|
||||
@@ -102,6 +102,26 @@ function liveTree(selector) {
|
||||
return treeOf(document.querySelector(selector))
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner decision 2026-10-15: an unnamed trigger carries the opened view's name per language;
|
||||
* the freeze has the French name twice. Applied to the frozen tree before comparing
|
||||
* (apps/app/tests/helpers/svgTree.ts withTriggerNamesPerLanguage).
|
||||
*/
|
||||
function declared(frozen) {
|
||||
const doc = JSON.parse(readFileSync(resolve(import.meta.dirname,
|
||||
'../supabase/seed/anatomical-sheets/equine/draft/document.json'), 'utf8'))
|
||||
const views = doc.views.map((v) => ({ id: v.id, fr: v.name.fr, en: v.name.en }))
|
||||
const visit = (n) => {
|
||||
if (typeof n !== 'object' || n === null) return
|
||||
const view = views.find((v) => v.id === n.attrs?.['data-anno-opens-view'])
|
||||
if (view && n.attrs?.['data-anno-name-en'] === view.fr) n.attrs['data-anno-name-en'] = view.en
|
||||
for (const v of views) if (n.text === `${v.fr} / ${v.fr}`) n.text = `${v.fr} / ${v.en}`
|
||||
n.children?.forEach(visit)
|
||||
}
|
||||
visit(frozen)
|
||||
return frozen
|
||||
}
|
||||
|
||||
async function dom(base) {
|
||||
const { chromium } = require('playwright-core')
|
||||
const goldens = resolve(import.meta.dirname, '../apps/app/tests/fixtures/goldens/r3')
|
||||
@@ -117,7 +137,7 @@ async function dom(base) {
|
||||
let failed = 0
|
||||
for (const view of ['main', 'head']) {
|
||||
const frozen = readFileSync(join(goldens, `canvas.${view}.json`), 'utf8')
|
||||
const same = JSON.stringify(trees[view]) === JSON.stringify(JSON.parse(frozen))
|
||||
const same = JSON.stringify(trees[view]) === JSON.stringify(declared(JSON.parse(frozen)))
|
||||
if (!same) failed++
|
||||
console.log(`${same ? 'equal ' : 'DIFFERENT'} ${view} canvas vs the R3 O1 freeze (${browser.version()})`)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user