Files
faunosteo/apps/app/tests/helpers/svgTree.ts
T
bchanot 9c606aa567 fix(anatomy): V1-2.2 the visible wins on the editor canvas
Owner decision 2026-11-01. The canvas paints and hits every point hitbox,
then every zone and trigger, then every visible twin, which captures on
what it paints; a junction's disc is no longer taken by the zone drawn
after it. The PDF view keeps the document order and its bytes. Click
spec: the five fixme run unmarked, six projects incl. a 320 px phone.
2026-11-01 00:56:11 +01:00

201 lines
8.0 KiB
TypeScript

import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { expect } from 'vitest'
import { FIXTURES_DIR } from './goldens'
/**
* R3 freeze (plan 2026-10-14 §3 O1): a DOM tree as structure and semantic
* properties, never bytes. Elements by namespace + local name, attributes as
* a map keyed by qualified name (their order is not part of the contract),
* children in document order with text nodes kept (the canvas imports the
* drawing's whitespace), comments and processing instructions named.
*/
export type TreeNode =
| {
ns: string | null
name: string
attrs: Record<string, string>
children: TreeNode[]
}
| { text: string }
| { comment: string }
| { pi: string }
const ELEMENT = 1
const TEXT = 3
const CDATA = 4
const PI = 7
const COMMENT = 8
export function treeOf(node: Node): TreeNode {
if (node.nodeType === TEXT || node.nodeType === CDATA) {
return { text: node.nodeValue ?? '' }
}
if (node.nodeType === COMMENT) return { comment: node.nodeValue ?? '' }
if (node.nodeType === PI) return { pi: node.nodeName }
if (node.nodeType !== ELEMENT) throw new Error(`node type ${node.nodeType}`)
const el = node as Element
const attrs: Record<string, string> = {}
for (const name of Array.from(el.attributes, (a) => a.name).sort()) {
attrs[name] = el.getAttribute(name) ?? ''
}
return {
ns: el.namespaceURI,
name: el.localName,
attrs,
children: Array.from(el.childNodes, treeOf),
}
}
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'
/**
* 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
}
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<string, string>; 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
}
/**
* Owner decision 2026-10-29 (V1-2.2): the canvas, inlined in the page, scopes the drawing's
* ids and the references to them to its view (`fv.<view>.<id>`). Applied to a frozen tree (a
* deep copy), written apart from the core's rewrite: every `id`, every `#id` href and every
* plain `url(#` (the only spelling of the product drawing). Mirrors
* `crates/core/tests/common/svg_tree.rs`.
*/
export function withIdsScopedPerView(tree: unknown, viewId: string): unknown {
const copy = structuredClone(tree)
const scope = `fv.${viewId}.`
const visit = (node: unknown): void => {
if (typeof node !== 'object' || node === null) return
const n = node as { attrs?: Record<string, string>; children?: unknown[] }
for (const [name, value] of Object.entries(n.attrs ?? {})) {
if (name === 'id') n.attrs![name] = `${scope}${value}`
else if ((name === 'href' || name === 'xlink:href') && value.startsWith('#')) {
n.attrs![name] = `#${scope}${value.slice(1)}`
} else n.attrs![name] = value.replaceAll('url(#', `url(#${scope}`)
}
n.children?.forEach(visit)
}
visit(copy)
return copy
}
const HITBOX_DECLARED = { stroke: 'none', 'pointer-events': 'visibleFill' }
/** A point hitbox of the R3 layer: a circle capturing on `all` with no stroke of its own. */
function isR3Hitbox(node: unknown): node is { name: string; attrs: Record<string, string> } {
const n = node as { name?: string; attrs?: Record<string, string> }
return n.name === 'circle' && n.attrs?.['pointer-events'] === 'all' && !('stroke' in n.attrs)
}
/**
* Owner brief 2026-10-30 (V1-2.2, three MEDIUM): each point hitbox the composers draw declares
* `stroke="none"` and `pointer-events="visibleFill"`. Applied to a frozen layer (a deep copy).
* Mirrors `crates/core/tests/common/svg_tree.rs`.
*/
export function withDeclaredHitboxes(layer: unknown): unknown {
const copy = structuredClone(layer) as { children?: unknown[] }
for (const child of copy.children ?? []) {
if (isR3Hitbox(child)) Object.assign(child.attrs, HITBOX_DECLARED)
}
return copy
}
/**
* Owner brief 2026-10-30 (V1-2.2, three MEDIUM): the composition root is the engine's. Applied
* to a frozen canvas tree (a deep copy): the root keeps its namespaces and `viewBox`; its other
* attributes and every child before the layer go into a `<g>` of the drawing; the layer's
* hitboxes are declared (`withDeclaredHitboxes`) and its markers put in the canvas passes
* (`withCanvasPasses`, owner decision 2026-11-01). Mirrors `crates/core/tests/common/svg_tree.rs`.
*/
export function withIsolatedLayer(tree: unknown): unknown {
const root = structuredClone(tree) as {
ns: string
attrs: Record<string, string>
children: unknown[]
}
const layer = root.children.pop()
const kept: Record<string, string> = {}
const moved: Record<string, string> = {}
for (const [name, value] of Object.entries(root.attrs)) {
if (name === 'xmlns' || name === 'xmlns:xlink' || name === 'viewBox') kept[name] = value
else moved[name] = value
}
const group = { ns: root.ns, name: 'g', attrs: moved, children: root.children }
root.attrs = kept
root.children = [group, withCanvasPasses(withDeclaredHitboxes(layer))]
return root
}
/** A marker's pass on the canvas: 0 a point hitbox, 1 a zone or a trigger, 2 a visible twin. */
function canvasPass(node: unknown): number {
const n = node as { name?: string; attrs?: Record<string, string> }
if (n.name !== 'circle') return 1
if (n.attrs?.fill === 'transparent') return 0
return n.attrs?.['pointer-events'] === 'none' ? 2 : 1
}
/**
* Owner decision 2026-11-01 (V1-2.2, « the visible wins »), the editor canvas only: applied to
* a frozen layer after `withDeclaredHitboxes` (a deep copy). Every point hitbox, then every
* other shape, then every visible twin, each pass in the frozen order; the twins capture on
* `visiblePainted`. Mirrors `with_canvas_passes` in `crates/core/tests/common/svg_tree.rs`.
*/
export function withCanvasPasses(layer: unknown): unknown {
const copy = structuredClone(layer) as { children?: unknown[] }
const ranked = (copy.children ?? []).map((child, at) => ({ child, at, pass: canvasPass(child) }))
ranked.sort((a, b) => a.pass - b.pass || a.at - b.at)
copy.children = ranked.map(({ child, pass }) => {
if (pass === 2) (child as { attrs: Record<string, string> }).attrs['pointer-events'] = 'visiblePainted'
return child
})
return copy
}