diff --git a/apps/app/package.json b/apps/app/package.json index 770946bf..2ee3ea6a 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -15,7 +15,6 @@ "report:compare": "tsx scripts/compare-reports.ts" }, "dependencies": { - "@faunosteo/anatomy": "workspace:*", "@faunosteo/core-wasm": "workspace:*", "@faunosteo/domain": "workspace:*", "@faunosteo/pdf": "workspace:*", diff --git a/apps/app/src/anatomy/drawing.ts b/apps/app/src/anatomy/drawing.ts index 2f47af67..5db5ce59 100644 --- a/apps/app/src/anatomy/drawing.ts +++ b/apps/app/src/anatomy/drawing.ts @@ -1,97 +1,20 @@ -import { - createLayerElement, - renderAnnotationLayer, - viewBoxOf, -} from '@faunosteo/anatomy/render' -import type { SheetView } from '@faunosteo/core-wasm/types' import type { SheetIndex } from '@/services/sheetIndex' /** - * Builds the inline SVG of one view: the sheet's drawing (sanitised asset - * text) framed on the view's box, plus the annotation layer generated from - * the document. The drawing is parsed once per asset and cloned per view. + * 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. */ -const SVG_NS = 'http://www.w3.org/2000/svg' -const FORBIDDEN_TAGS = ['script', 'foreignObject', 'iframe', 'object', 'embed'] - export type ViewStates = ReadonlyMap -/** Drops scripts, embedded documents, event handlers and script URLs (LRN-025). */ -export function sanitizeSvg(root: Element): void { - for (const tag of FORBIDDEN_TAGS) { - for (const el of Array.from(root.getElementsByTagName(tag))) el.remove() - } - for (const el of Array.from(root.querySelectorAll('*'))) { - for (const attr of Array.from(el.attributes)) { - const name = attr.name.toLowerCase() - const value = attr.value.trim().toLowerCase() - if (name.startsWith('on') || value.startsWith('javascript:')) { - el.removeAttribute(attr.name) - } - } - } -} - -export function parseDrawing(svgText: string): SVGSVGElement { - const doc = new DOMParser().parseFromString(svgText, 'image/svg+xml') - if (doc.querySelector('parsererror')) throw new Error('invalid SVG asset') - const root = doc.documentElement - if (root.tagName.toLowerCase() !== 'svg') - throw new Error('asset root is not ') - sanitizeSvg(root) - return root as unknown as SVGSVGElement -} - -const parsed = new Map() - -function drawingOf(index: SheetIndex, assetId: string): SVGSVGElement { - const key = `${index.sheet.ref.documentSha256}:${assetId}` - let root = parsed.get(key) - if (!root) { - const text = index.sheet.assets[assetId] - if (text === undefined) throw new Error(`asset ${assetId} not bundled`) - root = parseDrawing(text) - parsed.set(key, root) - } - return root -} - -/** The asset a view draws: its own, else its parent's (a crop). */ -export function assetOfView(index: SheetIndex, view: SheetView): string { - if (view.svg_asset_id) return view.svg_asset_id - if (view.kind === 'detail') { - const parent = index.view(view.parent_view_id) - if (parent) return assetOfView(index, parent) - } - throw new Error(`view ${view.id} has no asset`) -} - -export function buildViewSvg( - index: SheetIndex, - viewId: string, - states: ViewStates, -): SVGSVGElement { - const view = index.view(viewId) - if (!view) throw new Error(`unknown view ${viewId}`) - const source = drawingOf(index, assetOfView(index, view)) - const svg = document.createElementNS(SVG_NS, 'svg') - for (const attr of Array.from(source.attributes)) { - if (attr.name === 'width' || attr.name === 'height') continue - svg.setAttribute(attr.name, attr.value) - } - svg.setAttribute( - 'viewBox', - viewBoxOf(view) ?? source.getAttribute('viewBox') ?? '0 0 100 100', - ) - for (const child of Array.from(source.childNodes)) { - svg.appendChild(document.importNode(child, true)) - } - const layer = renderAnnotationLayer({ - document: index.sheet.document, - viewId, - states, - }) - svg.appendChild(createLayerElement(document, layer) as unknown as Node) - return svg +export function buildViewSvg(index: SheetIndex, viewId: string): SVGSVGElement | null { + const text = index.canvasSvg(viewId) + if (!text.ok) return null + 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 } diff --git a/apps/app/src/components/canvas/AnatomyCanvas.tsx b/apps/app/src/components/canvas/AnatomyCanvas.tsx index 3b321bcc..b0b4ad2b 100644 --- a/apps/app/src/components/canvas/AnatomyCanvas.tsx +++ b/apps/app/src/components/canvas/AnatomyCanvas.tsx @@ -1,8 +1,11 @@ -import { useCallback, useEffect, useLayoutEffect, useRef } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import { buildViewSvg, type ViewStates } from '@/anatomy/drawing' import type { SheetIndex } from '@/services/sheetIndex' import { useLocaleStore } from '@/state/localeStore' import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import { useT } from '@/i18n/useT' export interface AnatomyCanvasProps { index: SheetIndex @@ -20,9 +23,11 @@ function annotatedTarget(event: Event): Element | null { } /** - * One view of the sheet: the drawing plus the annotation layer generated - * from the document, rebuilt when the view changes and restyled in place - * when the selection changes. Clicks are delegated on `data-anno-id`. + * 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. */ export default function AnatomyCanvas({ index, @@ -35,17 +40,18 @@ export default function AnatomyCanvas({ const svgRef = useRef(null) const tooltipRef = useRef(null) const locale = useLocaleStore((s) => s.locale) - // Latest states for the build effect, which must only re-run on a view change. - const statesRef = useRef(states) - useLayoutEffect(() => { - statesRef.current = states - }, [states]) + 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) useEffect(() => { const host = svgRef.current if (!host) return - host.replaceChildren(buildViewSvg(index, viewId, statesRef.current)) - }, [index, viewId]) + const svg = buildViewSvg(index, viewId) + setFailed(svg === null) + host.replaceChildren(...(svg ? [svg] : [])) + }, [index, viewId, attempt]) useEffect(() => { const host = svgRef.current @@ -55,7 +61,7 @@ export default function AnatomyCanvas({ if (state) el.setAttribute('data-state', state) else el.removeAttribute('data-state') }) - }, [states, index, viewId]) + }, [states, index, viewId, attempt]) useEffect(() => { const host = svgRef.current @@ -123,6 +129,16 @@ export default function AnatomyCanvas({ className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto" />
+ {failed && ( +
+
+ {t('sheet.core_unavailable')} + +
+
+ )}
) } diff --git a/apps/app/src/core/sheetOps.ts b/apps/app/src/core/sheetOps.ts index 07bb144b..95b34c57 100644 --- a/apps/app/src/core/sheetOps.ts +++ b/apps/app/src/core/sheetOps.ts @@ -1,6 +1,7 @@ import type { CoreOutcome, SheetSession } from '@faunosteo/core-wasm' import type { ArchiveImport, + CanvasView, DraftRestore, LateralSide, Observation, @@ -89,6 +90,15 @@ export class SheetOps { return this.run('archive.import', attachment) } + /** + * The editor canvas of a view: the sheet's drawing, sanitised once at load, with the + * annotation layer (R3). Failures: `unknown_view`, `no_asset`, `svg_rejected` (the reason + * in `detail`), `invalid_character`. + */ + canvasView(viewId: string): CoreOutcome { + return this.run('view.canvas', { viewId }) + } + /** The snapshot of this sheet an archive of `report` carries. */ snapshot(report: Report): CoreOutcome { return this.run('archive.snapshot', { report }) diff --git a/apps/app/src/services/sheetIndex.ts b/apps/app/src/services/sheetIndex.ts index e7d6fd04..1c7323c3 100644 --- a/apps/app/src/services/sheetIndex.ts +++ b/apps/app/src/services/sheetIndex.ts @@ -10,6 +10,7 @@ import type { SheetView, VertebralRegion, } from '@faunosteo/core-wasm/types' +import type { CoreOutcome } from '@faunosteo/core-wasm' import type { SheetOps } from '@/core/sheetOps' /** @@ -29,8 +30,6 @@ export interface LoadedSheetView { schemaVersion: number /** The document as the core parsed it (defaults filled in). */ document: AnatomicalSheetDocument - /** SVG text by `svg_asset_id` (the canvas draws them until R3). */ - assets: Readonly> } function at( @@ -53,10 +52,11 @@ export class SheetIndex { readonly mainViewId: string private readonly spine: ReadonlySet private readonly nodes: ReadonlySet + /** The composed canvas of each view: constant for a loaded sheet, composed once (R3). */ + private readonly canvases = new Map() constructor( private readonly data: SheetIndexData, - assets: Readonly>, readonly ops: SheetOps, ) { const { document } = data @@ -66,13 +66,22 @@ export class SheetIndex { speciesId: data.speciesId, schemaVersion: data.schemaVersion, document, - assets, } this.mainViewId = data.mainViewId this.spine = new Set(data.spineIds) this.nodes = new Set(data.nodeKeys) } + /** The SVG text of a view's canvas (sanitised drawing + annotation layer), from the core. */ + canvasSvg(viewId: string): CoreOutcome { + const known = this.canvases.get(viewId) + if (known !== undefined) return { ok: true, value: known } + const outcome = this.ops.canvasView(viewId) + if (!outcome.ok) return outcome + this.canvases.set(viewId, outcome.value.svg) + return { ok: true, value: outcome.value.svg } + } + view(id: string): SheetView | undefined { return at(this.data.document.views, this.data.viewById, id) } diff --git a/apps/app/src/sheets/useSheet.ts b/apps/app/src/sheets/useSheet.ts index 67fe1945..388e5ea9 100644 --- a/apps/app/src/sheets/useSheet.ts +++ b/apps/app/src/sheets/useSheet.ts @@ -49,7 +49,7 @@ async function loadIntoCore(speciesId: string): Promise { const session = coreRuntime().sheet(JSON.stringify(bundle)) const data = session.call('index_data', '') if (data.ok) { - const index = new SheetIndex(data.value, bundle.assets, new SheetOps(session)) + const index = new SheetIndex(data.value, new SheetOps(session)) return { status: 'ready', index } } return { diff --git a/apps/app/tests/helpers/sheet.ts b/apps/app/tests/helpers/sheet.ts index 4f6d9c8b..08a2455e 100644 --- a/apps/app/tests/helpers/sheet.ts +++ b/apps/app/tests/helpers/sheet.ts @@ -132,5 +132,5 @@ export function sheetFromBundle(bundle: BundledSheetData): SheetIndex { const session = coreRuntime().sheet(JSON.stringify(bundle)) const data = session.call('index_data', '') if (!data.ok) throw new Error(`sheet refused by the core: ${data.kind}`) - return new SheetIndex(data.value, bundle.assets, new SheetOps(session)) + return new SheetIndex(data.value, new SheetOps(session)) } diff --git a/apps/app/tests/unit/canvas.trees.test.ts b/apps/app/tests/unit/canvas.trees.test.tsx similarity index 56% rename from apps/app/tests/unit/canvas.trees.test.ts rename to apps/app/tests/unit/canvas.trees.test.tsx index 5261ed9d..5cf24685 100644 --- a/apps/app/tests/unit/canvas.trees.test.ts +++ b/apps/app/tests/unit/canvas.trees.test.tsx @@ -1,14 +1,15 @@ /** - * R3 freeze O1 (plan 2026-10-14 §3): the editor canvas as the TypeScript - * built it before the anatomy core moved to Rust. For each view, the whole - * tree with no state (root attributes, the drawing's nodes, the layer), and - * for every state set the editor can produce from the three reference - * reports (each observation active, zones of every view, as EditorRoute - * builds them) plus "every annotation", the annotation layer. After the - * switch the same assertions hold on the Rust composition: trees compared by - * structure and semantic properties, never by bytes or attribute order. + * R3 freeze O1 (plan 2026-10-14 §3), now the switch's oracle: the editor canvas as the + * TypeScript built it before the anatomy core moved to Rust (frozen at 47c5f49, never + * regenerated to make this pass). For each view, the whole tree with no state; for every + * state set the editor can produce from the three reference reports (each observation + * active, zones of every view, as EditorRoute builds them) plus "every annotation", the + * annotation layer of the mounted canvas (the core composes, the canvas restyles in place). + * Trees compared by structure and semantic properties, never by bytes or attribute order. */ -import { beforeAll, describe, expect, it } from 'vitest' +import { afterEach, beforeAll, describe, expect, it } from 'vitest' +import { cleanup, render, waitFor } from '@testing-library/react' +import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import { buildViewSvg, type ViewStates } from '@/anatomy/drawing' import type { SheetIndex } from '@/services/sheetIndex' import { loadTestSheet } from '../helpers/sheet' @@ -25,6 +26,7 @@ beforeAll(async () => { sheet = await loadTestSheet() golden = buildGoldenReports(sheet) }) +afterEach(cleanup) const VIEWS = ['main', 'head'] as const @@ -54,16 +56,27 @@ function layerOf(tree: TreeNode): TreeNode { return last } +async function mountedLayer(viewId: string, states: ViewStates): Promise { + const { container, unmount } = render( + undefined} />, + ) + await waitFor(() => expect(container.querySelector('svg')).not.toBeNull()) + const layer = layerOf(treeOf(container.querySelector('svg')!)) + unmount() + return layer +} + describe.each(VIEWS)('the %s canvas', (viewId) => { it('builds the frozen tree with no state', () => { - const tree = treeOf(buildViewSvg(sheet, viewId, new Map())) - checkR3Golden(`canvas.${viewId}.json`, tree) + const svg = buildViewSvg(sheet, viewId) + expect(svg).not.toBeNull() + checkR3Golden(`canvas.${viewId}.json`, treeOf(svg!)) }) - it('builds the frozen layer for every state set of the reference reports', () => { + it('shows the frozen layer for every state set of the reference reports', async () => { const layers: Record = {} for (const [name, states] of stateCases()) { - layers[name] = layerOf(treeOf(buildViewSvg(sheet, viewId, states))) + layers[name] = await mountedLayer(viewId, states) } expect(Object.keys(layers).length).toBeGreaterThan(8) checkR3Golden(`canvas.${viewId}.layers.json`, layers) diff --git a/apps/app/tests/unit/components.AnatomyCanvas.test.tsx b/apps/app/tests/unit/components.AnatomyCanvas.test.tsx index 4e7dacdf..b8aeea5f 100644 --- a/apps/app/tests/unit/components.AnatomyCanvas.test.tsx +++ b/apps/app/tests/unit/components.AnatomyCanvas.test.tsx @@ -1,9 +1,11 @@ import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest' -import { cleanup, render, waitFor } from '@testing-library/react' +import { cleanup, render, screen, waitFor } from '@testing-library/react' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' -import { buildViewSvg, parseDrawing, sanitizeSvg } from '@/anatomy/drawing' +import { buildViewSvg } from '@/anatomy/drawing' import type { SheetIndex } from '@/services/sheetIndex' -import { loadTestSheet } from '../helpers/sheet' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' +import { bundledSheet, loadTestSheet, sheetFromBundle } from '../helpers/sheet' let sheet: SheetIndex beforeAll(async () => { @@ -11,10 +13,17 @@ beforeAll(async () => { }) afterEach(cleanup) +/** The bundled sheet with its drawing replaced by `svg` (a hostile asset). */ +async function sheetDrawing(svg: string): Promise { + 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 = buildViewSvg(sheet, 'main', new Map()) - const head = buildViewSvg(sheet, 'head', new Map()) + const main = buildViewSvg(sheet, 'main')! + const head = buildViewSvg(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( @@ -27,25 +36,23 @@ describe('buildViewSvg', () => { expect(main.hasAttribute('width')).toBe(false) }) - it('applies states as data-state on the generated markers', () => { - const svg = buildViewSvg(sheet, 'main', new Map([['stifle', 'current']])) - const marked = Array.from( - svg.querySelectorAll('[data-state="current"]'), - ).map((el) => el.getAttribute('data-anno-id')) - expect(marked).toEqual(['stifle', 'stifle']) + 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() }) - it('sanitises scripts, embedded documents and handlers out of an asset', () => { - const root = parseDrawing( + it('refuses a drawing the core would have to alter: nothing of it reaches the page (LRN-025)', async () => { + const hostile = await sheetDrawing( '', ) - sanitizeSvg(root) - expect(root.querySelector('script')).toBeNull() - expect(root.querySelector('foreignObject')).toBeNull() - expect(root.querySelector('g')!.hasAttribute('onclick')).toBe(false) - expect(root.querySelector('a')!.hasAttribute('href')).toBe(false) - expect(root.querySelector('path')).not.toBeNull() - expect(() => parseDrawing(' { expect(onZoneClick).toHaveBeenCalledTimes(1) }) + it('applies the states right after the build, on both elements of a point', async () => { + const { container } = render( + 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('shows the degraded notice for a drawing it cannot draw, and nothing of the drawing', async () => { + useLocaleStore.setState({ locale: 'fr' }) + const hostile = await sheetDrawing( + '', + ) + const { container } = render( + undefined} />, + ) + await screen.findByText(fr['sheet.core_unavailable']!) + expect(screen.getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument() + expect(container.querySelector('script, [data-layer], [data-anno-id]')).toBeNull() + }) + it('restyles in place when the states change', async () => { const { container, rerender } = render(