test(tests): R3 freeze O1 canvas trees and the visual comparison script
This commit is contained in:
1 parent
fbc9526e57
commit
47c5f49014
7 files changed
+40542
No files matched your search
@@ -0,0 +1,63 @@
|
||||
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'
|
||||
|
||||
export function checkR3Golden(name: string, actual: unknown): void {
|
||||
const file = resolve(R3_GOLDEN_DIR, name)
|
||||
if (MAKE_R3_GOLDEN) {
|
||||
mkdirSync(R3_GOLDEN_DIR, { recursive: true })
|
||||
writeFileSync(file, `${JSON.stringify(actual, null, 1)}\n`)
|
||||
return
|
||||
}
|
||||
expect(actual, name).toEqual(JSON.parse(readFileSync(file, 'utf8')))
|
||||
}
|
||||
Reference in new issue
Block a user