From c0a5c8c7ced4499f9fe60db53efba90953ef9964 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 15 Oct 2026 01:03:16 +0200 Subject: [PATCH] feat(editor): the canvas tells an engine failure (retry) from a view it cannot draw (no retry) --- apps/app/src/anatomy/drawing.ts | 31 +++++++-- .../src/components/canvas/AnatomyCanvas.tsx | 29 ++++---- apps/app/src/i18n/en.ts | 2 + apps/app/src/i18n/fr.ts | 2 + apps/app/tests/helpers/svgTree.ts | 44 +++++++++++- apps/app/tests/unit/canvas.trees.test.tsx | 21 ++++-- .../unit/components.AnatomyCanvas.test.tsx | 67 ++++++++++++++++--- scripts/visual-canvas.mjs | 22 +++++- 8 files changed, 182 insertions(+), 36 deletions(-) diff --git a/apps/app/src/anatomy/drawing.ts b/apps/app/src/anatomy/drawing.ts index 5db5ce59..6c68f57e 100644 --- a/apps/app/src/anatomy/drawing.ts +++ b/apps/app/src/anatomy/drawing.ts @@ -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 -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 = 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 } } diff --git a/apps/app/src/components/canvas/AnatomyCanvas.tsx b/apps/app/src/components/canvas/AnatomyCanvas.tsx index b0b4ad2b..0bdd17bd 100644 --- a/apps/app/src/components/canvas/AnatomyCanvas.tsx +++ b/apps/app/src/components/canvas/AnatomyCanvas.tsx @@ -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(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" />
- {failed && ( + {failure && (
- {t('sheet.core_unavailable')} - + + {t(failure === 'engine' ? 'sheet.core_unavailable' : 'canvas.view_unavailable')} + + {failure === 'engine' && ( + + )}
)} diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 3273e69d..ac9051bb 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -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.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 87a1cf83..437a3db2 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -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é.", diff --git a/apps/app/tests/helpers/svgTree.ts b/apps/app/tests/helpers/svgTree.ts index 16edec15..02e532f6 100644 --- a/apps/app/tests/helpers/svgTree.ts +++ b/apps/app/tests/helpers/svgTree.ts @@ -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; 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 } diff --git a/apps/app/tests/unit/canvas.trees.test.tsx b/apps/app/tests/unit/canvas.trees.test.tsx index 5cf24685..fcf88199 100644 --- a/apps/app/tests/unit/canvas.trees.test.tsx +++ b/apps/app/tests/unit/canvas.trees.test.tsx @@ -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 { const { container, unmount } = render( undefined} />, @@ -68,9 +79,9 @@ async function mountedLayer(viewId: string, states: ViewStates): Promise { 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) }) }) diff --git a/apps/app/tests/unit/components.AnatomyCanvas.test.tsx b/apps/app/tests/unit/components.AnatomyCanvas.test.tsx index b8aeea5f..b3fe8576 100644 --- a/apps/app/tests/unit/components.AnatomyCanvas.test.tsx +++ b/apps/app/tests/unit/components.AnatomyCanvas.test.tsx @@ -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 { const bundle = await bundledSheet() @@ -22,8 +31,8 @@ async function sheetDrawing(svg: string): Promise { 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', () => { '', ) 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(' { 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( - '', - ) + const drawing = '' + const hostile = await sheetDrawing(drawing) + sessionStorage.setItem('osteo:draft', '{"kept":true}') const { container } = render( 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( + 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('') + const first = render( + undefined} />, + ) + await screen.findByText(en['canvas.view_unavailable']!) + first.unmount() + const down = Object.create(sheet) as SheetIndex + down.canvasSvg = () => ({ ok: false, kind: 'internal' }) + render( 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 () => { diff --git a/scripts/visual-canvas.mjs b/scripts/visual-canvas.mjs index 03747755..1250df16 100644 --- a/scripts/visual-canvas.mjs +++ b/scripts/visual-canvas.mjs @@ -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()})`) }