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
@@ -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<string, 'current'>
|
||||
|
||||
/** 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 <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
|
||||
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
|
||||
}
|
||||
@@ -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<HTMLDivElement | null>(null)
|
||||
const tooltipRef = useRef<HTMLDivElement | null>(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"
|
||||
/>
|
||||
<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>
|
||||
)
|
||||
}
|
||||
@@ -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<CanvasView> {
|
||||
return this.run('view.canvas', { viewId })
|
||||
}
|
||||
|
||||
/** The snapshot of this sheet an archive of `report` carries. */
|
||||
snapshot(report: Report): CoreOutcome<SheetSnapshot> {
|
||||
return this.run('archive.snapshot', { report })
|
||||
|
||||
@@ -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<Record<string, string>>
|
||||
}
|
||||
|
||||
function at<T>(
|
||||
@@ -53,10 +52,11 @@ export class SheetIndex {
|
||||
readonly mainViewId: string
|
||||
private readonly spine: 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(
|
||||
private readonly data: SheetIndexData,
|
||||
assets: Readonly<Record<string, string>>,
|
||||
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<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 {
|
||||
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 data = session.call<SheetIndexData>('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 {
|
||||
|
||||
Reference in new issue
Block a user