diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-1-domain.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-1-domain.md new file mode 100644 index 00000000..68804939 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-1-domain.md @@ -0,0 +1,26 @@ +# CONTRACT — step-06 phase 1 domain +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: active +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (types), §14 "Read" steps 1-3 and "Bundle", §15 caps table (snapshot + branding rows), §2.2 (lean document content) + +## REQUEST (IMMUTABLE) +Give the domain package the archive contracts (sheet snapshot, envelope v1, branding, labels), the layered reader, the report rebase, and move the sheet index into the domain; make the bundle carry the asset hashes. Pure TypeScript + Zod, no DOM, no pdf-lib. The app keeps compiling and its suite stays green through re-export shims; no app behaviour changes in this phase. + +## ACCEPTANCE CRITERIA +1. `packages/domain/src/anatomical-sheet/sheet-index.ts` holds `buildSheetIndex`, `pickLabel`, `isObservable`, `SheetIndex`, `ObservableAnnotation`, `SheetIndexSource = { ref: { documentSha256: string }; document: AnatomicalSheetDocument; assets: Readonly> }` (generic so `SheetIndex['sheet']` keeps the caller's type: `buildSheetIndex(sheet: S): SheetIndex`); `pickLabel(text, locale: 'fr' | 'en')`. `apps/app/src/services/sheetIndex.ts` becomes a re-export of it (no other app file edited for this move). + CHECK: cd apps/app && corepack pnpm typecheck && corepack pnpm vitest run tests/unit/sheets.provider.test.ts 2>&1 | tail -2 + EXPECT: passed +2. `packages/domain/src/archive/` with `snapshot.ts` (`SheetSnapshotRef`, `SheetSnapshotAsset`, `SheetSnapshot`, `SheetSnapshotSchema`, `SnapshotSource`, `buildSheetSnapshot`, `assertSnapshot`, `SnapshotError`, `SnapshotRejection`, `snapshotIndexSource(snapshot): SheetIndexSource`), `branding.ts` (`ImageAsset`, `Credit`, `Branding`, `BrandingSchema`), `labels.ts` (`PDF_LABEL_KEYS`, `PdfLabels`, `PdfLabelSet`, `PdfLabelSetSchema`), `envelope.ts` (`ENVELOPE_FORMAT`, `ENVELOPE_VERSION`, `ReportArchiveEnvelope`, `ReportArchiveEnvelopeSchema`, `ArchiveOrigin`, `ArchiveReadOutcome`, `readArchiveDocument`), `index.ts`; exported as `@faunosteo/domain/archive` (package.json exports) and from the root index. Types and behaviour exactly as spec §13/§14; `SnapshotSource = { status; ref: SheetRef; speciesId; schemaVersion; document; assets; assetHashes? }` so that `LoadedSheet` satisfies it; snapshot `ref` = `{ ...sheet.ref, schemaVersion, speciesId }`. + CHECK: cd packages/domain && corepack pnpm vitest run tests/archive.snapshot.test.ts tests/archive.envelope.test.ts tests/archive.branding-labels.test.ts 2>&1 | tail -3 + EXPECT: Tests .* passed +3. `buildSheetSnapshot(sheet, report)` is pure and deterministic: document = all views, annotations, categories, vertebral_config, name/description/scope_disclaimer/attribution/species_id/schema_version kept; `references: []`; every finding zone kept as `{ id, name, categories }` where categories are pruned to the paths referenced by the report's findings (resolved or `unresolved`): category `{ id, kind, name, description: {}, reference_ids: [], review_status, children }`, node `{ id, name, description: {}, requires_vet_referral, reference_ids: [], review_status, children }`; zones not referenced have `categories: []`; assets = every asset reachable from a view (own `svg_asset_id` or parent chain), `sha256` from `assetHashes` or null. On the draft with the fixture report `apps/app/tests/fixtures/report-v2.full.json` migrated: the document passes `AnatomicalSheetDocumentSchema` and `validateSheetDocument` returns no `error` issue; pretty JSON of the snapshot (with the SVG) is under 250,000 bytes (print the number in the test output). +4. `assertSnapshot` order: iterative depth pre-check of `finding_zones[].categories[].children` (> 8 → `caps`) → `SheetSnapshotSchema.parse` (strict wrapper; failure → `schema`) → counters (views ≤ 64, annotations ≤ 1024, nodes ≤ 8192, any LocalizedText value > 512 chars, assets ≤ 4 / ≤ 2 MiB each / ≤ 6 MiB total → `caps`) → `validateSheetDocument` has an `error` → `integrity` → a view that reaches no asset present in `assets` → `integrity`. Tests cover each reason and the happy path. +5. `readArchiveDocument(data, map)` implements spec §14 "Read" steps 1-3 exactly, with these cases tested: bare v3 → `origin 'bare_v3'`, `archive null`, counts 0; bare v2 (fixture) → `'v2'`, `migrated true`, counts from the migration; envelope v1 valid → `'envelope_v1'`, `archive` = validated envelope, `migrated false`; envelope with `envelopeVersion: 2` and report v3 → report returned, `snapshotRejected 'unsupported_envelope'`; envelope v1 with report `version: 4` → throws `UnsupportedReportVersionError` with foundVersion 4; envelope v1 with unknown extra metadata key → accepted; envelope v1 with broken branding → `'schema'`; snapshot over caps → `'caps'`; snapshot ref sheetId/documentSha256 ≠ report.sheet → `'sheet_mismatch'`; `__proto__` keys harmless; non-object → throws. +6. `packages/domain/src/report/rebase.ts`: `rebaseReportOnSheet(report, index, archived)` as spec §13; tests: same sha → untouched, `rebased false`; different sha → unknown annotation → `unresolved: true` + labels from the archived snapshot's annotation name (both locales) when the zone had none; unknown viewId → unresolved; finding with no node → unresolved; already-unresolved items stay; resolved items untouched; `report.sheet` replaced by `index.sheet.ref`; output passes `ReportSchema`. +7. Bundle: `apps/app/vite/sheet-bundle.ts` payload gains `assetHashes` (from `assets.json` `sha256` by `svg_asset_id`); `apps/app/src/sheets/provider.ts` `BundledSheetData`/`LoadedSheet` gain `assetHashes: Readonly>` and `schemaVersion: number` (from `ref.schema_version`); `parseBundledSheet` fills them; `tests/unit/sheets.provider.test.ts` asserts the hash of the horse asset equals the manifest value. +8. Green everywhere: `corepack pnpm -r typecheck && corepack pnpm -r lint && corepack pnpm -r test:run` from the repo root (domain, anatomy, supabase, app). The Phase 0 golden tests and route characterisation tests under apps/app/tests must pass unchanged. + CHECK: cd /home/bchanot/Documents/faunosteo && corepack pnpm typecheck 2>&1 | tail -2 && corepack pnpm test:run 2>&1 | grep -E "Tests|Test Files" | tail -8 + EXPECT: all passed + +## FILE SCOPE +packages/domain/** (src/anatomical-sheet/sheet-index.ts new, src/archive/* new, src/report/rebase.ts new, index files, package.json exports, tests/archive.*.test.ts, tests/report.rebase.test.ts, tests/sheet-index.test.ts), apps/app/src/services/sheetIndex.ts (re-export only), apps/app/vite/sheet-bundle.ts, apps/app/src/sheets/provider.ts, apps/app/src/sheets/virtual-sheet.d.ts if needed, apps/app/tests/unit/sheets.provider.test.ts. Nothing under apps/app/src/pdf, packages/anatomy, packages/pdf. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-2-compose.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-2-compose.md new file mode 100644 index 00000000..43b788ba --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-2-compose.md @@ -0,0 +1,25 @@ +# CONTRACT — step-06 phase 2 compose +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: active +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §14 "composeViewSvg", §13 (Rasterizer not in scope here) + +## REQUEST (IMMUTABLE) +Promote the Node-side view composer of the curation pipeline (`packages/anatomy/src/curation/app-review.ts`) into the shared renderer as `composeViewSvg`, with an optional highlight applied on the LayerElement tree before it becomes DOM, so the PDF engine (Phase 3) can compose a highlighted view without a browser and without querySelector. The review drawings stay byte-identical. + +## ACCEPTANCE CRITERIA +1. `packages/anatomy/src/render/compose.ts` exports `composeViewSvg(input: { root: Element; document: AnatomicalSheetDocumentInput; viewId: string; highlight?: { annotationIds: ReadonlySet; halo: boolean } }): Element` and `HALO_FILTER_ID = 'osteo-halo'`; it uses only DOM Level 2 APIs on `root` and `root.ownerDocument` (no xmldom import, no querySelector, no `el.remove()`); exported from `packages/anatomy/src/render/index.ts`. + CHECK: grep -n "querySelector\|\.remove()\|xmldom" packages/anatomy/src/render/compose.ts; echo "rc=$?" + EXPECT: rc=1 +2. Without `highlight`, output = today's `renderAppReviewDrawing` output: `curation/app-review.ts` becomes a thin caller (parse with xmldom, call `composeViewSvg`, serialise) and the committed review drawings do not drift. + CHECK: cd packages/anatomy && corepack pnpm test:run 2>&1 | tail -3 + EXPECT: Tests .* passed (including the existing golden-artifacts test) +3. With `highlight`: only layer elements whose annotation id is in `annotationIds` remain; each gets `fill="#b85a3f"`, `fill-opacity="0.85"` and, when `halo`, `filter="url(#osteo-halo)"`; no `data-*` attribute is emitted on any layer element; `` children are kept; when `halo`, a `<defs>` (created as FIRST child when the asset has none) holds the `osteo-halo` filter exactly as `apps/app/src/pdf/render/observationPage.ts:157-197` (x/y "-100%", width/height "300%", filterUnits userSpaceOnUse, feGaussianBlur stdDeviation 18 result haloWide, feGaussianBlur stdDeviation 8 result haloTight, both in=SourceGraphic, feMerge of haloWide×3, haloTight×2, SourceGraphic); the layer `<g>` is appended last; `viewBox` set from `viewBoxOf(view)` when present; `width`/`height` removed from the root. + CHECK: cd packages/anatomy && corepack pnpm vitest run tests/render.compose.test.ts 2>&1 | tail -3 + EXPECT: Tests .* passed +4. Tests (xmldom, draft document + draft horse.svg): main view with two selected annotations (one point → both hitbox and twin highlighted, one spine zone), head view (no halo), nothing selected (layer empty), unknown view throws, idempotent halo (no duplicate filter when called on a root that already has one), highlight keeps `<title>`, zero `data-` attributes in the serialised output, review-mode output byte-identical to the previous `renderAppReviewDrawing` for both views. +5. `pnpm typecheck && pnpm lint && pnpm test:run` green in packages/anatomy; no other package changed. + CHECK: git -C /home/bchanot/Documents/faunosteo status --short | grep -v "^?? packages/anatomy\|^ M packages/anatomy" | grep -v ".claude/" | wc -l + EXPECT: 0 + +## FILE SCOPE +packages/anatomy/src/render/compose.ts (new), packages/anatomy/src/render/index.ts, packages/anatomy/src/curation/app-review.ts, packages/anatomy/tests/render.compose.test.ts (new). Nothing else. diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-3-engine.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-3-engine.md new file mode 100644 index 00000000..0bb4c082 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-3-engine.md @@ -0,0 +1,29 @@ +# CONTRACT — step-06 phase 3 engine +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: draft (dispatched after phases 1 and 2 land) +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (packages/pdf block), §14 (Export, Label policy, View SVG, Read), §15 (caps, sanitiser, text), §17 (goldens the engine must reproduce), §3.3 + +## REQUEST (IMMUTABLE) +Create `packages/pdf` (`@faunosteo/pdf`): the browser-free PDF engine that exports a report archive from explicit inputs (report, sheet snapshot, branding, labels, locale, rasterizer, exportedAt) and reads an archive back (layered reading). Render code moves from `apps/app/src/pdf` with its behaviour frozen by the Phase 0 goldens. The app is NOT wired in this phase (Phase 4); `apps/app/src` is not modified. + +## ACCEPTANCE CRITERIA +1. Package scaffold: `packages/pdf/{package.json,tsconfig.json,vitest.config.ts,eslint.config.js,src/,tests/}` following packages/domain conventions; dependencies `pdf-lib ^1.17.1`, `@pdf-lib/standard-fonts ^1.0.0` (for `Encodings.WinAnsi`), `@faunosteo/domain workspace:*`, `@faunosteo/anatomy workspace:*`, `@xmldom/xmldom ^0.9.8`; devDependencies as domain plus `@resvg/resvg-js` (latest 2.x) and `@pdf-lib/upng ^1.0.1` (PNG decode in tests); tsconfig `lib: ["ES2022"]`, `types: ["node","vitest/globals"]`; eslint on `src/**`: `no-restricted-globals` for fetch, window, document, Image, DOMParser, XMLSerializer, navigator, Buffer, process, require and `no-restricted-imports` for patterns `@/*`, `react*`, `node:*`; vitest `environment: 'node'`. Dockerfile copies `packages/pdf/package.json`; `packages/README.md` row updated. + CHECK: cd packages/pdf && corepack pnpm typecheck && corepack pnpm lint && echo ok + EXPECT: ok +2. Public API of `packages/pdf/src/index.ts` exactly spec §13: `exportReportArchive`, `exportFromEnvelope`, `readReportArchive`, `readAttachedDocument`, `ArchiveReadError` (kinds invalid_pdf | no_attachment | attachment_stripped | incompatible_version), `ArchiveExportError` (kinds snapshot_invalid | snapshot_too_large | sheet_mismatch | too_many_pages), `Rasterizer`, `ExportInput`, `ExportResult`, `ExportWarning`, `PdfLocale`, `defaultPdfLabels`, `PDF_KEYWORD`, `MAX_PDF_BYTES`, `MAX_ATTACHMENT_BYTES`, plus `composeHighlightedViewSvg(sheet: SheetSnapshot, viewId, observation): string` for tests and the app. +3. Export behaviour = spec §14 "Export" steps 1-10 and "Label policy"; branding images: `kind 'png'` → base64 decoded with `atob` → `embedPng`; `kind 'svg'` → sanitised + rasterised at width 1200 (height from its viewBox, same clamp) → `embedPng`; each slot fails alone (`logo_failed` warning); view raster failure → page without image + `view_raster_failed`; parallel rasterisation, sequential embedding in view order; `exportedAt` drives every date; `setKeywords([PDF_KEYWORD])`; envelope attached pretty-printed as `osteo-report.json`, description `Faunosteo report archive v1`. +4. Goldens (T3): `tests/goldens.test.ts` reproduces every Phase 0 golden under `apps/app/tests/fixtures/goldens/step6/` for the three reports (v2full migrated through the draft map, demo, v2unresolved rebuilt with the same recipe as Phase 0 — reuse the recipe by reading `apps/app/tests/helpers/legacyLeaves.ts` logic, copy what you need into `tests/helpers/`), two locales, two logo modes: text entries (page, text, x, y, size, font) identical; images identical; links identical; views facts identical except `titles` (hidden markers are absent in the engine; assert `titles` ≥ highlighted count instead). Logo modes: `nologos` = Branding with every logo null and credits with fallback texts, fake rasterizer returning the 1×1 PNG; `logos` = Branding built from the real `apps/app/public` files (PNG base64, Paws SVG), fake rasterizer returning the 2×1 PNG (same constants as Phase 0). Any mismatch is a visible change: do not "fix" the golden; report it. + CHECK: cd packages/pdf && corepack pnpm vitest run tests/goldens.test.ts 2>&1 | tail -3 + EXPECT: Tests .* passed +5. T1 no-sheet re-export (`tests/reexport.test.ts`): export demo from a snapshot built with `buildSheetSnapshot` on the draft loaded from `supabase/seed/anatomical-sheets/equine/draft/` → `readReportArchive` → `exportFromEnvelope` → identical text/images/views facts; envelope deep-equal minus `exportedAt`; the test file imports nothing that knows the draft after the first export (the second export receives only the envelope). +6. Read (`tests/read.test.ts`, T4 T5 T6): roundtrip envelope → `readReportArchive` → `archive` deep-equals the exported envelope, `origin 'envelope_v1'`; `apps/app/tests/fixtures/report-v2.full.pdf` and `report-v2.minimal.pdf` → `'v2'`, migrated, then re-export → import again equals; the 612-leaf v2 report (recipe from legacyLeaves) → 29 unresolved findings kept through export/import; `report-v3.bare.pdf` → `'bare_v3'`, `archive null`; envelope v2 wrapper → report kept + `snapshotRejected 'unsupported_envelope'`; envelope v1 with report v4 → `incompatible_version` foundVersion 4; bare `version: 7` → 7; a PDF with `Keywords` containing `faunosteo-archive` and no attachment → `attachment_stripped`; a foreign PDF → `no_attachment`; the Filespec named `osteo-report.json` is chosen over an earlier unrelated `EmbeddedFile` in a crafted PDF; > 50 MiB → `invalid_pdf`. +7. Security (`tests/security.test.ts`, T8): 5 assets, a 3 MiB asset, depth 9, 1,025 annotations, a view chain cycle, a dangling `svg_asset_id`, `sheet_mismatch` → report imported and `snapshotRejected` with the right reason; hostile SVG assets (`<script>`, `onload`, `javascript:` href, external `<image>`, `<!ENTITY>`, `<style>` with `url(http…)`, 257 `<use>`, root `viewBox="0 0 1 100000"`) → removed / refused / clamped as spec §15, the export still succeeds for the removable ones with the hostile parts gone, and `assertSnapshot` refuses the oversized ones at export with a typed error and no file; `__proto__` ids harmless; 24 MB inflate bomb → null (move the existing test); `horse.svg` and `Paws_in_harmony.svg` sanitise with `removed: []` and a serialisation byte-identical to the parsed input. +8. Text (`tests/text.test.ts`, T9): `safeText` keeps en dash, em dash, accented letters, `•`, `·`; replaces `⚠`, `→`, an emoji by `?`; strips `\t`, U+2028, ESC; `wrapLines` and every drawText go through it (a report with `⚠` in a comment exports without throwing); `formatDate` returns a non-ISO input unchanged. +9. Raster (`tests/raster.test.ts`, T10, resvg): a real `Rasterizer` built on `@resvg/resvg-js` (`fitTo width`) renders the demo report's main and head highlighted views: PNG width = 1200, height = requested ±1, pixels within ±24 of `#b85a3f` present, non-white ratio in [0.01, 0.9]; a rasterizer that throws yields a PDF whose page has no image and one `view_raster_failed` warning. +10. Size (T7): demo envelope attachment stored bytes (the EmbeddedFile stream `contents.length` found through `enumerateIndirectObjects`) < 250,000; the test prints stored and raw sizes for `nologos` and `logos` brandings. +11. Everything green: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run` in packages/pdf, and `corepack pnpm -r typecheck` at the root; `apps/app/src` untouched. + CHECK: git -C /home/bchanot/Documents/faunosteo status --short apps/app/src | wc -l + EXPECT: 0 + +## FILE SCOPE +packages/pdf/** (new), Dockerfile (one COPY line), packages/README.md (one row), pnpm-lock.yaml (install). Nothing under apps/app/src, packages/domain, packages/anatomy. diff --git a/packages/anatomy/src/curation/app-review.ts b/packages/anatomy/src/curation/app-review.ts index 7ff13708..e979301b 100644 --- a/packages/anatomy/src/curation/app-review.ts +++ b/packages/anatomy/src/curation/app-review.ts @@ -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) } diff --git a/packages/anatomy/src/render/compose.ts b/packages/anatomy/src/render/compose.ts new file mode 100644 index 00000000..482e5dd5 --- /dev/null +++ b/packages/anatomy/src/render/compose.ts @@ -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 +} diff --git a/packages/anatomy/src/render/index.ts b/packages/anatomy/src/render/index.ts index 96b61d67..001c708e 100644 --- a/packages/anatomy/src/render/index.ts +++ b/packages/anatomy/src/render/index.ts @@ -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' diff --git a/packages/anatomy/tests/render.compose.test.ts b/packages/anatomy/tests/render.compose.test.ts new file mode 100644 index 00000000..d875556c --- /dev/null +++ b/packages/anatomy/tests/render.compose.test.ts @@ -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) + }) +})