feat(editor): the canvas draws the view the Rust core composed; denylist and anatomy dependency removed
This commit is contained in:
1 parent
43a370aed1
commit
09a6cf7def
11 files changed
+165
-158
No files matched your search
@@ -15,7 +15,6 @@
|
|||||||
"report:compare": "tsx scripts/compare-reports.ts"
|
"report:compare": "tsx scripts/compare-reports.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@faunosteo/anatomy": "workspace:*",
|
|
||||||
"@faunosteo/core-wasm": "workspace:*",
|
"@faunosteo/core-wasm": "workspace:*",
|
||||||
"@faunosteo/domain": "workspace:*",
|
"@faunosteo/domain": "workspace:*",
|
||||||
"@faunosteo/pdf": "workspace:*",
|
"@faunosteo/pdf": "workspace:*",
|
||||||
|
|||||||
@@ -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'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds the inline SVG of one view: the sheet's drawing (sanitised asset
|
* The inline SVG of one view, as the core composed it (R3): the sheet's drawing, read and
|
||||||
* text) framed on the view's box, plus the annotation layer generated from
|
* sanitised by the core's allowlist at load, framed on the view, with the annotation layer
|
||||||
* the document. The drawing is parsed once per asset and cloned per view.
|
* 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<string, 'current'>
|
export type ViewStates = ReadonlyMap<string, 'current'>
|
||||||
|
|
||||||
/** Drops scripts, embedded documents, event handlers and script URLs (LRN-025). */
|
export function buildViewSvg(index: SheetIndex, viewId: string): SVGSVGElement | null {
|
||||||
export function sanitizeSvg(root: Element): void {
|
const text = index.canvasSvg(viewId)
|
||||||
for (const tag of FORBIDDEN_TAGS) {
|
if (!text.ok) return null
|
||||||
for (const el of Array.from(root.getElementsByTagName(tag))) el.remove()
|
const parsed = new DOMParser().parseFromString(text.value, 'image/svg+xml')
|
||||||
}
|
const root = parsed.documentElement
|
||||||
for (const el of Array.from(root.querySelectorAll('*'))) {
|
if (parsed.querySelector('parsererror') || root.localName !== 'svg') return null
|
||||||
for (const attr of Array.from(el.attributes)) {
|
return document.importNode(root, true) as unknown as SVGSVGElement
|
||||||
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 <svg>')
|
|
||||||
sanitizeSvg(root)
|
|
||||||
return root as unknown as SVGSVGElement
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsed = new Map<string, SVGSVGElement>()
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
@@ -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 { buildViewSvg, type ViewStates } from '@/anatomy/drawing'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
import { useLocaleStore } from '@/state/localeStore'
|
import { useLocaleStore } from '@/state/localeStore'
|
||||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
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 {
|
export interface AnatomyCanvasProps {
|
||||||
index: SheetIndex
|
index: SheetIndex
|
||||||
@@ -20,9 +23,11 @@ function annotatedTarget(event: Event): Element | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One view of the sheet: the drawing plus the annotation layer generated
|
* One view of the sheet: the drawing plus the annotation layer, composed by
|
||||||
* from the document, rebuilt when the view changes and restyled in place
|
* the core (R3), rebuilt when the view changes and restyled in place when the
|
||||||
* when the selection changes. Clicks are delegated on `data-anno-id`.
|
* 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({
|
export default function AnatomyCanvas({
|
||||||
index,
|
index,
|
||||||
@@ -35,17 +40,18 @@ export default function AnatomyCanvas({
|
|||||||
const svgRef = useRef<HTMLDivElement | null>(null)
|
const svgRef = useRef<HTMLDivElement | null>(null)
|
||||||
const tooltipRef = useRef<HTMLDivElement | null>(null)
|
const tooltipRef = useRef<HTMLDivElement | null>(null)
|
||||||
const locale = useLocaleStore((s) => s.locale)
|
const locale = useLocaleStore((s) => s.locale)
|
||||||
// Latest states for the build effect, which must only re-run on a view change.
|
const t = useT()
|
||||||
const statesRef = useRef(states)
|
// Each retry builds again; a failed build leaves the canvas empty behind the notice.
|
||||||
useLayoutEffect(() => {
|
const [attempt, setAttempt] = useState(0)
|
||||||
statesRef.current = states
|
const [failed, setFailed] = useState(false)
|
||||||
}, [states])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const host = svgRef.current
|
const host = svgRef.current
|
||||||
if (!host) return
|
if (!host) return
|
||||||
host.replaceChildren(buildViewSvg(index, viewId, statesRef.current))
|
const svg = buildViewSvg(index, viewId)
|
||||||
}, [index, viewId])
|
setFailed(svg === null)
|
||||||
|
host.replaceChildren(...(svg ? [svg] : []))
|
||||||
|
}, [index, viewId, attempt])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const host = svgRef.current
|
const host = svgRef.current
|
||||||
@@ -55,7 +61,7 @@ export default function AnatomyCanvas({
|
|||||||
if (state) el.setAttribute('data-state', state)
|
if (state) el.setAttribute('data-state', state)
|
||||||
else el.removeAttribute('data-state')
|
else el.removeAttribute('data-state')
|
||||||
})
|
})
|
||||||
}, [states, index, viewId])
|
}, [states, index, viewId, attempt])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const host = svgRef.current
|
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"
|
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 }} />
|
<div ref={tooltipRef} className="zone-tooltip" style={{ opacity: 0 }} />
|
||||||
|
{failed && (
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { CoreOutcome, SheetSession } from '@faunosteo/core-wasm'
|
import type { CoreOutcome, SheetSession } from '@faunosteo/core-wasm'
|
||||||
import type {
|
import type {
|
||||||
ArchiveImport,
|
ArchiveImport,
|
||||||
|
CanvasView,
|
||||||
DraftRestore,
|
DraftRestore,
|
||||||
LateralSide,
|
LateralSide,
|
||||||
Observation,
|
Observation,
|
||||||
@@ -89,6 +90,15 @@ export class SheetOps {
|
|||||||
return this.run('archive.import', attachment)
|
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<CanvasView> {
|
||||||
|
return this.run('view.canvas', { viewId })
|
||||||
|
}
|
||||||
|
|
||||||
/** The snapshot of this sheet an archive of `report` carries. */
|
/** The snapshot of this sheet an archive of `report` carries. */
|
||||||
snapshot(report: Report): CoreOutcome<SheetSnapshot> {
|
snapshot(report: Report): CoreOutcome<SheetSnapshot> {
|
||||||
return this.run('archive.snapshot', { report })
|
return this.run('archive.snapshot', { report })
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import type {
|
|||||||
SheetView,
|
SheetView,
|
||||||
VertebralRegion,
|
VertebralRegion,
|
||||||
} from '@faunosteo/core-wasm/types'
|
} from '@faunosteo/core-wasm/types'
|
||||||
|
import type { CoreOutcome } from '@faunosteo/core-wasm'
|
||||||
import type { SheetOps } from '@/core/sheetOps'
|
import type { SheetOps } from '@/core/sheetOps'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,8 +30,6 @@ export interface LoadedSheetView {
|
|||||||
schemaVersion: number
|
schemaVersion: number
|
||||||
/** The document as the core parsed it (defaults filled in). */
|
/** The document as the core parsed it (defaults filled in). */
|
||||||
document: AnatomicalSheetDocument
|
document: AnatomicalSheetDocument
|
||||||
/** SVG text by `svg_asset_id` (the canvas draws them until R3). */
|
|
||||||
assets: Readonly<Record<string, string>>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function at<T>(
|
function at<T>(
|
||||||
@@ -53,10 +52,11 @@ export class SheetIndex {
|
|||||||
readonly mainViewId: string
|
readonly mainViewId: string
|
||||||
private readonly spine: ReadonlySet<string>
|
private readonly spine: ReadonlySet<string>
|
||||||
private readonly nodes: ReadonlySet<string>
|
private readonly nodes: ReadonlySet<string>
|
||||||
|
/** The composed canvas of each view: constant for a loaded sheet, composed once (R3). */
|
||||||
|
private readonly canvases = new Map<string, string>()
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly data: SheetIndexData,
|
private readonly data: SheetIndexData,
|
||||||
assets: Readonly<Record<string, string>>,
|
|
||||||
readonly ops: SheetOps,
|
readonly ops: SheetOps,
|
||||||
) {
|
) {
|
||||||
const { document } = data
|
const { document } = data
|
||||||
@@ -66,13 +66,22 @@ export class SheetIndex {
|
|||||||
speciesId: data.speciesId,
|
speciesId: data.speciesId,
|
||||||
schemaVersion: data.schemaVersion,
|
schemaVersion: data.schemaVersion,
|
||||||
document,
|
document,
|
||||||
assets,
|
|
||||||
}
|
}
|
||||||
this.mainViewId = data.mainViewId
|
this.mainViewId = data.mainViewId
|
||||||
this.spine = new Set(data.spineIds)
|
this.spine = new Set(data.spineIds)
|
||||||
this.nodes = new Set(data.nodeKeys)
|
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<string> {
|
||||||
|
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 {
|
view(id: string): SheetView | undefined {
|
||||||
return at(this.data.document.views, this.data.viewById, id)
|
return at(this.data.document.views, this.data.viewById, id)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ async function loadIntoCore(speciesId: string): Promise<SheetLoad> {
|
|||||||
const session = coreRuntime().sheet(JSON.stringify(bundle))
|
const session = coreRuntime().sheet(JSON.stringify(bundle))
|
||||||
const data = session.call<SheetIndexData>('index_data', '')
|
const data = session.call<SheetIndexData>('index_data', '')
|
||||||
if (data.ok) {
|
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 { status: 'ready', index }
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -132,5 +132,5 @@ export function sheetFromBundle(bundle: BundledSheetData): SheetIndex {
|
|||||||
const session = coreRuntime().sheet(JSON.stringify(bundle))
|
const session = coreRuntime().sheet(JSON.stringify(bundle))
|
||||||
const data = session.call<SheetIndexData>('index_data', '')
|
const data = session.call<SheetIndexData>('index_data', '')
|
||||||
if (!data.ok) throw new Error(`sheet refused by the core: ${data.kind}`)
|
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))
|
||||||
}
|
}
|
||||||
+26
-13
@@ -1,14 +1,15 @@
|
|||||||
/**
|
/**
|
||||||
* R3 freeze O1 (plan 2026-10-14 §3): the editor canvas as the TypeScript
|
* R3 freeze O1 (plan 2026-10-14 §3), now the switch's oracle: the editor canvas as the
|
||||||
* built it before the anatomy core moved to Rust. For each view, the whole
|
* TypeScript built it before the anatomy core moved to Rust (frozen at 47c5f49, never
|
||||||
* tree with no state (root attributes, the drawing's nodes, the layer), and
|
* regenerated to make this pass). For each view, the whole tree with no state; for every
|
||||||
* for every state set the editor can produce from the three reference
|
* state set the editor can produce from the three reference reports (each observation
|
||||||
* reports (each observation active, zones of every view, as EditorRoute
|
* active, zones of every view, as EditorRoute builds them) plus "every annotation", the
|
||||||
* builds them) plus "every annotation", the annotation layer. After the
|
* annotation layer of the mounted canvas (the core composes, the canvas restyles in place).
|
||||||
* switch the same assertions hold on the Rust composition: trees compared by
|
* Trees compared by structure and semantic properties, never by bytes or attribute order.
|
||||||
* 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 { buildViewSvg, type ViewStates } from '@/anatomy/drawing'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
import { loadTestSheet } from '../helpers/sheet'
|
import { loadTestSheet } from '../helpers/sheet'
|
||||||
@@ -25,6 +26,7 @@ beforeAll(async () => {
|
|||||||
sheet = await loadTestSheet()
|
sheet = await loadTestSheet()
|
||||||
golden = buildGoldenReports(sheet)
|
golden = buildGoldenReports(sheet)
|
||||||
})
|
})
|
||||||
|
afterEach(cleanup)
|
||||||
|
|
||||||
const VIEWS = ['main', 'head'] as const
|
const VIEWS = ['main', 'head'] as const
|
||||||
|
|
||||||
@@ -54,16 +56,27 @@ function layerOf(tree: TreeNode): TreeNode {
|
|||||||
return last
|
return last
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function mountedLayer(viewId: string, states: ViewStates): Promise<TreeNode> {
|
||||||
|
const { container, unmount } = render(
|
||||||
|
<AnatomyCanvas index={sheet} viewId={viewId} states={states} onZoneClick={() => 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) => {
|
describe.each(VIEWS)('the %s canvas', (viewId) => {
|
||||||
it('builds the frozen tree with no state', () => {
|
it('builds the frozen tree with no state', () => {
|
||||||
const tree = treeOf(buildViewSvg(sheet, viewId, new Map()))
|
const svg = buildViewSvg(sheet, viewId)
|
||||||
checkR3Golden(`canvas.${viewId}.json`, tree)
|
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<string, TreeNode> = {}
|
const layers: Record<string, TreeNode> = {}
|
||||||
for (const [name, states] of stateCases()) {
|
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)
|
expect(Object.keys(layers).length).toBeGreaterThan(8)
|
||||||
checkR3Golden(`canvas.${viewId}.layers.json`, layers)
|
checkR3Golden(`canvas.${viewId}.layers.json`, layers)
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest'
|
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 AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
|
||||||
import { buildViewSvg, parseDrawing, sanitizeSvg } from '@/anatomy/drawing'
|
import { buildViewSvg } from '@/anatomy/drawing'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
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
|
let sheet: SheetIndex
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
@@ -11,10 +13,17 @@ beforeAll(async () => {
|
|||||||
})
|
})
|
||||||
afterEach(cleanup)
|
afterEach(cleanup)
|
||||||
|
|
||||||
|
/** 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', () => {
|
describe('buildViewSvg', () => {
|
||||||
it('frames the main view on the asset box and the head view on its crop of the same drawing', () => {
|
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 main = buildViewSvg(sheet, 'main')!
|
||||||
const head = buildViewSvg(sheet, 'head', new Map())
|
const head = buildViewSvg(sheet, 'head')!
|
||||||
expect(main.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
|
expect(main.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
|
||||||
expect(head.getAttribute('viewBox')).toBe('60 100 500 380')
|
expect(head.getAttribute('viewBox')).toBe('60 100 500 380')
|
||||||
expect(main.querySelectorAll('path').length).toBe(
|
expect(main.querySelectorAll('path').length).toBe(
|
||||||
@@ -27,25 +36,23 @@ describe('buildViewSvg', () => {
|
|||||||
expect(main.hasAttribute('width')).toBe(false)
|
expect(main.hasAttribute('width')).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('applies states as data-state on the generated markers', () => {
|
it('composes the view once per sheet (a constant text) and carries no state', () => {
|
||||||
const svg = buildViewSvg(sheet, 'main', new Map([['stifle', 'current']]))
|
expect(sheet.canvasSvg('main')).toEqual(sheet.canvasSvg('main'))
|
||||||
const marked = Array.from(
|
expect(buildViewSvg(sheet, 'main')!.querySelector('[data-state]')).toBeNull()
|
||||||
svg.querySelectorAll('[data-state="current"]'),
|
|
||||||
).map((el) => el.getAttribute('data-anno-id'))
|
|
||||||
expect(marked).toEqual(['stifle', 'stifle'])
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('sanitises scripts, embedded documents and handlers out of an asset', () => {
|
it('refuses a drawing the core would have to alter: nothing of it reaches the page (LRN-025)', async () => {
|
||||||
const root = parseDrawing(
|
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>',
|
'<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>',
|
||||||
)
|
)
|
||||||
sanitizeSvg(root)
|
expect(hostile.canvasSvg('main')).toMatchObject({ ok: false, kind: 'svg_rejected' })
|
||||||
expect(root.querySelector('script')).toBeNull()
|
expect(buildViewSvg(hostile, 'main')).toBeNull()
|
||||||
expect(root.querySelector('foreignObject')).toBeNull()
|
const malformed = await sheetDrawing('<not svg')
|
||||||
expect(root.querySelector('g')!.hasAttribute('onclick')).toBe(false)
|
expect(malformed.canvasSvg('main')).toMatchObject({
|
||||||
expect(root.querySelector('a')!.hasAttribute('href')).toBe(false)
|
ok: false,
|
||||||
expect(root.querySelector('path')).not.toBeNull()
|
kind: 'svg_rejected',
|
||||||
expect(() => parseDrawing('<not svg')).toThrow()
|
detail: 'malformed',
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -74,6 +81,37 @@ describe('AnatomyCanvas', () => {
|
|||||||
expect(onZoneClick).toHaveBeenCalledTimes(1)
|
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('shows the degraded notice for a drawing it cannot draw, and nothing of the drawing', async () => {
|
||||||
|
useLocaleStore.setState({ locale: 'fr' })
|
||||||
|
const hostile = await sheetDrawing(
|
||||||
|
'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
|
||||||
|
)
|
||||||
|
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()
|
||||||
|
expect(container.querySelector('script, [data-layer], [data-anno-id]')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
it('restyles in place when the states change', async () => {
|
it('restyles in place when the states change', async () => {
|
||||||
const { container, rerender } = render(
|
const { container, rerender } = render(
|
||||||
<AnatomyCanvas
|
<AnatomyCanvas
|
||||||
|
|||||||
@@ -4,31 +4,33 @@
|
|||||||
export type { AddSidesInput } from './AddSidesInput'
|
export type { AddSidesInput } from './AddSidesInput'
|
||||||
export type { AnatomicalSheetDocument } from './AnatomicalSheetDocument'
|
export type { AnatomicalSheetDocument } from './AnatomicalSheetDocument'
|
||||||
export type { Animal } from './Animal'
|
export type { Animal } from './Animal'
|
||||||
export type { AnnotationCategory } from './AnnotationCategory'
|
|
||||||
export type { Annotation } from './Annotation'
|
export type { Annotation } from './Annotation'
|
||||||
|
export type { AnnotationCategory } from './AnnotationCategory'
|
||||||
export type { ArchiveImport } from './ArchiveImport'
|
export type { ArchiveImport } from './ArchiveImport'
|
||||||
export type { ArchiveOrigin } from './ArchiveOrigin'
|
export type { ArchiveOrigin } from './ArchiveOrigin'
|
||||||
export type { ArchiveReadOutcome } from './ArchiveReadOutcome'
|
export type { ArchiveReadOutcome } from './ArchiveReadOutcome'
|
||||||
export type { Attribution } from './Attribution'
|
export type { Attribution } from './Attribution'
|
||||||
export type { Branding } from './Branding'
|
export type { Branding } from './Branding'
|
||||||
|
export type { CanvasView } from './CanvasView'
|
||||||
|
export type { CanvasViewInput } from './CanvasViewInput'
|
||||||
export type { Circle } from './Circle'
|
export type { Circle } from './Circle'
|
||||||
export type { CountRange } from './CountRange'
|
export type { CountRange } from './CountRange'
|
||||||
export type { Credit } from './Credit'
|
export type { Credit } from './Credit'
|
||||||
export type { DetailTriggerAnnotation } from './DetailTriggerAnnotation'
|
export type { DetailTriggerAnnotation } from './DetailTriggerAnnotation'
|
||||||
export type { DetailView } from './DetailView'
|
export type { DetailView } from './DetailView'
|
||||||
export type { DraftRestoreInput } from './DraftRestoreInput'
|
|
||||||
export type { DraftRestore } from './DraftRestore'
|
export type { DraftRestore } from './DraftRestore'
|
||||||
export type { FindingCategoryKind } from './FindingCategoryKind'
|
export type { DraftRestoreInput } from './DraftRestoreInput'
|
||||||
|
export type { Finding } from './Finding'
|
||||||
export type { FindingCategory } from './FindingCategory'
|
export type { FindingCategory } from './FindingCategory'
|
||||||
|
export type { FindingCategoryKind } from './FindingCategoryKind'
|
||||||
export type { FindingNode } from './FindingNode'
|
export type { FindingNode } from './FindingNode'
|
||||||
export type { FindingToggleInput } from './FindingToggleInput'
|
export type { FindingToggleInput } from './FindingToggleInput'
|
||||||
export type { Finding } from './Finding'
|
|
||||||
export type { FindingZone } from './FindingZone'
|
export type { FindingZone } from './FindingZone'
|
||||||
export type { Geometry } from './Geometry'
|
export type { Geometry } from './Geometry'
|
||||||
export type { ImageAsset } from './ImageAsset'
|
export type { ImageAsset } from './ImageAsset'
|
||||||
export type { JsIndex } from './JsIndex'
|
export type { JsIndex } from './JsIndex'
|
||||||
export type { Laterality } from './Laterality'
|
|
||||||
export type { LateralSide } from './LateralSide'
|
export type { LateralSide } from './LateralSide'
|
||||||
|
export type { Laterality } from './Laterality'
|
||||||
export type { Locale } from './Locale'
|
export type { Locale } from './Locale'
|
||||||
export type { LocalizedOptionalText } from './LocalizedOptionalText'
|
export type { LocalizedOptionalText } from './LocalizedOptionalText'
|
||||||
export type { LocalizedText } from './LocalizedText'
|
export type { LocalizedText } from './LocalizedText'
|
||||||
@@ -38,13 +40,13 @@ export type { MoveDirection } from './MoveDirection'
|
|||||||
export type { MoveObservationInput } from './MoveObservationInput'
|
export type { MoveObservationInput } from './MoveObservationInput'
|
||||||
export type { NewReportDraft } from './NewReportDraft'
|
export type { NewReportDraft } from './NewReportDraft'
|
||||||
export type { NewReportInput } from './NewReportInput'
|
export type { NewReportInput } from './NewReportInput'
|
||||||
|
export type { NextAppointment } from './NextAppointment'
|
||||||
export type { NextAppointmentDate } from './NextAppointmentDate'
|
export type { NextAppointmentDate } from './NextAppointmentDate'
|
||||||
export type { NextAppointmentPeriod } from './NextAppointmentPeriod'
|
export type { NextAppointmentPeriod } from './NextAppointmentPeriod'
|
||||||
export type { NextAppointment } from './NextAppointment'
|
|
||||||
export type { ObservableAnnotation } from './ObservableAnnotation'
|
export type { ObservableAnnotation } from './ObservableAnnotation'
|
||||||
export type { ObservableKind } from './ObservableKind'
|
export type { ObservableKind } from './ObservableKind'
|
||||||
export type { ObservationIndexInput } from './ObservationIndexInput'
|
|
||||||
export type { Observation } from './Observation'
|
export type { Observation } from './Observation'
|
||||||
|
export type { ObservationIndexInput } from './ObservationIndexInput'
|
||||||
export type { Owner } from './Owner'
|
export type { Owner } from './Owner'
|
||||||
export type { PathGeometry } from './PathGeometry'
|
export type { PathGeometry } from './PathGeometry'
|
||||||
export type { PdfLabelSet } from './PdfLabelSet'
|
export type { PdfLabelSet } from './PdfLabelSet'
|
||||||
@@ -56,33 +58,33 @@ export type { Practitioner } from './Practitioner'
|
|||||||
export type { RebaseOutcome } from './RebaseOutcome'
|
export type { RebaseOutcome } from './RebaseOutcome'
|
||||||
export type { Reference } from './Reference'
|
export type { Reference } from './Reference'
|
||||||
export type { ReferenceType } from './ReferenceType'
|
export type { ReferenceType } from './ReferenceType'
|
||||||
|
export type { Report } from './Report'
|
||||||
export type { ReportArchiveEnvelope } from './ReportArchiveEnvelope'
|
export type { ReportArchiveEnvelope } from './ReportArchiveEnvelope'
|
||||||
export type { ReportIdInput } from './ReportIdInput'
|
export type { ReportIdInput } from './ReportIdInput'
|
||||||
export type { ReportIndexInput } from './ReportIndexInput'
|
export type { ReportIndexInput } from './ReportIndexInput'
|
||||||
export type { Report } from './Report'
|
|
||||||
export type { ReportZone } from './ReportZone'
|
export type { ReportZone } from './ReportZone'
|
||||||
export type { ReviewStatus } from './ReviewStatus'
|
export type { ReviewStatus } from './ReviewStatus'
|
||||||
export type { Severity } from './Severity'
|
export type { Severity } from './Severity'
|
||||||
export type { SheetCheck } from './SheetCheck'
|
export type { SheetCheck } from './SheetCheck'
|
||||||
export type { SheetIndexData } from './SheetIndexData'
|
export type { SheetIndexData } from './SheetIndexData'
|
||||||
export type { SheetIssueSeverity } from './SheetIssueSeverity'
|
|
||||||
export type { SheetIssue } from './SheetIssue'
|
export type { SheetIssue } from './SheetIssue'
|
||||||
|
export type { SheetIssueSeverity } from './SheetIssueSeverity'
|
||||||
export type { SheetRef } from './SheetRef'
|
export type { SheetRef } from './SheetRef'
|
||||||
|
export type { SheetSnapshot } from './SheetSnapshot'
|
||||||
export type { SheetSnapshotAsset } from './SheetSnapshotAsset'
|
export type { SheetSnapshotAsset } from './SheetSnapshotAsset'
|
||||||
export type { SheetSnapshotRef } from './SheetSnapshotRef'
|
export type { SheetSnapshotRef } from './SheetSnapshotRef'
|
||||||
export type { SheetSnapshot } from './SheetSnapshot'
|
|
||||||
export type { SheetStatus } from './SheetStatus'
|
export type { SheetStatus } from './SheetStatus'
|
||||||
export type { SheetView } from './SheetView'
|
export type { SheetView } from './SheetView'
|
||||||
export type { SnapshotInput } from './SnapshotInput'
|
export type { SnapshotInput } from './SnapshotInput'
|
||||||
export type { SnapshotRejection } from './SnapshotRejection'
|
export type { SnapshotRejection } from './SnapshotRejection'
|
||||||
export type { SvgAsset } from './SvgAsset'
|
export type { SvgAsset } from './SvgAsset'
|
||||||
|
export type { Vertebra } from './Vertebra'
|
||||||
export type { VertebraAction } from './VertebraAction'
|
export type { VertebraAction } from './VertebraAction'
|
||||||
export type { VertebralConfig } from './VertebralConfig'
|
|
||||||
export type { VertebralRegion } from './VertebralRegion'
|
|
||||||
export type { VertebraSelectInput } from './VertebraSelectInput'
|
export type { VertebraSelectInput } from './VertebraSelectInput'
|
||||||
export type { VertebraSyncInput } from './VertebraSyncInput'
|
export type { VertebraSyncInput } from './VertebraSyncInput'
|
||||||
export type { Vertebra } from './Vertebra'
|
export type { VertebralConfig } from './VertebralConfig'
|
||||||
|
export type { VertebralRegion } from './VertebralRegion'
|
||||||
export type { ViewBox } from './ViewBox'
|
export type { ViewBox } from './ViewBox'
|
||||||
|
export type { ZoneClick } from './ZoneClick'
|
||||||
export type { ZoneClickInput } from './ZoneClickInput'
|
export type { ZoneClickInput } from './ZoneClickInput'
|
||||||
export type { ZoneClickKind } from './ZoneClickKind'
|
export type { ZoneClickKind } from './ZoneClickKind'
|
||||||
export type { ZoneClick } from './ZoneClick'
|
|
||||||
Generated
-3
@@ -20,9 +20,6 @@ importers:
|
|||||||
|
|
||||||
apps/app:
|
apps/app:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@faunosteo/anatomy':
|
|
||||||
specifier: workspace:*
|
|
||||||
version: link:../../packages/anatomy
|
|
||||||
'@faunosteo/core-wasm':
|
'@faunosteo/core-wasm':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/core-wasm
|
version: link:../../packages/core-wasm
|
||||||
|
|||||||
Reference in new issue
Block a user