feat(anatomy): report migration map and sheet reference generated by the pipeline, pure annotation-layer renderer (legacy marker look) shared with the app, app review drawings, marker colours as document data

This commit is contained in:
bchanot committed 2026-10-10 11:17:34 +02:00
1 parent 70bf992017
commit 0a17e390cf
25 files changed
+3533 -28

No files matched your search

+3 -2
View File
@@ -2,13 +2,14 @@
"name": "@faunosteo/anatomy",
"version": "0.1.0",
"private": true,
"description": "Faunosteo anatomy tooling: deterministic legacy importer that turns the historical equine assets into the canonical anatomical sheet draft",
"description": "Faunosteo anatomy tooling: deterministic legacy importer, curation pipeline (changeset \u2192 draft, report migration map) and the pure annotation-layer renderer shared with the application",
"license": "MIT",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
".": "./src/index.ts",
"./render": "./src/render/index.ts"
},
"scripts": {
"typecheck": "tsc -p tsconfig.json --noEmit",
@@ -0,0 +1,36 @@
import { DOMParser, XMLSerializer } from '@xmldom/xmldom'
import type { AnatomicalSheetDocumentInput } from '@faunosteo/domain'
import { createLayerElement } from '../render/dom'
import { renderAnnotationLayer, viewBoxOf } from '../render/layer'
/**
* 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.
*/
export interface AppReviewInput {
cleanedSvg: string
document: AnatomicalSheetDocumentInput
viewId: string
}
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)
return new XMLSerializer().serializeToString(doc)
}
@@ -3,6 +3,7 @@ import { KIND_LABELS, LEVEL_LABELS, LEVELS } from './labels'
import { needsConfirmation, type ChangeLevel } from './schema'
import { statRows, type DocumentStats } from './stats'
import { isItem } from './targets'
import type { MigrationMapStats } from './migration-map'
import type { ChangeRecord } from './types'
/**
@@ -94,14 +95,37 @@ function intro(): string {
].join('\n')
}
/** Fate of the legacy finding nodes a Report v2 may cite (report-migration-map.json). */
function migration(stats: MigrationMapStats): string {
const rows = [
['Nœuds du catalogue historique', String(stats.nodes)],
['Chemin identique', String(stats.identical)],
[
'Chemin renommé ou déplacé (suivi des renommages)',
String(stats.remapped),
],
[
'Relogé sous une autre catégorie (correspondance unique)',
String(stats.rehomed),
],
[
'Retiré : le bilan garde le constat avec ses libellés figés',
String(stats.removed),
],
]
return `## Migration des bilans v2\n\n${table(['Nœuds', 'Nombre'], rows)}`
}
export function renderChangelog(
result: { records: readonly ChangeRecord[] },
before: DocumentStats,
after: DocumentStats,
migrationStats: MigrationMapStats,
): string {
const sections = [
intro(),
comparison(before, after),
migration(migrationStats),
...LEVELS.map((level) => levelSection(level, result.records)),
]
return `${sections.join('\n\n')}\n`
+1
View File
@@ -23,6 +23,7 @@ const SETTABLE: Record<string, readonly string[]> = {
'finding_zone_id',
'vertebral_region_code',
'opens_view_id',
'color',
],
zone: ['name'],
finding_category: [
+8
View File
@@ -9,10 +9,18 @@ export { compactValue, renderChangelog } from './changelog'
export {
buildEquineDraft,
DRAFT_SEED_SQL_FILE,
MIGRATION_MAP_FILE,
SHEET_REF_FILE,
renderDraftArtifacts,
type DraftInput,
type DraftResult,
} from './pipeline'
export {
buildReportMigrationMap,
type MigrationMapInput,
type MigrationMapStats,
} from './migration-map'
export { renderAppReviewDrawing, type AppReviewInput } from './app-review'
export {
REVIEW_OVERLAY_DIR,
overlayMarkers,
@@ -0,0 +1,178 @@
import type { ReportMigrationMap, SheetRef } from '@faunosteo/domain'
import type { LegacyIdMap } from '../legacy/types'
import { allFindings, topCollection, type Item } from './targets'
import type { ChangeRecord } from './types'
/**
* Report migration map: where every identifier a Report v2 may carry lands
* in the curated draft. Annotations come from the legacy id map (then
* follow annotation renames), finding paths from replaying the applier's
* rename, move and remove records over every node of the legacy baseline.
* A node removed with its category and re-added under another category at
* the same relative place (the sphenoid restructure) is re-homed when the
* match is unique; anything else stays null = "removed", and the report
* keeps the finding with its snapshots.
*/
const FINDING = 'finding:'
export interface MigrationMapInput {
baseline: Item
final: Item
legacyIdMap: LegacyIdMap
records: readonly ChangeRecord[]
sheet: SheetRef
mainViewId: string
}
export interface MigrationMapStats {
nodes: number
identical: number
remapped: number
rehomed: number
removed: number
}
interface PathEntry {
legacy: string
current: string | null
rehomed: boolean
}
function strip(target: string): string {
return target.slice(FINDING.length)
}
function lastSegment(path: string): string {
return path.slice(path.lastIndexOf('/') + 1)
}
function withLastSegment(path: string, id: string): string {
const cut = path.lastIndexOf('/')
return cut < 0 ? id : `${path.slice(0, cut + 1)}${id}`
}
function replacePrefix(entries: PathEntry[], from: string, to: string | null) {
for (const entry of entries) {
const current = entry.current
if (current === null) continue
if (current === from) entry.current = to
else if (current.startsWith(`${from}/`)) {
entry.current = to === null ? null : `${to}${current.slice(from.length)}`
}
}
}
function applyRecord(
entries: PathEntry[],
ids: { annotations: Map<string, string>; views: Map<string, string> },
record: ChangeRecord,
) {
const { op, target } = record
if (op.op !== 'rename' && op.op !== 'remove' && op.op !== 'move') return
if (target.startsWith(FINDING)) {
const from = strip(target)
if (op.op === 'rename')
replacePrefix(entries, from, withLastSegment(from, op.id))
if (op.op === 'remove') replacePrefix(entries, from, null)
if (op.op === 'move')
replacePrefix(entries, from, `${strip(op.to)}/${lastSegment(from)}`)
return
}
const [kind, id] = target.split(':', 2) as [string, string]
if (kind === 'zone') {
for (const entry of entries) {
if (entry.current?.startsWith(`${id}/`)) {
entry.current =
op.op === 'remove'
? null
: `${op.op === 'rename' ? op.id : id}${entry.current.slice(id.length)}`
}
}
return
}
if (op.op === 'rename' && (kind === 'annotation' || kind === 'view')) {
const map = kind === 'annotation' ? ids.annotations : ids.views
for (const [legacy, current] of map)
if (current === id) map.set(legacy, op.id)
}
}
/** `zone/<any category>/<rest>` present exactly once in the final document. */
function rehome(entry: PathEntry, finalPaths: ReadonlySet<string>): void {
const [zone, , ...rest] = entry.legacy.split('/')
if (rest.length === 0) return
const tail = `/${rest.join('/')}`
const matches = [...finalPaths].filter(
(p) =>
p.startsWith(`${zone}/`) &&
p.endsWith(tail) &&
p.split('/').length === rest.length + 2,
)
if (matches.length === 1) {
entry.current = matches[0]!
entry.rehomed = true
}
}
function annotationNames(doc: Item): Map<string, { fr: string; en: string }> {
const names = new Map<string, { fr: string; en: string }>()
for (const a of topCollection(doc, 'annotation')) {
const name = a.name as { fr?: string; en?: string } | null
names.set(String(a.id), { fr: name?.fr ?? '', en: name?.en ?? '' })
}
return names
}
export function buildReportMigrationMap(input: MigrationMapInput): {
map: ReportMigrationMap
stats: MigrationMapStats
} {
const entries: PathEntry[] = allFindings(input.baseline).map((e) => ({
legacy: strip(e.target),
current: strip(e.target),
rehomed: false,
}))
const ids = {
annotations: new Map(Object.entries(input.legacyIdMap.annotations)),
views: new Map(Object.entries(input.legacyIdMap.views)),
}
for (const record of input.records) applyRecord(entries, ids, record)
const finalPaths = new Set(
allFindings(input.final).map((e) => strip(e.target)),
)
for (const entry of entries) {
if (entry.current !== null && !finalPaths.has(entry.current))
entry.current = null
if (entry.current === null) rehome(entry, finalPaths)
}
const legacyNames = annotationNames(input.baseline)
const importIds = new Map(Object.entries(input.legacyIdMap.annotations))
const annotations: ReportMigrationMap['annotations'] = {}
for (const [legacy, finalId] of ids.annotations) {
annotations[legacy] = {
id: finalId,
name: legacyNames.get(importIds.get(legacy)!) ?? { fr: '', en: '' },
}
}
const finding_paths: Record<string, string | null> = {}
for (const entry of entries) finding_paths[entry.legacy] = entry.current
const map: ReportMigrationMap = {
schema_version: 1,
sheet: input.sheet,
main_view_id: input.mainViewId,
views: Object.fromEntries(ids.views),
annotations,
finding_paths,
}
const stats: MigrationMapStats = {
nodes: entries.length,
identical: entries.filter((e) => e.current === e.legacy).length,
remapped: entries.filter(
(e) => e.current !== null && e.current !== e.legacy && !e.rehomed,
).length,
rehomed: entries.filter((e) => e.rehomed).length,
removed: entries.filter((e) => e.current === null).length,
}
return { map, stats }
}
+60 -2
View File
@@ -6,11 +6,19 @@ import type {
} from '@faunosteo/domain'
import { formatJson, formatMarkdown } from '../format'
import { HEAD_VIEW_ID, MAIN_VIEW_ID } from '../legacy/importer'
import type { Anomaly, AssetRecord, ImportResult } from '../legacy/types'
import type {
Anomaly,
AssetRecord,
ImportResult,
LegacyIdMap,
} from '../legacy/types'
import { applyChangeset, curatedIssues } from './apply'
import { cleanedAsset, stripLegacyAnnotations } from './assets'
import { renderChangelog } from './changelog'
import { REVIEW_OVERLAY_DIR, renderReviewOverlay } from './overlay'
import { buildReportMigrationMap } from './migration-map'
import { renderAppReviewDrawing } from './app-review'
import { sha256Hex } from '../legacy/ids'
import { renderReviewReport } from './review-report'
import {
ASSET_CHANGE_ID,
@@ -44,6 +52,7 @@ export interface DraftResult {
document: AnatomicalSheetDocumentInput
/** Legacy import the changeset was applied to. */
baseline: AnatomicalSheetDocumentInput
legacyIdMap: LegacyIdMap
records: ChangeRecord[]
changes: ChangeSummary[]
assets: AssetRecord[]
@@ -116,6 +125,7 @@ export function buildEquineDraft(input: DraftInput): DraftResult {
return {
document: result.document,
baseline,
legacyIdMap: input.importResult.legacyIdMap,
records: result.records,
changes: changes.map(changeSummary),
assets: [asset],
@@ -142,18 +152,66 @@ function reviewOverlays(draft: DraftResult): Record<string, string> {
return files
}
export const SHEET_REF_FILE = 'sheet-ref.json'
export const MIGRATION_MAP_FILE = 'report-migration-map.json'
/** What a report references: the sheet and the exact document bytes. */
function sheetRef(draft: DraftResult, documentJson: string) {
return {
sheetId: draft.sheetId,
versionId: null,
documentSha256: sha256Hex(documentJson),
}
}
/** The application's own rendering of each view, for the visual check. */
function appReviewDrawings(draft: DraftResult): Record<string, string> {
const files: Record<string, string> = {}
for (const view of draft.document.views) {
files[`${REVIEW_OVERLAY_DIR}/app-${view.id}.svg`] = renderAppReviewDrawing({
cleanedSvg: draft.cleanedSvg,
document: draft.document,
viewId: view.id,
})
}
return files
}
/** Text artifacts of the draft folder, keyed by file name. */
export async function renderDraftArtifacts(
draft: DraftResult,
legacyAnomalies: readonly Anomaly[],
): Promise<Record<string, string>> {
const documentJson = await formatJson(draft.document)
const changelog = renderChangelog(draft, draft.statsBefore, draft.statsAfter)
const ref = sheetRef(draft, documentJson)
const migration = buildReportMigrationMap({
baseline: draft.baseline as Record<string, unknown>,
final: draft.document as Record<string, unknown>,
legacyIdMap: draft.legacyIdMap,
records: draft.records,
sheet: ref,
mainViewId: MAIN_VIEW_ID,
})
const changelog = renderChangelog(
draft,
draft.statsBefore,
draft.statsAfter,
migration.stats,
)
const review = renderReviewReport({ ...draft, legacyAnomalies })
return {
'document.json': documentJson,
'assets.json': await formatJson(draft.assets),
[SHEET_REF_FILE]: await formatJson({
sheet_id: ref.sheetId,
version_id: ref.versionId,
document_sha256: ref.documentSha256,
schema_version: draft.document.schema_version,
species_id: draft.document.species_id,
}),
[MIGRATION_MAP_FILE]: await formatJson(migration.map),
...reviewOverlays(draft),
...appReviewDrawings(draft),
'CHANGELOG.md': await formatMarkdown(changelog),
'REVIEW-REPORT.md': await formatMarkdown(review),
[DRAFT_SEED_SQL_FILE]: renderDraftSeedSql({
+1
View File
@@ -1,2 +1,3 @@
export * from './legacy'
export * from './curation'
export * from './render'
+38
View File
@@ -0,0 +1,38 @@
import type { LayerElement } from './layer'
/**
* Materialises a layer tree with any DOM implementation (browser document,
* xmldom in the pipeline). Only the handful of methods used are required,
* so this module compiles without the DOM lib.
*/
export const SVG_NS = 'http://www.w3.org/2000/svg'
export interface MinimalNode {
appendChild(child: MinimalNode): unknown
}
export interface MinimalElement extends MinimalNode {
setAttribute(name: string, value: string): void
}
export interface MinimalDocument {
createElementNS(ns: string, tag: string): MinimalElement
createTextNode(text: string): MinimalNode
}
export function createLayerElement(
doc: MinimalDocument,
node: LayerElement,
): MinimalElement {
const element = doc.createElementNS(SVG_NS, node.tag)
for (const [name, value] of Object.entries(node.attrs)) {
element.setAttribute(name, value)
}
if (node.text !== undefined)
element.appendChild(doc.createTextNode(node.text))
for (const child of node.children) {
element.appendChild(createLayerElement(doc, child))
}
return element
}
+22
View File
@@ -0,0 +1,22 @@
export {
DETAIL_VIEW_STYLE,
FALLBACK_COLOR,
LAYER_ATTRIBUTE,
LAYER_NAME,
MAIN_VIEW_STYLE,
renderAnnotationLayer,
styleForView,
viewBoxOf,
type AnnotationState,
type LayerElement,
type LayerInput,
type MarkerStyle,
} from './layer'
export {
createLayerElement,
SVG_NS,
type MinimalDocument,
type MinimalElement,
type MinimalNode,
} from './dom'
export { serializeLayer } from './serialize'
+261
View File
@@ -0,0 +1,261 @@
import type {
AnatomicalSheetDocumentInput,
Geometry,
SheetView,
} from '@faunosteo/domain'
/**
* Annotation layer of one view, as pure data: the SVG elements the
* application draws over the sheet's drawing, reproducing the legacy
* markers (transparent hitbox + visible twin per point, filled polygon per
* spine zone, dashed outline per detail trigger). The elements carry the
* `data-anno-*` attributes the click delegation, the tooltip and the CSS
* states read, so the drawing itself needs no annotation element at all.
* No DOM here: `dom.ts` materialises the tree, `serialize.ts` prints it.
*/
export interface LayerElement {
tag: 'g' | 'circle' | 'polygon' | 'path' | 'title'
attrs: Record<string, string>
children: LayerElement[]
text?: string
}
/** Visual constants of the legacy markers, per view kind. */
export interface MarkerStyle {
/** Visible circle radius = hitbox radius − inset (34→22, 30→18, 27→15). */
visibleInset: number
visibleFillOpacity: number
visibleStroke: string
visibleStrokeWidth: number
zoneFillOpacity: number
zoneStrokeWidth: number
triggerFillOpacity: number
triggerStrokeWidth: number
triggerDash: string
}
const BASE_STYLE: Omit<MarkerStyle, 'visibleFillOpacity'> = {
visibleInset: 12,
visibleStroke: '#000',
visibleStrokeWidth: 1.5,
zoneFillOpacity: 0.3,
zoneStrokeWidth: 2,
triggerFillOpacity: 0.06,
triggerStrokeWidth: 2,
triggerDash: '8,4',
}
export const MAIN_VIEW_STYLE: MarkerStyle = {
...BASE_STYLE,
visibleFillOpacity: 0.65,
}
export const DETAIL_VIEW_STYLE: MarkerStyle = {
...BASE_STYLE,
visibleFillOpacity: 0.5,
}
/** When neither the annotation nor its category names a colour. */
export const FALLBACK_COLOR = '#888888'
export const LAYER_ATTRIBUTE = 'data-layer'
export const LAYER_NAME = 'annotations'
export type AnnotationState = 'current'
export interface LayerInput {
document: AnatomicalSheetDocumentInput
viewId: string
/** Annotation id → state, applied as `data-state`. */
states?: ReadonlyMap<string, AnnotationState>
}
type Annotation = AnatomicalSheetDocumentInput['annotations'][number]
export function styleForView(view: Pick<SheetView, 'kind'>): MarkerStyle {
return view.kind === 'main' ? MAIN_VIEW_STYLE : DETAIL_VIEW_STYLE
}
function el(
tag: LayerElement['tag'],
attrs: Record<string, string>,
children: LayerElement[] = [],
): LayerElement {
return { tag, attrs, children }
}
function title(text: string): LayerElement {
return { tag: 'title', attrs: {}, children: [], text }
}
function geometryAttrs(
geometry: Geometry,
): [LayerElement['tag'], Record<string, string>] {
switch (geometry.type) {
case 'circle':
return [
'circle',
{
cx: String(geometry.cx),
cy: String(geometry.cy),
r: String(geometry.r),
},
]
case 'polygon':
return [
'polygon',
{ points: geometry.points.map(([x, y]) => `${x},${y}`).join(' ') },
]
case 'path':
return ['path', { d: geometry.d }]
}
}
function colorOf(
a: Annotation,
categories: Map<string, string | null>,
): string {
return a.color ?? categories.get(a.category_id) ?? FALLBACK_COLOR
}
/** Attributes shared by every element of one annotation. */
function dataAttrs(
a: Annotation,
input: LayerInput,
viewName: string,
): Record<string, string> {
const attrs: Record<string, string> = {
'data-anno-id': a.id,
'data-anno-kind': a.kind,
'data-anno-lateral': a.laterality,
}
if (a.kind === 'detail_trigger') {
attrs['data-anno-opens-view'] = a.opens_view_id
attrs['data-anno-name-fr'] = a.name?.fr ?? viewName
attrs['data-anno-name-en'] = a.name?.en ?? viewName
} else {
attrs['data-anno-name-fr'] = a.name.fr
attrs['data-anno-name-en'] = a.name.en
if (a.finding_zone_id) attrs['data-anno-zone'] = a.finding_zone_id
if (a.vertebral_region_code)
attrs['data-anno-region'] = a.vertebral_region_code
}
const state = input.states?.get(a.id)
if (state) attrs['data-state'] = state
return attrs
}
function pointElements(
geometry: Extract<Geometry, { type: 'circle' }>,
color: string,
style: MarkerStyle,
data: Record<string, string>,
label: string,
): LayerElement[] {
const hitbox = el(
'circle',
{
...geometryAttrs(geometry)[1],
fill: 'transparent',
'pointer-events': 'all',
style: 'cursor:pointer',
...data,
},
[title(label)],
)
const visible = el(
'circle',
{
cx: String(geometry.cx),
cy: String(geometry.cy),
r: String(Math.max(2, geometry.r - style.visibleInset)),
fill: color,
'fill-opacity': String(style.visibleFillOpacity),
stroke: style.visibleStroke,
'stroke-width': String(style.visibleStrokeWidth),
'pointer-events': 'none',
...data,
},
[title(label)],
)
return [hitbox, visible]
}
function shapeElement(
geometry: Geometry,
color: string,
visual: Record<string, string>,
data: Record<string, string>,
label: string,
): LayerElement {
const [tag, attrs] = geometryAttrs(geometry)
return el(tag, { ...attrs, fill: color, stroke: color, ...visual, ...data }, [
title(label),
])
}
function annotationElements(
a: Annotation,
input: LayerInput,
style: MarkerStyle,
categories: Map<string, string | null>,
viewName: string,
): LayerElement[] {
if (!a.geometry) return []
const color = colorOf(a, categories)
const data = dataAttrs(a, input, viewName)
const label = `${data['data-anno-name-fr']} / ${data['data-anno-name-en']}`
if (a.kind === 'detail_trigger') {
const visual = {
'fill-opacity': String(style.triggerFillOpacity),
'stroke-width': String(style.triggerStrokeWidth),
'stroke-dasharray': style.triggerDash,
'pointer-events': 'all',
style: 'cursor:pointer',
class: 'detail-zone',
}
return [shapeElement(a.geometry, color, visual, data, label)]
}
if (a.geometry.type === 'circle') {
return pointElements(a.geometry, color, style, data, label)
}
const visual = {
'fill-opacity': String(style.zoneFillOpacity),
'stroke-width': String(style.zoneStrokeWidth),
'pointer-events': 'all',
style: 'cursor:pointer',
}
return [shapeElement(a.geometry, color, visual, data, label)]
}
/** The layer `<g>` of one view: every annotation of that view, in document order. */
export function renderAnnotationLayer(input: LayerInput): LayerElement {
const { document, viewId } = input
const view = document.views.find((v) => v.id === viewId)
if (!view) throw new Error(`unknown view "${viewId}"`)
const style = styleForView(view)
const categories = new Map(
document.categories.map((c) => [c.id, c.color ?? null]),
)
const viewNames = new Map(document.views.map((v) => [v.id, v.name.fr]))
const children = document.annotations
.filter((a) => a.view_id === viewId)
.flatMap((a) => {
const opened =
a.kind === 'detail_trigger'
? (viewNames.get(a.opens_view_id) ?? '')
: ''
return annotationElements(a, input, style, categories, opened)
})
return el(
'g',
{ [LAYER_ATTRIBUTE]: LAYER_NAME, 'data-view-id': viewId },
children,
)
}
/** `viewBox` attribute value the view renders with, or null for the asset's own. */
export function viewBoxOf(view: SheetView): string | null {
const box = view.view_box
return box ? `${box.min_x} ${box.min_y} ${box.width} ${box.height}` : null
}
+25
View File
@@ -0,0 +1,25 @@
import type { LayerElement } from './layer'
/** Serialises a layer tree to SVG text (review drawings, tests). */
function escape(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
export function serializeLayer(node: LayerElement, indent = ''): string {
const attrs = Object.entries(node.attrs)
.map(([k, v]) => ` ${k}="${escape(v)}"`)
.join('')
if (node.text !== undefined) {
return `${indent}<${node.tag}${attrs}>${escape(node.text)}</${node.tag}>`
}
if (node.children.length === 0) return `${indent}<${node.tag}${attrs}/>`
const inner = node.children
.map((child) => serializeLayer(child, `${indent} `))
.join('\n')
return `${indent}<${node.tag}${attrs}>\n${inner}\n${indent}</${node.tag}>`
}
@@ -0,0 +1,183 @@
import { ReportMigrationMapSchema } from '@faunosteo/domain'
import { beforeAll, describe, expect, it } from 'vitest'
import {
applyChangeset,
buildReportMigrationMap,
type DraftResult,
type ImportResult,
} from '../src'
import { changesetOf, MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
import { runDraft } from './helpers'
const SHEET = {
sheetId: 'sheet',
versionId: null,
documentSha256: 'f'.repeat(64),
}
describe('report migration map on the real draft', () => {
let result: ImportResult
let draft: DraftResult
let map: ReturnType<typeof buildReportMigrationMap>['map']
let stats: ReturnType<typeof buildReportMigrationMap>['stats']
beforeAll(async () => {
;({ result, draft } = await runDraft())
;({ map, stats } = buildReportMigrationMap({
baseline: draft.baseline as Record<string, unknown>,
final: draft.document as Record<string, unknown>,
legacyIdMap: draft.legacyIdMap,
records: draft.records,
sheet: SHEET,
mainViewId: 'main',
}))
})
it('is a valid map covering every legacy node, with the expected fates', () => {
expect(ReportMigrationMapSchema.parse(map)).toBeTruthy()
expect(stats).toEqual({
nodes: 792,
identical: 571,
remapped: 180,
rehomed: 7,
removed: 34,
})
expect(Object.keys(map.finding_paths)).toHaveLength(792)
})
it('maps every legacy annotation with its legacy labels and the views', () => {
expect(Object.keys(map.annotations)).toHaveLength(27)
expect(map.annotations['point-mpbwtst0']).toEqual({
id: 'hip',
name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' },
})
expect(map.annotations['zone-mpby55kd']).toEqual({
id: 'head-trigger',
name: { fr: '', en: '' },
})
expect(map.views).toEqual({ head: 'head' })
expect(map.main_view_id).toBe('main')
expect(result.legacyIdMap.annotations['point-mpbwtst0']).toBe('hip')
})
it('every target path exists in the draft; identical, renamed, re-homed and removed cases', () => {
const final = new Set<string>()
for (const zone of draft.document.finding_zones) {
const walk = (
nodes: readonly { id: string; children?: readonly unknown[] }[],
prefix: string,
) => {
for (const n of nodes) {
final.add(`${prefix}/${n.id}`)
walk((n.children ?? []) as never, `${prefix}/${n.id}`)
}
}
walk(zone.categories as never, zone.id)
}
for (const target of Object.values(map.finding_paths)) {
if (target !== null) expect(final.has(target), target).toBe(true)
}
expect(
map.finding_paths['hip/hip-dysfunctions/articular/restriction-flexion'],
).toBe('hip/hip-dysfunctions/articular/restriction-flexion')
expect(
map.finding_paths[
'cervical/cervical-observations/stumbling-proprioceptive'
],
).toBe('cervical/cervical-consultation-reasons/stumbling-proprioceptive')
expect(
map.finding_paths[
'sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-tension'
],
).toBe('sacroiliac/sacroiliac-dysfunctions/muscular/sacrotuberous-ligament')
expect(
map.finding_paths['sphenoid/ssb-dysfunctions/sutures/sphenopetrosal'],
).toBe('sphenoid/sphenoid-dysfunctions/sutures/sphenopetrosal')
expect(
map.finding_paths['ssb/ssb-dysfunctions/sutures/sphenozygomatic'],
).toBeNull()
expect(
map.finding_paths['frontal/frontal-dysfunctions/sutures/frontozygomatic'],
).toBeNull()
})
})
describe('report migration map replay on a synthetic changeset', () => {
function mapOf(ops: Parameters<typeof changesetOf>[0]) {
const baseline = miniSheet()
const result = applyChangeset(baseline, MINI_REFERENCES, changesetOf(ops))
return buildReportMigrationMap({
baseline: miniSheet() as never,
final: result.document as never,
legacyIdMap: {
views: { head: 'head' },
annotations: { 'legacy-hip': 'hip' },
categories: {},
finding_nodes: {},
assets: {},
},
records: result.records,
sheet: SHEET,
mainViewId: 'main',
})
}
it('follows a rename, a move and a removal, and a renamed annotation', () => {
const { map, stats } = mapOf([
{
op: 'rename',
target: 'finding:hip/hip-dysfunctions/mobility',
id: 'motion',
},
{
op: 'move',
target: 'finding:hip/hip-dysfunctions/motion/flexion',
to: 'finding:hip/anamnesis',
},
{ op: 'remove', target: 'finding:neck/neck-dysfunctions/vet' },
{ op: 'rename', target: 'annotation:hip', id: 'coxofemoral' },
])
expect(map.finding_paths['hip/hip-dysfunctions/mobility/extension']).toBe(
'hip/hip-dysfunctions/motion/extension',
)
expect(map.finding_paths['hip/hip-dysfunctions/mobility/flexion']).toBe(
'hip/anamnesis/flexion',
)
expect(map.finding_paths['neck/neck-dysfunctions/vet']).toBeNull()
expect(map.finding_paths['neck/neck-dysfunctions/stiffness']).toBe(
'neck/neck-dysfunctions/stiffness',
)
expect(map.annotations['legacy-hip']!.id).toBe('coxofemoral')
expect(stats.removed).toBe(1)
})
it('re-homes a node whose category was replaced by another one holding the same path', () => {
const { map, stats } = mapOf([
{
op: 'add',
target: 'zone:hip',
value: {
id: 'hip-new',
kind: 'dysfunction',
name: { fr: 'N', en: 'N' },
children: [
{
id: 'mobility',
name: { fr: 'M', en: 'M' },
children: [{ id: 'flexion', name: { fr: 'F', en: 'F' } }],
},
],
},
},
{ op: 'remove', target: 'finding:hip/hip-dysfunctions' },
])
expect(map.finding_paths['hip/hip-dysfunctions/mobility/flexion']).toBe(
'hip/hip-new/mobility/flexion',
)
expect(
map.finding_paths['hip/hip-dysfunctions/mobility/extension'],
).toBeNull()
expect(map.finding_paths['hip/hip-dysfunctions']).toBeNull()
expect(stats.rehomed).toBe(2)
})
})
+158
View File
@@ -0,0 +1,158 @@
import { DOMParser } from '@xmldom/xmldom'
import { beforeAll, describe, expect, it } from 'vitest'
import {
createLayerElement,
renderAnnotationLayer,
serializeLayer,
styleForView,
type DraftResult,
type LayerElement,
} from '../src'
import { miniSheet } from './fixtures/mini-sheet'
import { runDraft } from './helpers'
function flatten(node: LayerElement): LayerElement[] {
return [node, ...node.children.flatMap(flatten)]
}
function byId(layer: LayerElement, id: string): LayerElement[] {
return flatten(layer).filter((n) => n.attrs['data-anno-id'] === id)
}
describe('annotation layer on the real draft', () => {
let draft: DraftResult
beforeAll(async () => {
;({ draft } = await runDraft())
})
it('draws every annotation of the main view as the legacy pair, zone or trigger', () => {
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'main',
})
expect(layer.attrs).toEqual({
'data-layer': 'annotations',
'data-view-id': 'main',
})
const main = draft.document.annotations.filter((a) => a.view_id === 'main')
for (const a of main) {
const els = byId(layer, a.id)
if (a.kind === 'point')
expect(els.map((e) => e.tag)).toEqual(['circle', 'circle'])
else expect(els).toHaveLength(1)
}
const [hitbox, visible] = byId(layer, 'hip')
expect(hitbox!.attrs).toMatchObject({
r: '34',
fill: 'transparent',
'pointer-events': 'all',
'data-anno-lateral': 'bilateral',
'data-anno-zone': 'hip',
})
expect(visible!.attrs).toMatchObject({
r: '22',
fill: '#ff9500',
'fill-opacity': '0.65',
stroke: '#000',
'stroke-width': '1.5',
'pointer-events': 'none',
})
expect(hitbox!.children[0]).toMatchObject({
tag: 'title',
text: 'Hanche (coxo-fémorale) / Hip joint',
})
const [spine] = byId(layer, 'cervical')
expect(spine!.tag).toBe('polygon')
expect(spine!.attrs).toMatchObject({
fill: '#e100ff',
'fill-opacity': '0.3',
'stroke-width': '2',
'data-anno-region': 'C',
})
const [trigger] = byId(layer, 'head-trigger')
expect(trigger!.attrs).toMatchObject({
'data-anno-kind': 'detail_trigger',
'data-anno-opens-view': 'head',
'stroke-dasharray': '8,4',
'fill-opacity': '0.06',
class: 'detail-zone',
})
expect(trigger!.attrs['data-anno-name-fr']).toBe(
'Tête (vue latérale gauche)',
)
})
it('uses the detail style, the annotation colour override and the view box on the head view', () => {
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'head',
})
const [c0c1Hit, c0c1Vis] = byId(layer, 'c0-c1')
expect(c0c1Hit!.attrs.r).toBe('27')
expect(c0c1Vis!.attrs).toMatchObject({
r: '15',
fill: '#ff0000',
'fill-opacity': '0.5',
})
expect(byId(layer, 'atm')[1]!.attrs.fill).toBe('#ff8800')
expect(byId(layer, 'hyoid')[1]!.attrs.fill).toBe('#d507c4')
expect(byId(layer, 'parietal')[1]!.attrs.fill).toBe('#1baa08')
expect(styleForView(draft.document.views[1]!).visibleFillOpacity).toBe(0.5)
expect(flatten(layer).some((n) => n.attrs['data-anno-id'] === 'hip')).toBe(
false,
)
})
it('applies states as data-state on both elements of a point', () => {
const states = new Map([['hip', 'current' as const]])
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'main',
states,
})
expect(
byId(layer, 'hip').every((e) => e.attrs['data-state'] === 'current'),
).toBe(true)
expect(
byId(layer, 'stifle').every((e) => e.attrs['data-state'] === undefined),
).toBe(true)
})
it('materialises through a DOM and serialises to the same markup', () => {
const layer = renderAnnotationLayer({
document: draft.document,
viewId: 'head',
})
const doc = new DOMParser().parseFromString(
'<svg xmlns="http://www.w3.org/2000/svg"/>',
'image/svg+xml',
)
const element = createLayerElement(
doc as never,
layer,
) as unknown as Element
expect(element.getAttribute('data-layer')).toBe('annotations')
expect(element.getElementsByTagName('circle')).toHaveLength(18)
const text = serializeLayer(layer)
expect(text).toContain('<g data-layer="annotations" data-view-id="head">')
expect(text).toContain('<title>Appareil hyoïdien / Hyoid apparatus</title>')
expect(text).not.toContain('<script')
})
})
describe('annotation layer edge cases', () => {
it('skips annotations without geometry and falls back to grey without any colour', () => {
const sheet = miniSheet()
const layer = renderAnnotationLayer({ document: sheet, viewId: 'main' })
const ids = new Set(
flatten(layer)
.map((n) => n.attrs['data-anno-id'])
.filter(Boolean),
)
expect(ids.has('hip')).toBe(true)
expect(byId(layer, 'hip')[1]!.attrs.fill).toBe('#888888')
expect(() =>
renderAnnotationLayer({ document: sheet, viewId: 'nope' }),
).toThrow('unknown view')
})
})