feat(anatomy): composeViewSvg with tree-level highlight and halo, review drawing on the shared composer

This commit is contained in:
bchanot committed 2026-10-11 12:05:56 +02:00
1 parent 4c6c5151f8
commit 694092610d
7 files changed
+521 -14

No files matched your search

+4 -14
View File
@@ -1,14 +1,14 @@
import { DOMParser, XMLSerializer } from '@xmldom/xmldom'
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import { createLayerElement } from '../render/dom'
import { renderAnnotationLayer, viewBoxOf } from '../render/layer'
import { composeViewSvg } from '../render/compose'
/**
* The drawing of one view exactly as the application renders it: the
* cleaned asset framed on the view's box plus the annotation layer the app
* generates from the document. Written under draft/review/app-<view>.svg
* so the markers and the framing can be compared with the legacy files
* before and after a change, outside the browser.
* before and after a change, outside the browser. Parse and serialise
* here; the composition itself is the shared `composeViewSvg`.
*/
export interface AppReviewInput {
@@ -21,16 +21,6 @@ export function renderAppReviewDrawing(input: AppReviewInput): string {
const doc = new DOMParser().parseFromString(input.cleanedSvg, 'image/svg+xml')
const root = doc.documentElement
if (!root || root.tagName !== 'svg') throw new Error('not an SVG document')
const view = input.document.views.find((v) => v.id === input.viewId)
if (!view) throw new Error(`unknown view "${input.viewId}"`)
const box = viewBoxOf(view)
if (box) root.setAttribute('viewBox', box)
root.removeAttribute('width')
root.removeAttribute('height')
const layer = renderAnnotationLayer({
document: input.document,
viewId: view.id,
})
root.appendChild(createLayerElement(doc, layer) as never)
composeViewSvg({ root, document: input.document, viewId: input.viewId })
return new XMLSerializer().serializeToString(doc)
}
+196
View File
@@ -0,0 +1,196 @@
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import {
createLayerElement,
SVG_NS,
type MinimalDocument,
type MinimalElement,
type MinimalNode,
} from './dom'
import { renderAnnotationLayer, viewBoxOf, type LayerElement } from './layer'
/**
* Composes the drawing of one view: the parsed asset framed on the view's
* box plus the annotation layer rendered from the document. With a
* `highlight`, the layer keeps only the selected annotations, styled for
* print (legacy picture: accent fill, halo on the main view, no data
* attributes). Works on any DOM Level 2 implementation (a Node parser or
* the browser DOM): the caller parses and serialises.
*/
export const HALO_FILTER_ID = 'osteo-halo'
export const HIGHLIGHT_FILL = '#b85a3f'
export const HIGHLIGHT_FILL_OPACITY = '0.85'
/** DOM Level 2 surface the composer needs on the `<svg>` root. */
export interface ComposeElement extends MinimalElement {
readonly ownerDocument: MinimalDocument | null
readonly firstChild: MinimalNode | null
getAttribute(name: string): string | null
removeAttribute(name: string): void
insertBefore(node: MinimalNode, reference: MinimalNode | null): unknown
getElementsByTagName(tag: string): ComposeElementList
}
export interface ComposeElementList {
readonly length: number
item(index: number): ComposeElement | null
}
export interface ComposeHighlight {
/** Annotation ids kept on the layer; every other marker is dropped. */
annotationIds: ReadonlySet<string>
/** Wrap the kept markers in the `osteo-halo` filter (main view). */
halo: boolean
}
export interface ComposeInput<Root extends ComposeElement = ComposeElement> {
root: Root
document: AnatomicalSheetDocumentInput
viewId: string
highlight?: ComposeHighlight
}
/** Frames `root` on the view, appends the layer `<g>` last, returns `root`. */
export function composeViewSvg<Root extends ComposeElement>(
input: ComposeInput<Root>,
): Root {
const { root, document, viewId, highlight } = input
const view = document.views.find((v) => v.id === viewId)
if (!view) throw new Error(`unknown view "${viewId}"`)
const box = viewBoxOf(view)
if (box) root.setAttribute('viewBox', box)
root.removeAttribute('width')
root.removeAttribute('height')
if (highlight?.halo) ensureHaloFilter(root)
const rendered = renderAnnotationLayer({ document, viewId })
const layer = highlight ? highlightLayer(rendered, highlight) : rendered
root.appendChild(createLayerElement(documentOf(root), layer))
return root
}
/** Typed nullable by the DOM; an element taken from a parsed document has one. */
function documentOf(root: ComposeElement): MinimalDocument {
if (!root.ownerDocument) throw new Error('root has no owner document')
return root.ownerDocument
}
/**
* The layer reduced to the selected annotations (both elements of a point),
* each with the accent fill and, when asked, the halo filter. No `data-*`
* attribute survives: the result is a picture, not an interactive layer.
*/
export function highlightLayer(
layer: LayerElement,
highlight: ComposeHighlight,
): LayerElement {
const children = layer.children
.filter((child) =>
highlight.annotationIds.has(child.attrs['data-anno-id'] ?? ''),
)
.map((child) => highlightElement(child, highlight.halo))
return { ...layer, attrs: withoutDataAttrs(layer.attrs), children }
}
function highlightElement(node: LayerElement, halo: boolean): LayerElement {
const attrs: Record<string, string> = {
...withoutDataAttrs(node.attrs),
fill: HIGHLIGHT_FILL,
'fill-opacity': HIGHLIGHT_FILL_OPACITY,
}
if (halo) attrs.filter = `url(#${HALO_FILTER_ID})`
return { ...node, attrs }
}
function withoutDataAttrs(
attrs: Record<string, string>,
): Record<string, string> {
return Object.fromEntries(
Object.entries(attrs).filter(([name]) => !name.startsWith('data-')),
)
}
/**
* Adds the Gaussian-blur "halo" filter so the highlighted markers stay
* visible on the whole-animal view once rasterised at print scale. One
* filter per root: a second call finds it and leaves the tree alone.
*/
function ensureHaloFilter(root: ComposeElement): void {
if (hasElementWithId(root, 'filter', HALO_FILTER_ID)) return
const defs = root.getElementsByTagName('defs').item(0) ?? createDefs(root)
defs.appendChild(haloFilter(documentOf(root)))
}
function hasElementWithId(
root: ComposeElement,
tag: string,
id: string,
): boolean {
const list = root.getElementsByTagName(tag)
for (let i = 0; i < list.length; i++) {
if (list.item(i)?.getAttribute('id') === id) return true
}
return false
}
/** `<defs>` as the first child: the asset's own filters sit at the root. */
function createDefs(root: ComposeElement): MinimalElement {
const defs = documentOf(root).createElementNS(SVG_NS, 'defs')
root.insertBefore(defs, root.firstChild)
return defs
}
function svgElement(
doc: MinimalDocument,
tag: string,
attrs: Record<string, string>,
): MinimalElement {
const element = doc.createElementNS(SVG_NS, tag)
for (const [name, value] of Object.entries(attrs)) {
element.setAttribute(name, value)
}
return element
}
function haloFilter(doc: MinimalDocument): MinimalElement {
const filter = svgElement(doc, 'filter', {
id: HALO_FILTER_ID,
x: '-100%',
y: '-100%',
width: '300%',
height: '300%',
filterUnits: 'userSpaceOnUse',
})
filter.appendChild(gaussianBlur(doc, '18', 'haloWide'))
filter.appendChild(gaussianBlur(doc, '8', 'haloTight'))
filter.appendChild(haloMerge(doc))
return filter
}
function gaussianBlur(
doc: MinimalDocument,
stdDeviation: string,
result: string,
): MinimalElement {
return svgElement(doc, 'feGaussianBlur', {
in: 'SourceGraphic',
stdDeviation,
result,
})
}
/** Three wide blurs, two tight ones, then the marker itself on top. */
function haloMerge(doc: MinimalDocument): MinimalElement {
const merge = svgElement(doc, 'feMerge', {})
const inputs = [
'haloWide',
'haloWide',
'haloWide',
'haloTight',
'haloTight',
'SourceGraphic',
]
for (const input of inputs) {
merge.appendChild(svgElement(doc, 'feMergeNode', { in: input }))
}
return merge
}
+11
View File
@@ -20,3 +20,14 @@ export {
type MinimalNode,
} from './dom'
export { serializeLayer } from './serialize'
export {
composeViewSvg,
HALO_FILTER_ID,
HIGHLIGHT_FILL,
HIGHLIGHT_FILL_OPACITY,
highlightLayer,
type ComposeElement,
type ComposeElementList,
type ComposeHighlight,
type ComposeInput,
} from './compose'
@@ -0,0 +1,230 @@
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { DOMParser, XMLSerializer, type Element } from '@xmldom/xmldom'
import { beforeAll, describe, expect, it } from 'vitest'
import {
composeViewSvg,
EQUINE_DRAFT_DIR,
HALO_FILTER_ID,
highlightLayer,
renderAnnotationLayer,
renderAppReviewDrawing,
type DraftResult,
type LayerElement,
} from '../src'
import { REPO_ROOT, runDraft } from './helpers'
const draftDir = join(REPO_ROOT, EQUINE_DRAFT_DIR)
const HALO_FILTER_MARKUP =
`<defs><filter id="${HALO_FILTER_ID}" x="-100%" y="-100%" width="300%" ` +
'height="300%" filterUnits="userSpaceOnUse">' +
'<feGaussianBlur in="SourceGraphic" stdDeviation="18" result="haloWide"/>' +
'<feGaussianBlur in="SourceGraphic" stdDeviation="8" result="haloTight"/>' +
'<feMerge><feMergeNode in="haloWide"/><feMergeNode in="haloWide"/>' +
'<feMergeNode in="haloWide"/><feMergeNode in="haloTight"/>' +
'<feMergeNode in="haloTight"/><feMergeNode in="SourceGraphic"/>' +
'</feMerge></filter></defs>'
let draft: DraftResult
let horseSvg: string
/** The committed cleaned drawing, parsed fresh for every test. */
function parseHorse(): Element {
const doc = new DOMParser().parseFromString(horseSvg, 'image/svg+xml')
return doc.documentElement!
}
function serialize(root: Element): string {
return new XMLSerializer().serializeToString(root.ownerDocument!)
}
function elements(list: { length: number; item(i: number): Element | null }) {
return Array.from({ length: list.length }, (_, i) => list.item(i)!)
}
/** Element children of the layer `<g>`, the last child of the root. */
function layerChildren(root: Element): Element[] {
const layer = root.lastChild as Element
expect(layer.nodeName).toBe('g')
return elements(layer.childNodes as never).filter((n) => n.nodeType === 1)
}
function dataAttributeCount(root: Element): number {
return (serialize(root).match(/ data-[a-z-]+="/g) ?? []).length
}
beforeAll(async () => {
;({ draft } = await runDraft())
const [asset] = draft.assets
horseSvg = await readFile(join(draftDir, 'assets', asset!.file), 'utf8')
})
describe('composeViewSvg with a highlight', () => {
it('keeps both elements of a selected point and the selected spine zone, haloed on the main view', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(['hip', 'cervical']), halo: true },
})
const kept = layerChildren(root)
expect(kept.map((e) => e.nodeName)).toEqual(['circle', 'circle', 'polygon'])
for (const element of kept) {
expect(element.getAttribute('fill')).toBe('#b85a3f')
expect(element.getAttribute('fill-opacity')).toBe('0.85')
expect(element.getAttribute('filter')).toBe(`url(#${HALO_FILTER_ID})`)
}
expect(kept[0]!.getAttribute('r')).toBe('34')
expect(kept[1]!.getAttribute('r')).toBe('22')
expect(root.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
expect(root.hasAttribute('width')).toBe(false)
expect(root.hasAttribute('height')).toBe(false)
})
it('creates <defs> as the first child of an asset without one and fills it with the halo filter', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(['hip']), halo: true },
})
expect(root.firstChild!.nodeName).toBe('defs')
expect(root.getElementsByTagName('defs')).toHaveLength(1)
expect(serialize(root)).toContain(HALO_FILTER_MARKUP)
})
it('never duplicates the filter on a root that already holds it', () => {
const root = parseHorse()
const input = {
root,
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(['hip']), halo: true },
}
composeViewSvg(input)
composeViewSvg(input)
const filters = elements(root.getElementsByTagName('filter')).filter(
(f) => f.getAttribute('id') === HALO_FILTER_ID,
)
expect(filters).toHaveLength(1)
expect(root.getElementsByTagName('defs')).toHaveLength(1)
})
it('frames the head view on its view box without any halo', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'head',
highlight: { annotationIds: new Set(['parietal']), halo: false },
})
expect(root.getAttribute('viewBox')).toBe('60 100 500 380')
expect(root.getElementsByTagName('defs')).toHaveLength(0)
expect(serialize(root)).not.toContain(HALO_FILTER_ID)
const kept = layerChildren(root)
expect(kept.map((e) => e.nodeName)).toEqual(['circle', 'circle'])
for (const element of kept) {
expect(element.getAttribute('fill')).toBe('#b85a3f')
expect(element.hasAttribute('filter')).toBe(false)
}
})
it('leaves an empty layer when nothing is selected', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(), halo: true },
})
expect(layerChildren(root)).toHaveLength(0)
})
it('keeps the <title> of every kept marker and emits no data attribute', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
highlight: { annotationIds: new Set(['hip', 'cervical']), halo: true },
})
const titles = elements(root.lastChild!.childNodes as never)
.filter((n) => n.nodeType === 1)
.map((e) => e.getElementsByTagName('title').item(0)!.textContent)
expect(titles).toEqual([
'Hanche (coxo-fémorale) / Hip joint',
'Hanche (coxo-fémorale) / Hip joint',
'Vertèbres cervicales / Cervical vertebrae',
])
expect(dataAttributeCount(root)).toBe(0)
})
it('refuses an unknown view', () => {
expect(() =>
composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'nope',
highlight: { annotationIds: new Set(), halo: false },
}),
).toThrow('unknown view')
})
})
describe('highlightLayer on the layer tree', () => {
function flatten(node: LayerElement): LayerElement[] {
return [node, ...node.children.flatMap(flatten)]
}
it('filters, restyles and strips data attributes without touching the input', () => {
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'main',
})
const before = JSON.stringify(layer)
const highlighted = highlightLayer(layer, {
annotationIds: new Set(['cervical']),
halo: false,
})
expect(JSON.stringify(layer)).toBe(before)
expect(highlighted.children).toHaveLength(1)
expect(highlighted.children[0]!.attrs).toMatchObject({
fill: '#b85a3f',
'fill-opacity': '0.85',
'stroke-width': '2',
})
expect(highlighted.children[0]!.attrs.filter).toBeUndefined()
const dataKeys = flatten(highlighted).flatMap((n) =>
Object.keys(n.attrs).filter((k) => k.startsWith('data-')),
)
expect(dataKeys).toEqual([])
})
})
describe('composeViewSvg without a highlight (review drawings)', () => {
it.each(['main', 'head'])(
'renderAppReviewDrawing(%s) equals the committed review drawing',
async (viewId) => {
const committed = await readFile(
join(draftDir, 'review', `app-${viewId}.svg`),
'utf8',
)
const rendered = renderAppReviewDrawing({
cleanedSvg: horseSvg,
document: draft.document,
viewId,
})
expect(rendered).toBe(committed)
},
)
it('keeps the full interactive layer with its data attributes', () => {
const root = composeViewSvg({
root: parseHorse(),
document: draft.document,
viewId: 'main',
})
expect(root.getElementsByTagName('defs')).toHaveLength(0)
expect((root.lastChild as Element).getAttribute('data-layer')).toBe(
'annotations',
)
expect(dataAttributeCount(root)).toBeGreaterThan(0)
})
})