Merge feature/step-05-app-on-canonical-sheet into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s

This commit is contained in:
bchanot committed 2026-10-10 22:16:24 +02:00
commit 91131713b1
191 files changed
+10450 -14764

No files matched your search

+8
View File
@@ -319,3 +319,11 @@ Status: closed; content awaits professional review (REVIEW-REPORT §10, 9 questi
User decisions: curated equine draft = reference draft of the app until published (no publication without professional review); technical integrity ≠ medical validation (`inherited` / `reviewed` / `to_confirm` stay visible, REVIEW-REPORT the hand-off doc for the osteopath, 11 open questions → next changeset); future schema changes = incremental non-destructive migrations (BLK-008); legal scope text re-read on consolidated Légifrance texts before publication; head view preserved as crop, per-view assets still possible. Docker `faunosteo_` rule permanent; `.env.example` change documented in DEPLOY.md (file denied to Claude). SaaS development continues without waiting for medical validation. User decisions: curated equine draft = reference draft of the app until published (no publication without professional review); technical integrity ≠ medical validation (`inherited` / `reviewed` / `to_confirm` stay visible, REVIEW-REPORT the hand-off doc for the osteopath, 11 open questions → next changeset); future schema changes = incremental non-destructive migrations (BLK-008); legal scope text re-read on consolidated Légifrance texts before publication; head view preserved as crop, per-view assets still possible. Docker `faunosteo_` rule permanent; `.env.example` change documented in DEPLOY.md (file denied to Claude). SaaS development continues without waiting for medical validation.
Status: closed. Status: closed.
---
## BDR-038 | 2026-10-10 | Step 5: app on the canonical sheet — bundled sheet, layer renderer, Report v3, migration map
Sheet source: `SheetProvider` interface; Step 5 implementation = Vite virtual module `virtual:faunosteo-sheet` built from the seed draft (`vite/sheet-bundle.ts`), mode `SHEET_BUNDLE=draft|none`, default draft for dev server, none for builds/CI/Docker (`--build-arg SHEET_BUNDLE=draft` = explicit preview) → unvalidated draft never ships by accident (D2). Markers: pure renderer `@faunosteo/anatomy/render` (element tree, no DOM) reproduces legacy look (hitbox r + twin r−12, opacities 0.65/0.5, spine 0.3, trigger 0.06 dashed); colours = document data (`categories[].color`, additive `annotations[].color` for the head shades, schema_version stays 2 for additive optional fields); same renderer feeds `draft/review/app-<view>.svg` for visual checks. Report v3 in packages/domain: `(annotationId, viewId)` zones with label snapshots, `(findingZoneId, path)` findings, severity codes, `sheet {sheetId, versionId|null, documentSha256}`, `unresolved: true` for what migration cannot place, `localAnnotations: []` reserved. Migration map generated by the pipeline from applier records (replay renames/moves/removals + unique re-homing): 792 nodes → 571/180/7/34. Interaction = pure service + reducers (BDR-019 kept); store = v3 + persistence adapter (v2 draft migrated on restore). D4 applied: registry, matchers, SVG parser, editors, pathology-editor, public species assets deleted; legacy sources moved to `supabase/seed/.../legacy-sources/` (importer input).
Alt rejected: copying the draft into apps/app (duplication, drift); runtime fetch of `/sheets/*.json` (still public, no gain); UUID annotation ids (BDR-031); converting v3→v2 for attachments (lossy); per-view colour table in the app (horse knowledge in generic code).
Status: closed; awaiting user validation of Step 5.
+17
View File
@@ -80,3 +80,20 @@ Method: 4 research agents (skull, axial, limbs, osteo/legal), every citation tag
Result: verifier pass 1 ECARTS(4): B changes left targets `inherited` (CHG-008/032/039 + partials), 3 stale doc numbers, lockfile outside contract scope (orchestrator omission), eslint-disable any in a test → executor: applier rule (B/C ⇒ touched findings/annotations `to_confirm`, `reviewed` refused in B/C), typed test reads, docs. Pass 2 ECARTS(2): JSAVA citation without author (completed from the PDF: Le Roux & Carstens 2018, DOI), DEPLOY.md stale `faunosteo-web`. Pass 3 ECARTS(1): 3 stale doc lines (migration list, "two assets", CLAUDE.md migrations) → fixed by hand, cap of 3 verifier passes reached, not re-verified. Security PASS, LOW: SQL gate did not check reference url scheme → `reference.url.scheme` added (migration still unmerged, pgTAP 008 10 cases); `.env.example` COMPOSE_PROJECT_NAME=osteo-report overrides compose `name:` → file denied to Claude, user action. Result: verifier pass 1 ECARTS(4): B changes left targets `inherited` (CHG-008/032/039 + partials), 3 stale doc numbers, lockfile outside contract scope (orchestrator omission), eslint-disable any in a test → executor: applier rule (B/C ⇒ touched findings/annotations `to_confirm`, `reviewed` refused in B/C), typed test reads, docs. Pass 2 ECARTS(2): JSAVA citation without author (completed from the PDF: Le Roux & Carstens 2018, DOI), DEPLOY.md stale `faunosteo-web`. Pass 3 ECARTS(1): 3 stale doc lines (migration list, "two assets", CLAUDE.md migrations) → fixed by hand, cap of 3 verifier passes reached, not re-verified. Security PASS, LOW: SQL gate did not check reference url scheme → `reference.url.scheme` added (migration still unmerged, pgTAP 008 10 cases); `.env.example` COMPOSE_PROJECT_NAME=osteo-report overrides compose `name:` → file denied to Claude, user action.
Anomalies: ImageMagick MSVG drops `fill="none"` shapes and shapes with `<title>` child (LRN-042); two legacy points (t18-l1, l6-s1) floated above the silhouette, found only by the overlay render, not by the catalog audit; Supabase `db reset` unconfirms the asset row (upload script must re-run: objects kept, row confirmed). Anomalies: ImageMagick MSVG drops `fill="none"` shapes and shapes with `<title>` child (LRN-042); two legacy points (t18-l1, l6-s1) floated above the silhouette, found only by the overlay render, not by the catalog audit; Supabase `db reset` unconfirms the asset row (upload script must re-run: objects kept, row confirmed).
Action: user validation of the draft content (REVIEW-REPORT §10: 11 questions); never publish; Step 5 only after validation. Action: user validation of the draft content (REVIEW-REPORT §10: 11 questions); never publish; Step 5 only after validation.
---
## EVAL-011 | 2026-10-10 | Step 5 app on the canonical sheet — suites on the bundled sheet, archive PDFs, gates
Method: golden v2 PDFs frozen from the old pipeline before any change; suites rewritten on the bundled draft (domain 94, anatomy 107, supabase 21, app 168+: service branches 10/5/12/1, store + v2 draft migration, provider, canvas, pickers, card, route click chain, PDF v3 roundtrip FR/EN + both v2 fixtures + synthetic removed/unknown ids); root check, vite builds none/draft (grep of a draft label in dist = 0/1), docker build, real stack 267/267 + types; legacy-vs-app marker style diff by the verifier (0 differences); fresh verifier ×3 + security-auditor ×1.
Result: verifier pass 1 ECARTS(36) = 4 real (golden test not pinning the new generated files, EditorRoute 398 lines, 5 stale doc lines, one eslint-disable) + my contract omissions (scope files, deleted legacy suites) + floor noise ("species" matched "spec"); pass 2 ECARTS(4) = replacement assertions missing for 4 deleted suites; pass 3 ECARTS(4) = doc counts + 3 more suites' assertions (PDF conclusion/metadata/attachment structure, ObservationCard, persistence). All closed by executors (two) and by hand (docs); cap of 3 passes reached → last lot not re-verified. Security PASS with LOW: prototype-key lookup on untrusted ids (fixed: Object.hasOwn + test), unbounded inflate on the primary attachment path + no file cap (fixed: 16 MiB attachment, 50 MB PDF + test), denylist SVG sanitiser acceptable while assets are repo-built (allowlist before Storage-served assets, Step 13).
Anomalies: executor ran `pnpm format` repo-wide and reverted by hand (watch for `format` in briefs); foreign JSON attachment (no version) surfaced as incompatible_version → fixed to no_attachment (legacy message); verifier floor counts deleted legacy tests as findings until CLARIFICATIONS name them.
Action: user validation of Step 5 (manual FR/EN flow, visual before/after); BDR-038, LRN-043.
## EVAL-012 | 2026-10-10 | Step 5 addendum during user manual validation — per-leaf migration tests, archive check tool, final controls
Method: user asked (while testing) for final controls on last lot + per-leaf test beyond the map + simple v2/v3 PDF comparison method. Built: anatomy test all 612 legacy leaves through `migrateReportV2ToV3` with committed map vs draft document (442 identical / 141 moved = 134 category + 7 leaf renames / 29 removed, snapshots + vet flag verbatim, 26 annotations on right view, v3 re-read stable); app test same leaves via `sheetIndex.nodeAt` + v3 PDF roundtrip; CLI `pnpm report:compare` (pure module + entry, `readAttachedDocument` split out of `extractReportJson`, behaviour unchanged). Contract criteria 16-18 added, gates MET, fresh verifier ×3 + security ×2.
Result: verifier pass 1 ECARTS(2) = floor only (EVAL-011 prose "eslint-disable" false positive → CLARIFICATIONS; 11 dropped `regionFromLabel` assertions → new `legacy.regions.test.ts` on `inferRegionCode`); security PASS + 2 MEDIUM (terminal control chars in untrusted strings; free text printed by default) → executor: `esc()` + `--full` privacy default; pass 2 ECARTS(1) (`--diff` still clear text, JSON.parse message echoed attachment fragment) + security PASS 4 LOW → executor: diff follows `--full`, generic reason, Cc/Cf escaping, regular files only; pass 3 CONFORME. Workspace 94/21/119/181, docker build OK.
Anomalies: verifier stage runs after executor edits only (concurrent reads otherwise); gates.sh needs `EVIDENCE: PENDING` placeholder lines on new criteria. Residuals noted, not fixed: ZodError message echoes closed-vocabulary received values (never names), `compareReport` computes v3 lines twice, template-literal lines >80 chars, locals >5 in two functions.
Action: await user manual validation of Step 5; residuals in TODO follow-up.
+5
View File
@@ -190,3 +190,8 @@ Step 4 validated + finished into develop. User decisions on the 7 open points
- Gates 4c: verifier ×3 (4→2→1 écarts, last 3 doc lines fixed by hand at cap), executor closed the applier rule + typed tests; security PASS (LOW url scheme → SQL rule `reference.url.scheme`). Real stack 267/267, Storage e2e OK. EVAL-010. Awaiting user validation; `.env.example` COMPOSE_PROJECT_NAME left to the user (file denied). - Gates 4c: verifier ×3 (4→2→1 écarts, last 3 doc lines fixed by hand at cap), executor closed the applier rule + typed tests; security PASS (LOW url scheme → SQL rule `reference.url.scheme`). Real stack 267/267, Storage e2e OK. EVAL-010. Awaiting user validation; `.env.example` COMPOSE_PROJECT_NAME left to the user (file denied).
- Step 4c VALIDATED by user 2026-10-10 → tracking: head view check documented (spec §6), BLK-008 migration limit, BDR-037, DEPLOY.md `.env.example` note. Finished into develop. Next: Step 5 (app on the canonical sheet), design points flagged before any UI work. - Step 4c VALIDATED by user 2026-10-10 → tracking: head view check documented (spec §6), BLK-008 migration limit, BDR-037, DEPLOY.md `.env.example` note. Finished into develop. Next: Step 5 (app on the canonical sheet), design points flagged before any UI work.
- Step 5 preparation (2026-10-10): 4 analyzer agents (core/store, rendering, PDF, tests) + plan/spec reading → docs/development/STEP5_MIGRATION_ANALYSIS.md on chore/step-05-migration-analysis. Key facts: all 27 legacy data-anno-ids differ from canonical ids; 170/612 legacy finding paths moved/removed by curation → generated report-migration-map; markers never drawn by the app (in the SVG); PDF depends on markers only for the highlight; 66 tests import the registry. 8 decisions D1–D8 await the user. No implementation. - Step 5 preparation (2026-10-10): 4 analyzer agents (core/store, rendering, PDF, tests) + plan/spec reading → docs/development/STEP5_MIGRATION_ANALYSIS.md on chore/step-05-migration-analysis. Key facts: all 27 legacy data-anno-ids differ from canonical ids; 170/612 legacy finding paths moved/removed by curation → generated report-migration-map; markers never drawn by the app (in the SVG); PDF depends on markers only for the highlight; 66 tests import the registry. 8 decisions D1–D8 await the user. No implementation.
- Step 5 implemented (2026-10-10, feature/step-05-app-on-canonical-sheet): domain report v3 + migration (80 tests), pipeline migration map/sheet-ref/app review drawings + layer renderer (110), app rewritten on the sheet (99 tests: service, store, provider, canvas, pickers, PDF v2/v3, route), legacy code removed, docs rewritten (ANNOTATION-RENDERING.md replaces the SVG convention). Root check green, docker build OK, real stack 267/267, default build carries no sheet. BDR-038, LRN-043. Gates next; awaiting user validation.
- Step 5 gates (2026-10-10): verifier 36→4→4 (real gaps closed by 2 executors + doc fixes; cap reached, last test lot unverified by a 4th pass), security PASS (2 LOW fixed: prototype keys, size caps). EVAL-011. Final check green. Awaiting user validation; no publication; default build carries no sheet.
- Step 5 addendum (2026-10-10, user testing manually): per-leaf migration tests (612 leaves, anatomy + app + PDF roundtrip), `pnpm report:compare` archive check tool (privacy default, escaping), stale `scaffold:species` script removed, attachment read/parse split. Gates: verifier 2→1→CONFORME, security PASS ×2 (2 MEDIUM + 4 LOW fixed by executors). EVAL-012, LRN-044. Branch 14 commits ahead, not merged; awaiting user validation; no Step 6.
- Step 5 user validation (2026-10-10): all paths OK. One defect: findings picker text blurry on screen. Root cause (headless Chromium measure): permanent `will-change: transform, opacity` on the picker list + fractional offset inside height-animated card → composited text resampled; PDF unaffected. Hotfix 1f0b710: prop dropped, regression test (app 182). Security PASS, docs NONE. Full check green. User signal → finish Step 5; carpus + moved points noted, 28 annotations NOT a final catalog (enrichment with the osteopath + future editor later). Step 6 to present, not started.
+14
View File
@@ -323,3 +323,17 @@ Apply: every pgTAP touching storage.*; every workspace CLI.
Authoring 44 changes / 679 ops by hand is error-prone → scratch python modules (one per research theme, shared helpers `set_op/cite_op/add_change`, auto-numbered ids, targets derived from the baseline by walking it) built into changes.json; the pipeline's Zod + integrity rules catch any bad target at once. Order of modules = order of ops: a later module must address ids renamed by an earlier one (consultation-reason category ids). Stylised drawing: render with `magick` + 50-unit grid crops; sample first non-white row per column to prove "point floats above the silhouette" (t18-l1, l6-s1 were 30-70 units above the back). ImageMagick's internal SVG renderer drops shapes with `fill="none"` and shapes containing a `<title>` child → overlay uses fill-opacity and puts `<title>` on the `<g>`. Research agents: one theme each, every citation tagged VERIFIED-fetched/snippet/UNVERIFIED; only fetched or bibliographically confirmed entries enter the registry, unread books say "non consulté" in the citation. Authoring 44 changes / 679 ops by hand is error-prone → scratch python modules (one per research theme, shared helpers `set_op/cite_op/add_change`, auto-numbered ids, targets derived from the baseline by walking it) built into changes.json; the pipeline's Zod + integrity rules catch any bad target at once. Order of modules = order of ops: a later module must address ids renamed by an earlier one (consultation-reason category ids). Stylised drawing: render with `magick` + 50-unit grid crops; sample first non-white row per column to prove "point floats above the silhouette" (t18-l1, l6-s1 were 30-70 units above the back). ImageMagick's internal SVG renderer drops shapes with `fill="none"` and shapes containing a `<title>` child → overlay uses fill-opacity and puts `<title>` on the `<g>`. Research agents: one theme each, every citation tagged VERIFIED-fetched/snippet/UNVERIFIED; only fetched or bibliographically confirmed entries enter the registry, unread books say "non consulté" in the citation.
Apply: next species/sheet curation; any overlay/diagnostic SVG rasterised with ImageMagick. Apply: next species/sheet curation; any overlay/diagnostic SVG rasterised with ImageMagick.
---
## LRN-043 | 2026-10-10 | Migrating an app onto a new data model: freeze goldens first, make ids + maps data, read fresh state in DOM handlers
Freeze golden artifacts with the OLD code before touching it (v2 PDFs via a one-shot vitest, MAKE_GOLDEN=1, deleted after): the new importer is then tested against real archive-like bytes. Generate id/path maps from the pipeline's own records (renames/removals), never hand-written, and commit them as golden-tested data. In React routes, click handlers bound through `useEffect` capture stale closures when two DOM clicks land before a re-render (tests dispatch synchronously): read `store.getState()` inside the handler. A sheet needed to restore a draft but only known from the draft → load the default species' sheet when no report is open. Vitest has its own config: a Vite plugin providing a virtual module must be registered there too. ImageMagick cannot verify marker look with `<title>` children or `fill="none"`: strip titles for the raster only.
Apply: Step 6 (PDF v3 snapshot), Step 13 (Supabase SheetProvider), any future schema bump.
## LRN-044 | 2026-10-10 | CLI over untrusted documents: escape before print, privacy default, generic parse errors
Context: `report:compare` prints content of archive PDFs (attachment JSON). Security audit: raw interpolation lets a crafted attachment carry ESC/CR sequences that erase or forge lines, including a `!! UNRESOLVED` marker in an integrity tool; free text leaks names when stdout lands in CI logs; V8 `JSON.parse` message echoes ~15 chars of the input.
Pattern: one `esc()` helper (`/[\p{Cc}\p{Cf}\u2028\u2029]/gu` → `\uXXXX`) on every interpolated untrusted string incl. file names and error messages; default output = ids + catalog labels + counts + placeholders, `--full` opt-in for names and free text, same rule in every mode (`--diff` too); `SyntaxError` → generic reason; `statSync().isFile()` + size before `readFileSync`; INIT_CWD for paths under pnpm.
Apply: any future CLI/log over report content (Step 6 server import, worker). Test with `\u001b[2K`, `\n`, `\u009b`, `\u202e`, `__proto__` ids.
+15 -9
View File
@@ -86,15 +86,21 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [x] 4c.5 reports: REVIEW-REPORT.md for the osteopath (10 sections, questions ranked), CHANGELOG table, before/after review SVGs (draft/review/, PNG renders by operator), quantitative before/after. - [x] 4c.5 reports: REVIEW-REPORT.md for the osteopath (10 sections, questions ranked), CHANGELOG table, before/after review SVGs (draft/review/, PNG renders by operator), quantitative before/after.
- [ ] 4c follow-up (open, not blocking Step 5): 11 questions for the osteopath (draft/REVIEW-REPORT.md §10) → next changeset; legal scope text to re-read on consolidated Légifrance articles before publication; BLK-008 data migration v1→v2 before real data; user action `.env.example` COMPOSE_PROJECT_NAME=faunosteo (DEPLOY.md) - [ ] 4c follow-up (open, not blocking Step 5): 11 questions for the osteopath (draft/REVIEW-REPORT.md §10) → next changeset; legal scope text to re-read on consolidated Légifrance articles before publication; BLK-008 data migration v1→v2 before real data; user action `.env.example` COMPOSE_PROJECT_NAME=faunosteo (DEPLOY.md)
- [x] 4c.6 verify (root check 68+21+100+278, PGlite + real stack 267/267, types, docker build, Storage e2e; verifier ×3 → fixes, security PASS; EVAL-010): pnpm check, PGlite + real stack pgTAP, types, docker build, golden tests; gates verifier + security; docs (spec §6/§7, SUPABASE.md, CLAUDE.md, plan Step 4c, CHANGELOG); memory (BDR/LRN/EVAL/journal). Stop for user validation. - [x] 4c.6 verify (root check 68+21+100+278, PGlite + real stack 267/267, types, docker build, Storage e2e; verifier ×3 → fixes, security PASS; EVAL-010): pnpm check, PGlite + real stack pgTAP, types, docker build, golden tests; gates verifier + security; docs (spec §6/§7, SUPABASE.md, CLAUDE.md, plan Step 4c, CHANGELOG); memory (BDR/LRN/EVAL/journal). Stop for user validation.
- [ ] Step 5 — application on the canonical sheet (analysis 2026-10-10, branch chore/step-05-migration-analysis, AWAITING user validation of docs/development/STEP5_MIGRATION_ANALYSIS.md and decisions D1–D8; no implementation before) - [x] Step 5 — application on the canonical sheet (analysis validated 2026-10-10; implemented on feature/step-05-app-on-canonical-sheet; USER VALIDATED 2026-10-10, all paths OK; finished into develop 2026-10-10; D5 orphan findings documented as UX follow-up)
- [ ] 5.0 freeze: golden v2 PDFs + expected v3 docs; CHARACTERIZATION_REPORT refreshed - [x] 5.0 freeze: golden v2 PDFs + expected v3 docs; CHARACTERIZATION_REPORT refreshed
- [ ] 5.1 pipeline: report-migration-map.json (annotations, views, findingPaths 442/136/≤34), app-main.svg + app-head.svg review renders, category colours changeset (D1) - [x] 5.1 pipeline: report-migration-map.json (annotations, views, findingPaths 442/136/≤34), app-main.svg + app-head.svg review renders, category colours changeset (D1)
- [ ] 5.2 packages/domain: Report v3 (annotationId+viewId, free region codes, severity codes D8, sheet ref, unresolved findings, localAnnotations []), migrateReportV2ToV3, tests on fixtures + 612 leaves - [x] 5.2 packages/domain: Report v3 (annotationId+viewId, free region codes, severity codes D8, sheet ref, unresolved findings, localAnnotations []), migrateReportV2ToV3, tests on fixtures + 612 leaves
- [ ] 5.3 app foundation: bundledSheetProvider (Vite alias @sheets), sheetIndex, sanitiser, renderAnnotationLayer (legacy look), AnatomyCanvas/DetailModal on views (head = crop) - [x] 5.3 app foundation: bundledSheetProvider (Vite alias @sheets), sheetIndex, sanitiser, renderAnnotationLayer (legacy look), AnatomyCanvas/DetailModal on views (head = crop)
- [ ] 5.4 zoneInteraction service + reducers, store split + sessionStoragePersistence (v2 migration on load), pickers/cards on sheetIndex (D6 ranges, D7 title), EditorRoute < 300 lines - [x] 5.4 zoneInteraction service + reducers, store split + sessionStoragePersistence (v2 migration on load), pickers/cards on sheetIndex (D6 ranges, D7 title), EditorRoute < 300 lines
- [ ] 5.5 PDF shim + attachment v3 + v2 import (gate D3) - [x] 5.5 PDF shim + attachment v3 + v2 import (gate D3)
- [ ] 5.6 delete legacy (registry, species/*, zoneMatch, spineZones, svgConvention, D4 tools), SVG convention doc replaced, CLAUDE.md map, CHANGELOG, plan note, memory - [x] 5.6 delete legacy (registry, species/*, zoneMatch, spineZones, svgConvention, D4 tools), SVG convention doc replaced, CLAUDE.md map, CHANGELOG, plan note, memory
- [ ] 5.7 manual FR/EN flow, visual before/after, gates verifier + security - [x] 5.7 visual before/after (cmp renders), root check + docker + real stack green; verifier ×3 (gaps closed), security PASS (LOW fixed); EVAL-011. Manual FR/EN flow = user validation
- [x] 5.8 per-leaf migration (user ask 2026-10-10, during manual validation): every legacy leaf (612 = 442 identical, 141 moved, 29 removed) as a v2 finding → migrated → resolved to a draft leaf (anatomy, map file) and through sheetIndex.nodeAt + PDF roundtrip (app); the 27 legacy annotations as zones on their views
- [x] 5.9 archive check tool `pnpm report:compare <pdf|dir>...`: v2 attachment vs migrated v3 side by side, unresolved flagged (removed vs unknown), `--full` opt-in for names/free text, control chars escaped, --diff of two PDFs, --summary; attachment.ts split read/parse (additive, D3); docs PDF-FORMAT/CLAUDE/README
- [x] 5.10 final controls on the last lot: stale root script scaffold:species removed; verifier ×3 (2→1→CONFORME) + security ×2 PASS on criteria 16-18; EVAL-012
- [x] 5.11 user validation defect: findings picker text blurry on screen → permanent `will-change` on the list dropped (hotfix 1f0b710, regression test); PDF never affected
- [ ] 5.12 follow-up (not Step 5): equine sheet anatomical enrichment with the osteopath + future sheet editor (Step 17); the 28 draft annotations (carpus added, points moved) are NOT a final catalog
- [ ] 5 follow-up: allowlist SVG sanitiser before Storage-served assets (Step 13); orphan findings UX (D5) at the report UX step; report:compare residuals (ZodError reason genericised, v3 lines computed once, long template lines); 16 MiB attachment cap without direct test
--- ---
@@ -0,0 +1,27 @@
# CONTRACT — findings-picker-blur
- date: 2026-10-10 | flow: hotfix | branch: feature/step-05-app-on-canonical-sheet
- status: active
## REQUEST (verbatim — IMMUTABLE)
Un seul défaut visuel constaté : le texte des constats apparaît flou dans le sélecteur de constats. En revanche, il est net dans le PDF. Merci d'analyser la cause réelle (rendu CSS, transformations, mise à l'échelle, opacité, police, etc.) et de corriger ce problème sans modifier inutilement le design ou les interactions. Vérifie le résultat à l'écran, notamment sur desktop et mobile, et conserve les tests de non-régression.
## CLARIFICATIONS
none — request complete. Root cause located in the main loop (headless Chromium, Playwright): the `motion.ul` of `FindingsTreePicker` keeps a permanent inline `will-change: transform, opacity` after its 220 ms slide ends (computed transform `none`); the list sits at a fractional offset inside the height-animated card (left 561.1875 px desktop, top 735.765625 px mobile), so the composited text is resampled and blurs. The PDF never goes through that layer.
## ACCEPTANCE CRITERIA
1. The findings list carries no inline `will-change` (motion promotes the element itself during the slide).
CHECK: grep -n "willChange" apps/app/src/components/observation/FindingsTreePicker.tsx; echo "rc=$?"
EXPECT: rc=1
EVIDENCE: 2026-10-10 grep → no match, rc=1. MET.
2. A regression test asserts the rendered findings list has no inline will-change; every existing test kept.
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/components.FindingsTreePicker.test.tsx 2>&1 | tail -3
EXPECT: Tests .* passed
EVIDENCE: 2026-10-10 appended to the existing picker test file (path corrected here, [gated 2026-10-10] main loop) → Test Files 1 passed, Tests 6 passed. App suite 182 passed (executor smoke). MET.
3. Symptom gone on screen (desktop 1280×1, mobile 390×2): computed `willChange` of the list is `auto` and the edge-sharpness ratio rises versus the before capture (main loop measures with the Playwright script, no executor action).
EVIDENCE: 2026-10-10 headless Chromium 1243: willChange "transform, opacity" → "auto" on both profiles. Sharpness ratio mobile 0.640 → 0.774 (visibly crisper), desktop 0.594 → 0.583 (flat: headless renders text without LCD antialiasing, so the desktop difference is not observable there; the compositing mechanism is removed, the user confirms in a real browser). PARTIALLY MET (mechanism + mobile proven; desktop by user).
4. build/tests green: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run`.
EVIDENCE: typecheck + lint pass, app 182 tests pass (executor smoke); full workspace rerun before gitflow finish.
## FILE SCOPE
apps/app/src/components/observation/FindingsTreePicker.tsx (delete the `style={{ willChange: 'transform, opacity' }}` prop on `motion.ul`)
apps/app/tests/unit/FindingsTreePicker.test.tsx (new or existing picker test file: one regression test)
+1
View File
@@ -11,6 +11,7 @@ Versions follow [Semantic Versioning](https://semver.org/).
- **Supabase foundation** — local stack (`supabase/config.toml`), migrations (schemas `private` / `audit`, `profiles`, platform roles with audited RPCs), pgTAP suite run on PGlite (`pnpm test:run`) and on the real stack (`pnpm db:test`), `@faunosteo/supabase` typed client + generated types. No UI change. - **Supabase foundation** — local stack (`supabase/config.toml`), migrations (schemas `private` / `audit`, `profiles`, platform roles with audited RPCs), pgTAP suite run on PGlite (`pnpm test:run`) and on the real stack (`pnpm db:test`), `@faunosteo/supabase` typed client + generated types. No UI change.
- **Anatomical sheet model** — `@faunosteo/domain`: canonical sheet document (views tree, annotations with stable ids and explicit laterality, ordered vertebral regions, typed finding categories, explicit annotation → finding zone links, FR/EN labels) with integrity validation; tables `species`, `anatomical_sheets`, `anatomical_sheet_versions` (published rows immutable, one draft per sheet, deletion preconditions), `anatomical_sheet_assets`; lifecycle RPCs (create, draft, publish, deprecate, delete, fork with provenance, archive, assets) audited and under RLS. Spec: `docs/development/ANATOMICAL_SHEET_MODEL.md`. - **Anatomical sheet model** — `@faunosteo/domain`: canonical sheet document (views tree, annotations with stable ids and explicit laterality, ordered vertebral regions, typed finding categories, explicit annotation → finding zone links, FR/EN labels) with integrity validation; tables `species`, `anatomical_sheets`, `anatomical_sheet_versions` (published rows immutable, one draft per sheet, deletion preconditions), `anatomical_sheet_assets`; lifecycle RPCs (create, draft, publish, deprecate, delete, fork with provenance, archive, assets) audited and under RLS. Spec: `docs/development/ANATOMICAL_SHEET_MODEL.md`.
- **Application on the canonical sheet (Step 5)** — the editor renders the bundled reference sheet (curated equine draft, `SHEET_BUNDLE=draft`; a default build carries no sheet): markers drawn from the document with the legacy look (`@faunosteo/anatomy/render`), head view as a crop of the same drawing, zone interaction service, pickers on the sheet's regions (usual count, extension to the documented range) and finding zones. Report document **v3** (`packages/domain/report`): zones by annotation and view ids, findings by zone and path, severity codes, exact sheet reference; v2 PDFs and drafts migrate through the generated `report-migration-map.json`, unresolved items kept with their labels. Removed: species registry, label matchers, SVG convention parser, `/editors`, `/svg-editor`, `pathology-editor.html`, `scaffold:species`; the legacy sources now live under `supabase/seed/anatomical-sheets/equine/legacy-sources/`. Archive check tool `pnpm report:compare` (attachment vs its v3 reading, unresolved items flagged); the 612 legacy catalog leaves are tested through the migration in both packages.
- **Equine sheet curation (Step 4c)** — document schema v2 (references registry, `review_status` on findings and annotations, configurable vertebral `count_range`; migration `20261010100000`, pgTAP 008); `@faunosteo/anatomy` curation pipeline: authored changeset (`curation/changes.json`, levels A/B/C, before/after records) applied to the legacy baseline → working draft with `CHANGELOG.md`, `REVIEW-REPORT.md` (10 sections for the osteopath) and before/after review drawings; one cleaned SVG asset, head view as a crop. Content: research-backed audit of the horse sheet (44 changes, 48 verifiable references): sphenoid zone restructured, NAV terminology, FR/EN translations, vertebral ranges, ten SVG points relocated, carpus zone added, veterinary red flags, legal disclaimer anchored on R. 243-6 / R. 243-8, osteopathic-model status on unvalidated concepts, 11 questions for the professional. Still a private DRAFT, not published. Docker resources prefixed `faunosteo_` (Compose project and container). - **Equine sheet curation (Step 4c)** — document schema v2 (references registry, `review_status` on findings and annotations, configurable vertebral `count_range`; migration `20261010100000`, pgTAP 008); `@faunosteo/anatomy` curation pipeline: authored changeset (`curation/changes.json`, levels A/B/C, before/after records) applied to the legacy baseline → working draft with `CHANGELOG.md`, `REVIEW-REPORT.md` (10 sections for the osteopath) and before/after review drawings; one cleaned SVG asset, head view as a crop. Content: research-backed audit of the horse sheet (44 changes, 48 verifiable references): sphenoid zone restructured, NAV terminology, FR/EN translations, vertebral ranges, ten SVG points relocated, carpus zone added, veterinary red flags, legal disclaimer anchored on R. 243-6 / R. 243-8, osteopathic-model status on unvalidated concepts, 11 questions for the professional. Still a private DRAFT, not published. Docker resources prefixed `faunosteo_` (Compose project and container).
- **Equine import (Step 4b)** — `@faunosteo/anatomy` deterministic importer: `Horse.svg` + `Horse_head.svg` + `pathologies.json` → canonical document, legacy id map, French import report, idempotent seed creating the official sheet `faunosteo-cheval` as a private DRAFT (never published by code). Storage bucket `anatomical-sheet-assets` (content-addressed SVGs, read through the sheet, operator upload script). - **Equine import (Step 4b)** — `@faunosteo/anatomy` deterministic importer: `Horse.svg` + `Horse_head.svg` + `pathologies.json` → canonical document, legacy id map, French import report, idempotent seed creating the official sheet `faunosteo-cheval` as a private DRAFT (never published by code). Storage bucket `anatomical-sheet-assets` (content-addressed SVGs, read through the sheet, operator upload script).
+74 -64
View File
@@ -14,8 +14,10 @@ attachment so importing it restores the session for a follow-up.
SPA deployed via Docker + nginx on Scaleway VPS. Backend foundation on Supabase SPA deployed via Docker + nginx on Scaleway VPS. Backend foundation on Supabase
(PostgreSQL + Auth + RLS) since Step 3 of the SaaS plan: profiles, platform roles and (PostgreSQL + Auth + RLS) since Step 3 of the SaaS plan: profiles, platform roles and
audit log exist; Step 4 added the canonical anatomical sheet model (`packages/domain`, audit log exist; Step 4 added the canonical anatomical sheet model (`packages/domain`,
tables `species`, `anatomical_sheets` / `_versions` / `_assets`). The UI does not use tables `species`, `anatomical_sheets` / `_versions` / `_assets`). Step 5 moved the
the client yet (local-only flows unchanged). application onto that model: the editor renders the bundled reference sheet (the
curated equine DRAFT, `SHEET_BUNDLE=draft`), writes Report v3 and imports v2 PDFs
through a generated migration map. The Supabase client is still unused by the UI.
MVP species: equine only. Open-source MIT. MVP species: equine only. Open-source MIT.
--- ---
@@ -81,6 +83,12 @@ pnpm db:reset # replay from zero
pnpm db:test # pgTAP on the real stack pnpm db:test # pgTAP on the real stack
pnpm db:types # regenerate packages/supabase/src/database.types.ts pnpm db:types # regenerate packages/supabase/src/database.types.ts
pnpm db:types:check # CI diff pnpm db:types:check # CI diff
# Reference sheet in the app: the dev server bundles the curated draft; a build does not
pnpm build:preview # SHEET_BUNDLE=draft build (manual validation, preview deployments)
pnpm preview:draft # same, then serves it
pnpm import:equine # regenerate legacy-import/ and draft/ (document, migration map, review drawings)
pnpm report:compare <pdf|dir>... # archive check: attachment vs its v3 reading, unresolved items flagged (docs/PDF-FORMAT.md)
``` ```
## Docker commands ## Docker commands
@@ -89,6 +97,9 @@ pnpm db:types:check # CI diff
# Build image # Build image
docker build -t faunosteo . docker build -t faunosteo .
# Build an image that embeds the reference DRAFT sheet (preview only, never the default)
docker build --build-arg SHEET_BUNDLE=draft -t faunosteo .
# Run with compose (reads .env for APP_* vars) # Run with compose (reads .env for APP_* vars)
docker compose up --build docker compose up --build
@@ -115,8 +126,9 @@ pnpm test # vitest watch — dev loop
``` ```
Test files live in `apps/app/tests/unit/*.test.ts(x)`; golden fixtures in Test files live in `apps/app/tests/unit/*.test.ts(x)`; golden fixtures in
`apps/app/tests/fixtures/`. Setup: `apps/app/tests/setup.ts` imports `apps/app/tests/fixtures/`. The 612 legacy catalog leaves run through the v2 → v3 migration
@testing-library/jest-dom. Characterisation suite: files prefixed `char.`. in both `packages/anatomy` (against the draft document) and the app (sheet index + PDF roundtrip). Setup: `apps/app/tests/setup.ts` imports
@testing-library/jest-dom. Suites run on the bundled reference sheet (`tests/helpers/sheet.ts`); frozen v2 fixtures under `tests/fixtures/`.
SQL: `supabase/tests/*.sql` (pgTAP) run by `packages/supabase/tests/db/pgtap.test.ts` SQL: `supabase/tests/*.sql` (pgTAP) run by `packages/supabase/tests/db/pgtap.test.ts`
on PGlite (part of `pnpm test:run`) and by `pnpm db:test` on the real stack. on PGlite (part of `pnpm test:run`) and by `pnpm db:test` on the real stack.
@@ -136,54 +148,43 @@ pnpm format # Prettier write
``` ```
faunosteo/ faunosteo/
├─ apps/app/ ← @faunosteo/app (everything below until packages/) ├─ apps/app/ ← @faunosteo/app (everything below until packages/)
├─ public/ ├─ public/ ← logos only (no anatomy asset: the sheet is bundled)
│ ├─ species/equine/{Horse,Horse_head}.svg ← real anatomy SVGs ├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none)
│ └─ pathology-editor.html ← standalone JSON editor (served as static file) ├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts)
├─ src/ ├─ src/
│ ├─ app/ │ ├─ app/
│ │ ├─ App.tsx ← root router │ │ ├─ App.tsx ← root router
│ │ ├─ routes/{Home,NewReport,Editor,Editors,SvgEditor,NotFound}Route.tsx │ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx
│ │ └─ providers/ConfigProvider.tsx ← AppConfig context │ │ └─ providers/ConfigProvider.tsx ← AppConfig context
│ ├─ config/env.ts ← runtime config resolution │ ├─ config/env.ts ← runtime config resolution
│ ├─ domain/ │ ├─ sheets/{provider,useSheet}.ts ← SheetProvider interface, bundled implementation, per-species hook
│ │ ├─ schema/ ← Zod schemas (source of truth) │ ├─ services/
│ │ │ ├─ report.ts │ │ ├─ sheetIndex.ts ← read-only lookups over the loaded sheet (ids, never labels)
│ │ │ ├─ observation.ts │ │ └─ zoneInteraction.ts ← pure click decision + observation reducers (zones, sides, vertebrae)
│ │ │ ├─ practitioner.ts
│ │ │ ├─ animal.ts
│ │ │ └─ findings.ts
│ │ └─ species/
│ │ ├─ types.ts ← SpeciesManifest interface
│ │ ├─ registry.ts ← getSpecies(), getAllSpecies()
│ │ └─ equine/{index,vertebrae,pathologies}.{ts,json}
│ ├─ i18n/ │ ├─ i18n/
│ │ ├─ types.ts ← Locale type + Dict type │ │ ├─ types.ts ← Locale type + Dict type
│ │ ├─ fr.ts + en.ts ← translation dicts (flat key → string) │ │ ├─ fr.ts + en.ts ← translation dicts (flat key → string)
│ │ ├─ index.ts ← getDict(locale) │ │ ├─ index.ts ← getDict(locale)
│ │ └─ useT.ts ← useT() hook (reads localeStore) │ │ └─ useT.ts ← useT() hook (reads localeStore)
│ ├─ state/ │ ├─ state/
│ │ ├─ reportStore.ts ← Zustand store │ │ ├─ reportStore.ts ← Zustand store (Report v3) + persistence.ts (sessionStorage adapter, v2 draft migration)
│ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage) │ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage)
│ │ └─ practitionerCache.ts ← localStorage prefill │ │ └─ practitionerCache.ts ← localStorage prefill
│ ├─ anatomy/ │ ├─ anatomy/drawing.ts ← sanitised asset + generated annotation layer → inline <svg> per view
│ │ ├─ types.ts ← Bone, BoneCategory, BoneState
│ │ ├─ svgConvention.ts ← parseSvgBones()
│ │ ├─ svgLoader.ts ← loadSvg()
│ │ └─ labels.ts ← boneLabel(bone, locale, fallback)
│ ├─ components/ │ ├─ components/
│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip}.tsx │ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx │ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,FindingsTreePicker, │ │ ├─ observation/{ObservationList,ObservationCard,ObservationPickers,FindingsTreePicker,
│ │ │ VertebraPicker,SeveritySelector,LateralityPicker, │ │ │ VertebraPicker,SeveritySelector,LateralityPicker,
│ │ │ FreeTextFindingInput}.tsx │ │ │ FreeTextFindingInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm, │ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog,
│ │ │ ConclusionPanel,NextAppointmentPicker}.tsx │ │ │ ConclusionPanel,NextAppointmentPicker}.tsx
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx │ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
│ ├─ pdf/ │ ├─ pdf/
│ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts │ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts
│ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng,text,logo,linkAnnotation}.ts │ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng,text,logo,linkAnnotation}.ts
│ ├─ lib/{dates,id,assert,zoneMatch,spineZones,supabase}.ts ← supabase.ts: getSupabaseClient() | null │ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null
│ ├─ styles/{index,tokens,svg-editor}.css ← Tailwind v4 CSS-first + SVG editor styles │ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first
│ └─ main.tsx │ └─ main.tsx
├─ tests/ ├─ tests/
│ ├─ setup.ts │ ├─ setup.ts
@@ -192,8 +193,7 @@ faunosteo/
│ ├─ entrypoint.sh ← injects env.js at container start │ ├─ entrypoint.sh ← injects env.js at container start
│ └─ nginx.conf ← SPA fallback + PORT envsubst │ └─ nginx.conf ← SPA fallback + PORT envsubst
├─ docs/ ├─ docs/
│ ├─ ANATOMY-SVG-CONVENTION.md ← SVG data-* contract │ ├─ ANNOTATION-RENDERING.md ← annotation layer contract (attributes, styles, colours)
│ ├─ ADDING-A-SPECIES.md
│ ├─ PDF-FORMAT.md │ ├─ PDF-FORMAT.md
│ ├─ faunosteo-audit/ ← audit of the current system (frozen at 83e40af) │ ├─ faunosteo-audit/ ← audit of the current system (frozen at 83e40af)
│ ├─ development/ ← SaaS implementation plan, WORKSPACE.md │ ├─ development/ ← SaaS implementation plan, WORKSPACE.md
@@ -204,7 +204,7 @@ faunosteo/
├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only) ├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only)
│ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules │ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules
│ └─ tests/{fixtures/horse-slice.ts,*.test.ts} │ └─ tests/{fixtures/horse-slice.ts,*.test.ts}
├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer (SVG + catalog → canonical document) + curation ├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer, curation pipeline, pure annotation-layer renderer (`./render`)
│ ├─ src/legacy/{svg,catalog,regions,ids,report,importer}.ts, src/cli/import-equine.ts │ ├─ src/legacy/{svg,catalog,regions,ids,report,importer}.ts, src/cli/import-equine.ts
│ ├─ src/curation/{schema,targets,fields,ops,rename,apply,types,assets,labels,stats,changelog,review-report,overlay,seed,sources,pipeline}.ts ← changeset → draft │ ├─ src/curation/{schema,targets,fields,ops,rename,apply,types,assets,labels,stats,changelog,review-report,overlay,seed,sources,pipeline}.ts ← changeset → draft
│ └─ tests/ ← counts preserved, special cases, determinism, curation ops, golden artifacts │ └─ tests/ ← counts preserved, special cases, determinism, curation ops, golden artifacts
@@ -215,9 +215,10 @@ faunosteo/
│ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts │ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2 │ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2
│ ├─ seed/anatomical-sheets/equine/ │ ├─ seed/anatomical-sheets/equine/
│ │ ├─ legacy-sources/ ← the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input, never edited)
│ │ ├─ legacy-import/ ← GENERATED baseline: document, id map, IMPORT-REPORT, SVG copies (no SQL) │ │ ├─ legacy-import/ ← GENERATED baseline: document, id map, IMPORT-REPORT, SVG copies (no SQL)
│ │ ├─ curation/{changes,references}.json ← AUTHORED changeset + references registry (never generated) │ │ ├─ curation/{changes,references}.json ← AUTHORED changeset + references registry (never generated)
│ │ └─ draft/ ← GENERATED working revision: document, cleaned horse.svg, CHANGELOG, REVIEW-REPORT, review/*.svg, equine_draft.sql │ │ └─ draft/ ← GENERATED working revision: document, cleaned horse.svg, sheet-ref, report-migration-map, CHANGELOG, REVIEW-REPORT, review/*.svg, equine_draft.sql
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy │ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
├─ packages/README.md ← shared packages index ├─ packages/README.md ← shared packages index
├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker ├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker
@@ -238,16 +239,19 @@ User interaction
→ Zustand store (reportStore) → Zustand store (reportStore)
→ Components read store via selectors (no prop drilling) → Components read store via selectors (no prop drilling)
Sheet loading
→ useSheet(speciesId) → SheetProvider (bundled: virtual:faunosteo-sheet, SHEET_BUNDLE=draft)
→ Zod-validated document + assets + migration map → buildSheetIndex()
SVG interaction SVG interaction
→ AnatomyCanvas fetches SVG text via loadSvg() → AnatomyCanvas builds the view: sanitised asset + renderAnnotationLayer() (markers from the document)
→ parseSvgBones() walks DOM → Bone map → delegated click on [data-anno-id] → decideZoneClick() (services/zoneInteraction, pure)
→ delegated click listener → getBoneIdFromEvent() → open_view → DetailModal (same drawing, view_box crop, or the view's own asset)
→ if spine-zone → VertebraPicker modal → open_vertebra_picker / open_laterality_picker → pickers → reducers (ensureZone, addSides, syncVertebrae)
→ if data-anno-opens-detail → DetailModal (loads detail SVG) → toggle / remove_both_sides → updateObservation() in store
→ else → updateObservation() in store
PDF export PDF export
→ exportReportToPdf(report, { locale }) → exportReportToPdf(report, sheet, { locale })
→ pdf-lib PDFDocument → pdf-lib PDFDocument
→ embedFonts (Helvetica body + TimesRoman heading — WinAnsi StandardFonts; TTF Inter/Fraunces planned) → embedFonts (Helvetica body + TimesRoman heading — WinAnsi StandardFonts; TTF Inter/Fraunces planned)
→ for each observation: addObservationPage (rasterize SVG → PNG) → for each observation: addObservationPage (rasterize SVG → PNG)
@@ -256,9 +260,9 @@ PDF export
→ Uint8Array → browser download → Uint8Array → browser download
PDF import PDF import
→ importReportFromPdf(bytes) → importReportFromPdf(bytes, migrationMap)
→ extractReportJson → Zod validate → extractReportJson → readReportDocument (v3 as is, v2 migrated, else incompatible_version)
→ hydrateReport() → navigate /editor → hydrateReport() → navigate /editor (unresolved zones/findings kept and flagged)
Runtime config Runtime config
→ Docker entrypoint writes env.js (window.__APP_CONFIG__) → Docker entrypoint writes env.js (window.__APP_CONFIG__)
@@ -290,7 +294,7 @@ Database (Supabase)
- Both dicts must share the exact same key set; a key missing in one dict logs a warning in DEV - Both dicts must share the exact same key set; a key missing in one dict logs a warning in DEV
- Get the translate function in any component: `const t = useT()` then `t('common.cancel')` - Get the translate function in any component: `const t = useT()` then `t('common.cancel')`
- `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match - `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match
- Finding leaf labels (zone names shown in PDF) are resolved at export time via SVG `data-anno-name-fr` / `data-anno-name-en` attributes — not from the dict - Zone and finding names shown in the editor and the PDF come from the sheet document (`{ fr, en }` labels) and from the report's snapshots, not from the dict
- PDF static labels (section headings, metadata) come from the dict via `getDict(locale)` in `exportReportToPdf` - PDF static labels (section headings, metadata) come from the dict via `getDict(locale)` in `exportReportToPdf`
### Identity strings ### Identity strings
@@ -298,34 +302,40 @@ Database (Supabase)
- Always read from ConfigProvider via useConfig() - Always read from ConfigProvider via useConfig()
- src/config/env.ts is the only place with defaults - src/config/env.ts is the only place with defaults
### SVG convention ### Annotation rendering
- docs/ANATOMY-SVG-CONVENTION.md is the source of truth - docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the app draws
- Every clickable element must have: data-anno-id, data-anno-name-fr, data-anno-name-en, data-anno-category the markers from the document (`@faunosteo/anatomy/render`), with the attributes listed there
- SvgConventionError thrown on any missing required attribute - Never rely on element id, className or a label for click targeting or behaviour — always `data-anno-id`
- Never rely on element id or className for click targeting — always data-anno-id and the annotation's fields (`laterality`, `vertebral_region_code`, `opens_view_id`)
- Marker look (radii, opacities, strokes) is renderer style; colours are document data (`color` on categories
and annotations); no graphic redesign without prior validation
### Schemas ### Schemas
- domain/schema/*.ts are the data contracts — never change without bumping version - `packages/domain/src/report/*.ts` are the report data contracts (v3 current, v2 input only); never change
without bumping the version on a breaking change (additive optional fields keep it)
- All user-provided data goes through Zod parse before hitting the store - All user-provided data goes through Zod parse before hitting the store
- ReportSchema.version = 2 (v1 attachments rejected at import with a typed error); future breaking changes → version 3 - Report version 3: zones by `(annotationId, viewId)`, findings by `(findingZoneId, path)`, severities
`mild|moderate|severe`, `sheet` reference; v2 is migrated through `report-migration-map.json`
(`migrateReportV2ToV3`, never throws on content, `unresolved: true` marks what the sheet no longer holds);
v1 and unknown versions are refused with a typed error
### Stores ### Stores
- No direct store mutation outside Zustand actions - No direct store mutation outside Zustand actions
- No business logic in components — delegate to store actions - No business logic in components — delegate to store actions
- sessionStorage key: osteo:draft (auto-saved on every observation change) - sessionStorage key: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated on restore once the sheet is loaded)
- localStorage key: osteo:lastPractitioner (practitioner prefill cache) - localStorage key: osteo:lastPractitioner (practitioner prefill cache)
### PDF ### PDF
- A4 portrait: 595.28 × 841.89 pt - A4 portrait: 595.28 × 841.89 pt
- No raw URLs in PDF output — abbreviated citations only - No raw URLs in PDF output — abbreviated citations only
- JSON attachment filename must start with osteo-report - JSON attachment filename must start with osteo-report; content = Report v3; import accepts v2 (migrated) and v3
- Fonts are StandardFonts (Helvetica/TimesRoman, WinAnsi encoding) — TTF Inter/Fraunces planned but not yet embedded. Any non-Latin-1 glyph in PDF text must use an ASCII surrogate until the TTF migration lands (e.g. `(!)` instead of `⚠`). - Fonts are StandardFonts (Helvetica/TimesRoman, WinAnsi encoding) — TTF Inter/Fraunces planned but not yet embedded. Any non-Latin-1 glyph in PDF text must use an ASCII surrogate until the TTF migration lands (e.g. `(!)` instead of `⚠`).
### Pathology DB ### Anatomical sheet content
- All entries must pass PathologySchema.parse() - The findings catalog, the vertebral regions and the markers are the canonical sheet document; every content
- Each entry needs ≥1 source with citation change goes through `supabase/seed/anatomical-sheets/equine/curation/changes.json` (see the sheet model section)
- boneIds: [] = all zones; speciesIds: [] = all species - The curated draft is the reference content in development (`SHEET_BUNDLE=draft`); it is not medically
- Source types: manual | journal | database | web validated and a production build carries no sheet unless that flag is set on purpose
### Database (Supabase) ### Database (Supabase)
- Platform roles (`platform_role`: owner/admin/moderator/support) are NOT professional - Platform roles (`platform_role`: owner/admin/moderator/support) are NOT professional
@@ -403,12 +413,12 @@ Database (Supabase)
## Workflow expectations ## Workflow expectations
- Run `pnpm typecheck && pnpm test:run` before every commit. - Run `pnpm typecheck && pnpm test:run` before every commit.
- Domain schema changes (domain/schema/*.ts) require updating all callers + bumping version if breaking. - Domain schema changes (`packages/domain/src/report/*.ts`) require updating all callers + bumping version if breaking.
- SVG convention changes require updating docs/ANATOMY-SVG-CONVENTION.md first. - Annotation rendering changes require updating docs/ANNOTATION-RENDERING.md first.
- Never modify anatomy SVGs in public/species/ — they are source assets from the user. - Never modify the legacy sources under `supabase/seed/anatomical-sheets/equine/legacy-sources/` — they are the
- Pathology DB entries must be source-cited before commit; client review required for MVP batch. importer's input (the user's historical files).
- Ask before any change to importReportFromPdf or extractReportJson — these handle user data. - Ask before any change to importReportFromPdf, extractReportJson or readAttachedDocument — these handle user data.
- After PDF roundtrip tests fail: check attachment bytes, then Zod validation, then DecompressionStream inflation. - After PDF roundtrip tests fail: check attachment bytes, then Zod validation (v3, or v2 through the migration map), then DecompressionStream inflation.
- Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install. - Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install.
- SQL change: `pnpm --filter @faunosteo/supabase test:run` (PGlite) before commit; `pnpm db:reset && pnpm db:test` - SQL change: `pnpm --filter @faunosteo/supabase test:run` (PGlite) before commit; `pnpm db:reset && pnpm db:test`
on the real stack when Docker is available; regenerate types (`pnpm db:types`). on the real stack when Docker is available; regenerate types (`pnpm db:types`).
+13
View File
@@ -21,6 +21,19 @@ The host should publish only ports `22`, `80`, `443` to the internet. The
container port (`8080` by default) should stay loopback-only — the host container port (`8080` by default) should stay loopback-only — the host
reverse proxy reads from it on `127.0.0.1:8080`. reverse proxy reads from it on `127.0.0.1:8080`.
### Reference sheet in the image (SHEET_BUNDLE)
The application needs an anatomical sheet to work. Until sheets are served by
Supabase (plan Step 13) the only source is the sheet bundled at build time:
| Build | Sheet in the bundle |
|---|---|
| `docker build .` / `pnpm build` (default, CI) | none: the app shows "no anatomical sheet" and refuses to create or import a report |
| `docker build --build-arg SHEET_BUNDLE=draft .` / `pnpm build:preview` | the curated equine DRAFT, medically unvalidated |
Bundling the draft is a deliberate preview decision, never the default: the
draft content is readable by anyone who can load the application (BDR-037).
### Docker resource naming ### Docker resource naming
Expected change in `.env.example` (file not editable by the assistant): Expected change in `.env.example` (file not editable by the assistant):
+6 -1
View File
@@ -17,7 +17,12 @@ COPY packages/supabase/package.json packages/supabase/
RUN pnpm install --frozen-lockfile RUN pnpm install --frozen-lockfile
# Copy source and build the private app only # Copy source and build the private app only.
# SHEET_BUNDLE=draft embeds the reference equine DRAFT (medically unvalidated)
# into the bundle for a preview deployment; the default image carries no sheet
# (BDR-037, Step 5 D2): `docker build --build-arg SHEET_BUNDLE=draft .`
ARG SHEET_BUNDLE=none
ENV SHEET_BUNDLE=$SHEET_BUNDLE
COPY . . COPY . .
RUN pnpm --filter @faunosteo/app build RUN pnpm --filter @faunosteo/app build
+32 -32
View File
@@ -5,10 +5,11 @@ SVGs — click zones, build observations, export a self-contained PDF with the
full report JSON embedded as a native PDF attachment. Re-importing that PDF full report JSON embedded as a native PDF attachment. Re-importing that PDF
restores the state for a follow-up. restores the state for a follow-up.
Multi-species by design. MVP data set covers the **horse** (équin). Additional Multi-species by design. The MVP ships the **horse** sheet: a canonical anatomical
species — dog, cat, goat, cow, pig, rabbit, donkey, sheep — drop in by adding sheet document (drawing + annotations + findings catalog, `packages/domain`)
their SVG schematic + manifest + pathology file under `src/domain/species/`. generated and curated under `supabase/seed/anatomical-sheets/equine/`. Another
See [`docs/ADDING-A-SPECIES.md`](docs/ADDING-A-SPECIES.md) for the recipe. species is another sheet document, no code change.
See `docs/development/ANATOMICAL_SHEET_MODEL.md` §6 for how a sheet is produced.
Open to every praticien who wants to use it. No authentication, no backend, Open to every praticien who wants to use it. No authentication, no backend,
no central server in v1 — the PDF is the long-term record. Phase 2 will add no central server in v1 — the PDF is the long-term record. Phase 2 will add
@@ -19,20 +20,17 @@ contract.
## Features ## Features
- **Anatomy canvas** — inline SVG with clickable zones; hitbox+visible twin pattern; delegated click listener - **Anatomy canvas** — inline SVG drawing with markers rendered from the sheet document (hitbox + visible twin, delegated click listener)
- **Observation builder** — group zones into clinical observations with severity and free-text notes - **Observation builder** — group zones into clinical observations with severity and free-text notes
- **Hierarchical findings tree** — per-zone picker with breadcrumb drill-down through the expert-authored catalog (26 zones for the horse), vet-referral badges on sensitive leaves, scope-disclaimer modal once per session - **Hierarchical findings tree** — per-zone picker with breadcrumb drill-down through the expert-authored catalog (26 zones for the horse), vet-referral badges on sensitive leaves, scope-disclaimer modal once per session
- **Vertebra picker** — region tabs (C/T/L/S/Cd) with multi-select chip grid for precise vertebral notation - **Vertebra picker** — region tabs (C/T/L/S/Cd) with multi-select chip grid for precise vertebral notation
- **Detail popups** — click a zone (e.g. head) to open a secondary SVG with finer-grained zones - **Detail views** — click the head trigger to open the head view (a crop of the same drawing, or a view's own asset)
- **PDF export** — A4 portrait with rasterized anatomy SVGs (native browser `Image`/`canvas` pipeline), structured observations, and the full report JSON as a native PDF attachment - **PDF export** — A4 portrait with rasterized views, structured observations, and the full Report v3 JSON as a native PDF attachment; older v2 PDFs import through a generated migration map
- **PDF re-import** — open a previously exported PDF to restore the session for a follow-up - **PDF re-import** — open a previously exported PDF to restore the session for a follow-up
- **Bilingual UI** — full FR/EN interface with a one-click language switcher; default locale auto-detected from the browser, then persisted - **Bilingual UI** — full FR/EN interface with a one-click language switcher; default locale auto-detected from the browser, then persisted
- **Configurable identity** — site name, brand, footer, tagline all come from env vars; nothing hardcoded - **Configurable identity** — site name, brand, footer, tagline all come from env vars; nothing hardcoded
- **Practitioner cache** — last-used practitioner block prefilled via localStorage - **Practitioner cache** — last-used practitioner block prefilled via localStorage
- **Pathology editor** — standalone `pathology-editor.html` tool (no build step) for visually editing the species findings JSON via SVG zone selection; exports a downloadable JSON file
- **Laterality** — left/right side selection on bilateral zones, reflected in badges and the PDF - **Laterality** — left/right side selection on bilateral zones, reflected in badges and the PDF
- **SVG anatomy editor** — in-app `/svg-editor` tool to annotate anatomy SVGs
- **Welcome screen + editors page** — tabbed entry with a project SVG picker and an `/editors` listing
- **Footer branding** — global footer (copyright, "Powered by ZenQuality", partner logo), on site + PDF - **Footer branding** — global footer (copyright, "Powered by ZenQuality", partner logo), on site + PDF
--- ---
@@ -80,8 +78,9 @@ docker compose up --build
```bash ```bash
pnpm typecheck # TypeScript strict, no emit pnpm typecheck # TypeScript strict, no emit
pnpm lint # ESLint 9 flat config, 0 warnings pnpm lint # ESLint 9 flat config, 0 warnings
pnpm test:run # vitest run (app 278 + supabase 13, incl. 79 pgTAP checks on PGlite) pnpm test:run # vitest run (domain, anatomy, supabase/PGlite, app)
pnpm build # tsc + vite build → apps/app/dist/ pnpm build # tsc + vite build → apps/app/dist/
pnpm report:compare <pdf|dir>... # archive PDF vs its v3 reading, unresolved items flagged
``` ```
--- ---
@@ -101,9 +100,9 @@ For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy,
## Documentation ## Documentation
- [CLAUDE.md](CLAUDE.md) — project conventions, stack reference, architecture overview - [CLAUDE.md](CLAUDE.md) — project conventions, stack reference, architecture overview
- [docs/ANATOMY-SVG-CONVENTION.md](docs/ANATOMY-SVG-CONVENTION.md) — SVG data-* contract (source of truth) - [docs/ANNOTATION-RENDERING.md](docs/ANNOTATION-RENDERING.md) — annotation layer contract (markers drawn from the sheet document)
- [docs/ADDING-A-SPECIES.md](docs/ADDING-A-SPECIES.md) — guide for adding a second species post-MVP - [docs/development/ANATOMICAL_SHEET_MODEL.md](docs/development/ANATOMICAL_SHEET_MODEL.md) — canonical anatomical sheet document, curation pipeline, report migration map
- [docs/PATHOLOGIES-FORMAT.md](docs/PATHOLOGIES-FORMAT.md) — findings catalog format + authoring guide - [docs/development/STEP5_MIGRATION_ANALYSIS.md](docs/development/STEP5_MIGRATION_ANALYSIS.md) — how the application moved onto the canonical sheet (Report v3)
- [docs/PDF-FORMAT.md](docs/PDF-FORMAT.md) — PDF page layout and attachment contract - [docs/PDF-FORMAT.md](docs/PDF-FORMAT.md) — PDF page layout and attachment contract
- [docs/development/SUPABASE.md](docs/development/SUPABASE.md) — local Supabase stack, migrations, RLS tests, generated types - [docs/development/SUPABASE.md](docs/development/SUPABASE.md) — local Supabase stack, migrations, RLS tests, generated types
- [DEPLOY.md](DEPLOY.md) — production VPS deploy guide (Docker + nginx + TLS + hardening) - [DEPLOY.md](DEPLOY.md) — production VPS deploy guide (Docker + nginx + TLS + hardening)
@@ -117,25 +116,26 @@ For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy,
``` ```
faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md) faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md)
├─ apps/app/ the private application (@faunosteo/app): ├─ apps/app/ the private application (@faunosteo/app):
├─ public/species/equine/ anatomy SVGs (Horse.svg, Horse_head.svg) ├─ vite/sheet-bundle.ts Vite plugin bundling the reference sheet (SHEET_BUNDLE=draft|none)
├─ src/app/ routes + ConfigProvider ├─ src/app/ routes + ConfigProvider
├─ src/config/ runtime env config resolution ├─ src/config/ runtime env config resolution
├─ src/domain/ Zod schemas + species registry + equine data ├─ src/sheets/ SheetProvider (bundled implementation) + useSheet hook
├─ src/services/ sheet index (lookups by id) + zone interaction service (pure)
├─ src/i18n/ translation dicts (fr/en) + useT() hook ├─ src/i18n/ translation dicts (fr/en) + useT() hook
├─ src/state/ Zustand store + locale store + localStorage cache ├─ src/state/ Zustand store (Report v3) + persistence adapter + locale store
├─ src/anatomy/ SVG parser + loader ├─ src/anatomy/ drawing: sanitised asset + annotation layer → inline SVG per view
├─ src/components/ UI primitives, canvas, observation, report ├─ src/components/ UI primitives, canvas, observation, report
├─ src/pdf/ export/import/attachment/fonts + renderers ├─ src/pdf/ export/import/attachment/fonts + renderers
├─ src/lib/ id, dates, assert utilities ├─ src/lib/ id, dates, assert utilities
├─ src/styles/ Tailwind v4 CSS + design tokens ├─ src/styles/ Tailwind v4 CSS + design tokens
├─ tests/unit/ vitest tests (apps/app/tests, incl. characterisation suite) ├─ tests/unit/ vitest tests on the bundled sheet (+ frozen v2 fixtures)
├─ packages/domain/ @faunosteo/domain: canonical anatomical sheet document (Zod) + integrity rules ├─ packages/domain/ @faunosteo/domain: canonical sheet document + report document (v3, v2 migration)
├─ packages/anatomy/ @faunosteo/anatomy: legacy importer, curation pipeline, annotation-layer renderer
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness ├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness
├─ supabase/ CLI config, SQL migrations, local seed, pgTAP tests ├─ supabase/ CLI config, SQL migrations, local seed (incl. the equine sheet), pgTAP tests
├─ docker/ entrypoint.sh + nginx.conf ├─ docker/ entrypoint.sh + nginx.conf
├─ docs/ conventions + species guide + PDF spec ├─ docs/ conventions, sheet model, PDF spec, development plan
├─ index.html SPA entry point └─ index.html SPA entry point
└─ public/pathology-editor.html standalone pathology JSON editor (served as static file)
``` ```
--- ---
@@ -146,16 +146,16 @@ v0.1.0 MVP — implementation complete.
- `pnpm typecheck` ✅ - `pnpm typecheck` ✅
- `pnpm lint` ✅ - `pnpm lint` ✅
- `pnpm test:run` ✅ — 271 tests across 39 files - `pnpm test:run` ✅ — 367 tests across the workspace (domain, anatomy, supabase, app)
- `pnpm build` ✅ - `pnpm build` ✅
The first species data set ships with the real `Horse.svg` + `Horse_head.svg` The first species ships as the equine anatomical sheet: the historical
anatomy sources at `public/species/equine/` and a full v2.0 findings catalog `Horse.svg`, `Horse_head.svg` and findings catalog (26 zones, 792 nodes)
(26 zones, 792 nodes, 612 leaves, 41 vet-referral leaves) authored by the imported, then audited and curated (`supabase/seed/anatomical-sheets/equine/`,
domain expert. Adding **dog, cat, goat, cow, pig, rabbit, donkey, sheep** is 45 traced changes, 48 references). The application bundles that curated
the same procedure: convention-compliant SVG + manifest + findings JSON. See draft in development (`SHEET_BUNDLE=draft`); it is not medically validated and
[docs/ADDING-A-SPECIES.md](docs/ADDING-A-SPECIES.md) and a production build carries no sheet unless asked. Another species is another
[docs/PATHOLOGIES-FORMAT.md](docs/PATHOLOGIES-FORMAT.md). sheet document produced the same way.
Manual QA checklist: `.claude/audits/MVP-QA.md` — walk it through `pnpm dev` Manual QA checklist: `.claude/audits/MVP-QA.md` — walk it through `pnpm dev`
before delivery. before delivery.
+4 -1
View File
@@ -12,9 +12,11 @@
"test": "vitest", "test": "vitest",
"test:run": "vitest run", "test:run": "vitest run",
"lint": "eslint . --max-warnings 0", "lint": "eslint . --max-warnings 0",
"scaffold:species": "node scripts/scaffold-species.mjs" "report:compare": "tsx scripts/compare-reports.ts"
}, },
"dependencies": { "dependencies": {
"@faunosteo/anatomy": "workspace:*",
"@faunosteo/domain": "workspace:*",
"@faunosteo/supabase": "workspace:*", "@faunosteo/supabase": "workspace:*",
"motion": "^11.11.17", "motion": "^11.11.17",
"pdf-lib": "^1.17.1", "pdf-lib": "^1.17.1",
@@ -38,6 +40,7 @@
"eslint-plugin-react-hooks": "^5.1.0", "eslint-plugin-react-hooks": "^5.1.0",
"globals": "^15.14.0", "globals": "^15.14.0",
"happy-dom": "^20.10.6", "happy-dom": "^20.10.6",
"tsx": "^4.23.15",
"typescript": "^5.7.2", "typescript": "^5.7.2",
"typescript-eslint": "^8.19.0", "typescript-eslint": "^8.19.0",
"vite": "^7.3.6", "vite": "^7.3.6",
File diff suppressed because it is too large. Load diff
+152
View File
@@ -0,0 +1,152 @@
/**
* Archive check: reads the report attached to one or more Faunosteo PDFs and
* prints it next to its v3 reading on the bundled reference sheet.
*
* pnpm report:compare <file.pdf | folder>... [--summary] [--full]
* [--locale fr|en] [--diff a.pdf b.pdf]
*
* A v2 archive PDF is shown legacy id → canonical id, line by line; a v3 PDF
* is checked against the sheet. Items the sheet cannot place are marked
* `!! UNRESOLVED` with the reason. `--diff` compares the v3 content of two
* PDFs (an archive and its re-export after import, typically). By default
* only identifiers, catalog labels, counts and placeholders are printed and
* compared (a text shows as `conclusion (present)`); names and free texts,
* printed and compared, need `--full`.
* Untrusted strings are printed with control characters escaped. It writes
* no output file.
*/
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { basename, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PDFDocument } from 'pdf-lib'
import {
readReportDocument,
REPORT_VERSION,
UnsupportedReportVersionError,
} from '@faunosteo/domain'
import { readAttachedDocument } from '../src/pdf/attachment'
import { MAX_PDF_BYTES } from '../src/pdf/import'
import { parseBundledSheet } from '../src/sheets/provider'
import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex'
import {
compareReport,
diffLines,
esc,
parseArgs,
renderComparison,
renderSummary,
type CliArgs,
type Comparison,
} from './compare/report'
const SEED_DIR = resolve(
fileURLToPath(import.meta.url),
'../../../../supabase/seed/anatomical-sheets/equine/draft',
)
/** pnpm runs the script from apps/app; paths are typed from the caller's folder. */
const CWD = process.env.INIT_CWD ?? process.cwd()
function loadSheet(): SheetIndex {
const json = (name: string) =>
JSON.parse(readFileSync(join(SEED_DIR, name), 'utf8')) as never
// The comparison needs the document and the map, not the drawings.
return buildSheetIndex(
parseBundledSheet({
status: 'draft',
ref: json('sheet-ref.json'),
document: json('document.json'),
migrationMap: json('report-migration-map.json'),
assets: {},
}),
)
}
/** A folder stands for its PDFs; any other argument stays one entry. */
function expandArg(arg: string): string[] {
const path = resolve(CWD, arg)
try {
if (!statSync(path).isDirectory()) return [path]
} catch {
return [path] // reported as a failed entry by compareFile
}
return readdirSync(path)
.filter((f) => f.toLowerCase().endsWith('.pdf'))
.sort()
.map((f) => join(path, f))
}
async function compareFile(
path: string,
sheet: SheetIndex,
args: CliArgs,
): Promise<Comparison> {
const st = statSync(path)
if (!st.isFile()) throw new Error('not a regular file')
if (st.size > MAX_PDF_BYTES) throw new Error('file too large')
const bytes = new Uint8Array(readFileSync(path))
const pdf = await PDFDocument.load(bytes, { ignoreEncryption: true })
const raw = await readAttachedDocument(pdf)
const version = (raw as { version: number }).version
try {
const outcome = readReportDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, version !== REPORT_VERSION, sheet, args)
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new Error(`report version ${version} cannot be read`)
}
throw err
}
}
/** A missing or unreadable file is a failed entry, not a crash. */
function failureReason(err: unknown): string {
const code = (err as NodeJS.ErrnoException | undefined)?.code
if (code === 'ENOENT') return 'file not found'
if (code === 'EACCES') return 'file not readable'
// JSON.parse messages echo a fragment of the attachment.
if (err instanceof SyntaxError) return 'attachment is not valid JSON'
return err instanceof Error ? err.message : String(err)
}
async function main(argv: string[]): Promise<number> {
const args = parseArgs(argv)
const files = args.files.flatMap(expandArg)
if (files.length === 0 || (args.diff && files.length !== 2)) {
console.error(
'usage: pnpm report:compare <file.pdf | folder>... [--summary] [--full] [--locale fr|en] [--diff a.pdf b.pdf]',
)
return 1
}
const sheet = loadSheet()
const results: Comparison[] = []
let failures = 0
for (const file of files) {
const name = esc(basename(file))
try {
const c = await compareFile(file, sheet, args)
results.push(c)
if (!args.diff) {
const lines = args.summary
? [renderSummary(name, c)]
: [...renderComparison(name, c), '']
console.log(lines.join('\n'))
}
} catch (err) {
failures += 1
console.log(`!! ${name}: ${esc(failureReason(err))}`)
}
}
if (args.diff && results.length === 2) {
const diff = diffLines(results[0]!.normalized, results[1]!.normalized)
console.log(diff.length ? diff.join('\n') : 'identical v3 content')
}
return failures ? 2 : 0
}
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(err) => {
console.error(esc(err instanceof Error ? err.message : String(err)))
process.exit(1)
},
)
+364
View File
@@ -0,0 +1,364 @@
import {
ReportV2Schema,
findingPathKey,
type Finding,
type FindingV2,
type MigrationOutcome,
type ObservationZoneV2,
type Report,
type ReportZone,
} from '@faunosteo/domain'
import type { Locale } from '../../src/i18n/types'
import { pickLabel, type SheetIndex } from '../../src/services/sheetIndex'
/**
* Pure comparison of a report document found in a PDF with its v3 reading:
* a v2 archive is shown legacy id → canonical id line by line, a v3 report
* is checked against the bundled sheet. Every item the sheet cannot place is
* marked `!! UNRESOLVED` with the reason, nothing is summarised away.
*/
export const UNRESOLVED = '!! UNRESOLVED'
export interface CompareOptions {
locale: Locale
/** Print names and the real free texts (off by default: placeholders). */
full: boolean
}
export interface Comparison {
/** `v2` when the attachment was migrated, `v3` when read as is. */
source: 'v2' | 'v3'
header: string[]
observations: string[][]
footer: string[]
/** Lines in the v3 vocabulary only, for `--diff` between two PDFs. */
normalized: string[]
counts: Counts
}
export interface Counts {
observations: number
zones: number
unresolvedZones: number
findings: number
unresolvedFindings: number
}
/**
* Escapes Unicode control (C0, DEL, C1) and format characters (bidi
* overrides, zero-width) plus the line and paragraph separators as `\uXXXX`
* (newline and carriage return included): a PDF is untrusted, and a raw
* escape sequence printed to a terminal can rewrite the screen or fake a line.
*/
export function esc(text: string): string {
return text.replace(
/[\p{Cc}\p{Cf}\u2028\u2029]/gu,
(c) => `\\u${c.codePointAt(0)!.toString(16).padStart(4, '0')}`,
)
}
const q = (text: string) => `"${esc(text)}"`
function zoneRef(z: { annotationId: string; viewId: string; side?: string }) {
return esc(`${z.annotationId}@${z.viewId}${z.side ? ' ' + z.side : ''}`)
}
function findingRef(f: { findingZoneId: string; path: readonly string[] }) {
return esc(findingPathKey(f.findingZoneId, f.path))
}
function vertebraeOf(z: { vertebrae?: { region: string; index: number }[] }) {
return z.vertebrae?.length
? ` [${z.vertebrae.map((v) => esc(`${v.region}${v.index}`)).join(', ')}]`
: ''
}
/** Free-text lines: the texts with `full`, else only how many there are. */
function textLines(texts: readonly string[], full: boolean): string[] {
if (texts.length === 0) return []
if (!full) return [`text (${texts.length} entries)`]
return texts.map((t) => `text ${q(t)}`)
}
/** A single free-text field: its content with `full`, else a placeholder. */
function fieldLine(label: string, value: string | undefined, full: boolean) {
if (!value) return []
return [full ? `${label} ${q(value)}` : `${label} (present)`]
}
/** A v3 zone against the sheet: current label, or why it cannot be shown. */
function describeZone(
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const ref = `${zoneRef(z)}${vertebraeOf(z)}`
const anno = sheet.annotation(z.annotationId)
if (z.unresolved) {
return `${ref} ${q(z.labelFrSnapshot ?? '')} ${UNRESOLVED} legacy zone kept from the archive`
}
if (!anno || anno.view_id !== z.viewId) {
return `${ref} ${q(z.labelFrSnapshot ?? '')} !! not in the sheet (unflagged)`
}
return `${ref} ${q(pickLabel(sheet.name(anno), locale))}`
}
/** A v3 finding against the sheet: current label, or why it cannot be shown. */
function describeFinding(
f: Finding,
sheet: SheetIndex,
locale: Locale,
): string {
const snapshot = q(locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot)
const vet = f.requiresVetReferral ? ' (!)' : ''
const side = f.side ? ` ${esc(f.side)}` : ''
const ref = `${findingRef(f)}${side}${vet}`
if (f.unresolved) {
return `${ref} ${snapshot} ${UNRESOLVED} kept with its snapshot`
}
const node = sheet.nodeAt(f.findingZoneId, f.path)
if (!node) return `${ref} ${snapshot} !! not in the sheet (unflagged)`
if (node.children.length > 0) {
return `${ref} ${snapshot} !! points at a category, not a leaf`
}
return `${ref} ${q(pickLabel(node.name, locale))}`
}
/** Legacy zone → migrated zone. */
function describeZoneMigration(
legacy: ObservationZoneV2,
out: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const side = legacy.side ? ` ${legacy.side}` : ''
const detail = legacy.detailSourceId ? '@' + legacy.detailSourceId : ''
const from = `${esc(legacy.boneId + detail + side)}${vertebraeOf(legacy)}`
if (out.unresolved) {
return `${from} ${UNRESOLVED} unknown legacy id, kept as ${zoneRef(out)}`
}
const anno = sheet.annotation(out.annotationId)
const label = anno ? q(pickLabel(sheet.name(anno), locale)) : '!! missing'
return `${from} ${q(out.labelFrSnapshot ?? '')} → ${zoneRef(out)} ${label}`
}
/** Legacy finding → migrated finding, with the fate the map decided. */
function describeFindingMigration(
legacy: FindingV2,
out: Finding,
sheet: SheetIndex,
locale: Locale,
): string {
const map = sheet.sheet.migrationMap.finding_paths
const vet = legacy.requiresVetReferral ? ' (!)' : ''
const legacyKey = findingPathKey(legacy.zoneId, legacy.path)
const key = `${esc(legacyKey)}${vet}`
const snapshot = q(
locale === 'en' ? legacy.labelEnSnapshot : legacy.labelFrSnapshot,
)
if (out.unresolved) {
const why = Object.hasOwn(map, legacyKey)
? 'removed from the sheet, kept with its label'
: 'never in the legacy catalog, kept with its label'
return `${key} ${snapshot} ${UNRESOLVED} ${why}`
}
const node = sheet.nodeAt(out.findingZoneId, out.path)
const label = node ? q(pickLabel(node.name, locale)) : '!! missing'
const target = findingRef(out) === esc(legacyKey) ? 'same' : findingRef(out)
return `${key} ${snapshot} → ${target} ${label}`
}
function observationLines(
obs: Report['observations'][number],
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const lines = [
`[${esc(obs.id)}] severity ${esc(obs.severity ?? 'none')}`,
...obs.zones.map((z) => `zone ${describeZone(z, sheet, opts.locale)}`),
...obs.findings.map(
(f) => `finding ${describeFinding(f, sheet, opts.locale)}`,
),
...textLines(obs.freeTextFindings, opts.full),
...fieldLine('comment ', obs.comment, opts.full),
]
return lines
}
function migratedObservationLines(
raw: unknown,
report: Report,
sheet: SheetIndex,
opts: CompareOptions,
): string[][] {
const v2 = ReportV2Schema.parse(raw)
return v2.observations.map((legacy, i) => {
const out = report.observations[i]!
const severity = legacy.severity
? esc(`${legacy.severity} → ${out.severity}`)
: 'none'
const lines = [`[${esc(legacy.id)}] severity ${severity}`]
legacy.zones.forEach((z, j) => {
const line = describeZoneMigration(z, out.zones[j]!, sheet, opts.locale)
lines.push(`zone ${line}`)
})
legacy.findings.forEach((f, j) => {
const line = describeFindingMigration(
f,
out.findings[j]!,
sheet,
opts.locale,
)
lines.push(`finding ${line}`)
})
lines.push(...textLines(legacy.freeTextFindings, opts.full))
lines.push(...fieldLine('comment ', legacy.comment, opts.full))
return lines
})
}
function countsOf(report: Report): Counts {
const zones = report.observations.flatMap((o) => o.zones)
const findings = report.observations.flatMap((o) => o.findings)
return {
observations: report.observations.length,
zones: zones.length,
unresolvedZones: zones.filter((z) => z.unresolved).length,
findings: findings.length,
unresolvedFindings: findings.filter((f) => f.unresolved).length,
}
}
function headerLines(
source: 'v2' | 'v3',
report: Report,
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const ref = sheet.sheet.ref
const sameSheet =
report.sheet.sheetId === ref.sheetId &&
report.sheet.documentSha256 === ref.documentSha256
const sheetLine = sameSheet
? `sheet ${esc(ref.sheetId)} (${sheet.sheet.status}, matches the bundled sheet)`
: `sheet ${esc(report.sheet.sheetId)} !! written on another sheet document (sha ${esc(report.sheet.documentSha256.slice(0, 12))}…)`
const c = countsOf(report)
const lines = [
source === 'v2' ? 'v2 → v3 (migrated)' : 'v3 (read as is)',
sheetLine,
`id ${esc(report.id)} · date ${esc(report.date)} · ${c.observations} observations · ${c.zones} zones (${c.unresolvedZones} unresolved) · ${c.findings} findings (${c.unresolvedFindings} unresolved)`,
]
if (opts.full) {
lines.push(
`practitioner ${q(report.practitioner.name)} · animal ${q(report.animal.name)} · owner ${q(report.owner.name)}`,
)
}
return lines
}
function footerLines(report: Report, full: boolean): string[] {
const appointment = report.nextAppointment
return [
...fieldLine('conclusion', report.conclusion, full),
...fieldLine('recommendations', report.recommendations, full),
...(appointment
? [
full
? `next appointment ${esc(JSON.stringify(appointment))}`
: `next appointment (${appointment.kind})`,
]
: []),
]
}
/**
* `raw` is the attachment as found in the PDF, `outcome` its v3 reading
* (`readReportDocument`); `migrated` tells which vocabulary the lines use.
*/
export function compareReport(
raw: unknown,
outcome: MigrationOutcome,
migrated: boolean,
sheet: SheetIndex,
opts: CompareOptions,
): Comparison {
const { report } = outcome
const source = migrated ? 'v2' : 'v3'
const v3Lines = report.observations.map((o) =>
observationLines(o, sheet, opts),
)
// Same privacy default as the listing: texts are compared with `--full`.
const normalized = [
...report.observations.flatMap((o) => observationLines(o, sheet, opts)),
...footerLines(report, opts.full),
]
return {
source,
header: headerLines(source, report, sheet, opts),
observations: migrated
? migratedObservationLines(raw, report, sheet, opts)
: v3Lines,
footer: footerLines(report, opts.full),
normalized,
counts: countsOf(report),
}
}
export function renderComparison(name: string, c: Comparison): string[] {
return [
`== ${name}`,
...c.header.map((l) => ` ${l}`),
...c.observations.flatMap((lines) =>
lines.map((l, i) => (i === 0 ? ` ${l}` : ` ${l}`)),
),
...c.footer.map((l) => ` ${l}`),
]
}
export function renderSummary(name: string, c: Comparison): string {
const n = c.counts
return `${name} · ${c.source === 'v2' ? 'v2→v3' : 'v3'} · ${n.observations} obs · zones ${n.zones}/${n.unresolvedZones} unresolved · findings ${n.findings}/${n.unresolvedFindings} unresolved`
}
/** Lines of A absent from B and lines of B absent from A, in order. */
export function diffLines(a: string[], b: string[]): string[] {
const inB = new Set(b)
const inA = new Set(a)
return [
...a.filter((l) => !inB.has(l)).map((l) => `- ${l}`),
...b.filter((l) => !inA.has(l)).map((l) => `+ ${l}`),
]
}
export interface CliArgs extends CompareOptions {
files: string[]
summary: boolean
diff: boolean
}
export function parseArgs(argv: string[]): CliArgs {
const args: CliArgs = {
files: [],
locale: 'fr',
full: false,
summary: false,
diff: false,
}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]!
if (arg === '--full') args.full = true
else if (arg === '--summary') args.summary = true
else if (arg === '--diff') args.diff = true
else if (arg === '--locale') {
const value = argv[++i]
if (value !== 'fr' && value !== 'en') {
throw new Error('--locale takes fr or en')
}
args.locale = value
} else if (arg.startsWith('--'))
throw new Error(`unknown option ${esc(arg)}`)
else args.files.push(arg)
}
return args
}
-238
View File
@@ -1,238 +0,0 @@
#!/usr/bin/env node
/**
* Scaffolds a new species: prompts for the few required values then
* writes the boilerplate that the auto-discovery registry expects.
*
* Run via: pnpm scaffold:species
* or: node scripts/scaffold-species.mjs
*
* The script never touches existing files — it refuses to write if any
* of the targets already exist, so you can rerun it after fixing typos
* without losing work. SVG assets are NOT created; drop them in
* `public/species/<assetFolder>/` yourself after the script finishes.
*/
import { existsSync } from 'node:fs'
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import readline from 'node:readline/promises'
import { stdin as input, stdout as output } from 'node:process'
const HERE = dirname(fileURLToPath(import.meta.url))
const PROJECT_ROOT = resolve(HERE, '..')
const rl = readline.createInterface({ input, output })
async function ask(question, fallback) {
const suffix = fallback === undefined ? '' : ` [${fallback}]`
const raw = (await rl.question(`${question}${suffix}: `)).trim()
return raw || (fallback ?? '')
}
async function askRequired(question, validate) {
while (true) {
const v = (await rl.question(`${question}: `)).trim()
if (!v) {
console.log(' (required)')
continue
}
if (validate) {
const err = validate(v)
if (err) {
console.log(` ${err}`)
continue
}
}
return v
}
}
async function askPositiveInt(question, fallback) {
while (true) {
const v = await ask(question, String(fallback))
const n = Number(v)
if (Number.isInteger(n) && n > 0) return n
console.log(' enter a positive integer')
}
}
function isKebab(s) {
return /^[a-z][a-z0-9-]*$/.test(s)
}
function capitalize(s) {
return s.charAt(0).toUpperCase() + s.slice(1)
}
function indexTs({ id, labelFr, labelEn, mainSvgPath, details, formulaConstName }) {
const detailLines = details
.map((d) => ` ${d.key}: '${d.path}',`)
.join('\n')
return `import type { SpeciesManifest } from '@/domain/species/types'
import { ${formulaConstName} } from './vertebrae'
const ${id}: SpeciesManifest = {
id: '${id}',
labelFr: '${labelFr.replace(/'/g, "\\'")}',
labelEn: '${labelEn.replace(/'/g, "\\'")}',
mainSvg: '${mainSvgPath}',
details: {
${detailLines}
},
vertebralFormula: ${formulaConstName},
findings: () => import('./pathologies'),
}
// Default export is the convention picked up by the registry's
// import.meta.glob() auto-discovery.
export default ${id}
`
}
function vertebraeTs({ formulaConstName, labelFr, formula }) {
return `import type { VertebralFormula } from '@/domain/species/types'
/** Vertebral formula for ${labelFr}. Adjust to species-specific anatomy. */
export const ${formulaConstName}: VertebralFormula = {
C: ${formula.C},
T: ${formula.T},
L: ${formula.L},
S: ${formula.S},
Cd: ${formula.Cd},
}
`
}
function pathologiesTs() {
return `import {
SpeciesFindingsSchema,
type SpeciesFindings,
} from '@/domain/schema/findings'
import data from './pathologies.json'
const FINDINGS: SpeciesFindings = SpeciesFindingsSchema.parse(data)
export default FINDINGS
`
}
function pathologiesJsonTemplate({ id, labelFr, labelEn }) {
return JSON.stringify(
{
schema_version: '1.1',
scope_disclaimer:
"Les éléments listés correspondent au périmètre légal de l'ostéopathie animale : dysfonctions ostéopathiques palpées, observations cliniques et motifs de consultation. Aucun diagnostic médical n'est posé. Toute pathologie organique relève du vétérinaire.",
species: {
id,
name_fr: labelFr,
name_en: labelEn,
},
zones: {},
},
null,
2,
)
}
async function collectDetails() {
const details = []
console.log('\nDetail popup SVGs (optional — leave key blank to stop).')
console.log(' Each "key" must match a data-anno-opens-detail value on a hitbox in the main SVG.')
for (;;) {
const key = (await rl.question(' detail key (e.g. head, patte): ')).trim()
if (!key) return details
if (!isKebab(key)) {
console.log(' → key must be kebab-case (lowercase, hyphen-separated). Try again.')
continue
}
const path = await askRequired(
` detail SVG path for "${key}" (e.g. /species/canine/Dog_head.svg)`,
(v) => (v.startsWith('/species/') ? '' : ' path must start with /species/'),
)
details.push({ key, path })
}
}
async function main() {
console.log('\nZoosteo — new species scaffold')
console.log('-----------------------------------\n')
const id = await askRequired(
'species id (kebab-case, e.g. canine, feline, bovine)',
(v) => (isKebab(v) ? '' : 'must be kebab-case (lowercase letters / digits / hyphens; start with a letter)'),
)
const labelFr = await askRequired('display label (FR), e.g. "Chien"')
const labelEn = await ask('display label (EN), e.g. "Dog"', capitalize(id))
const assetFolder = await ask(
'public asset folder under /species/',
id,
)
const mainSvgFile = await askRequired(
`main SVG filename in /public/species/${assetFolder}/ (e.g. Dog.svg)`,
)
const mainSvgPath = `/species/${assetFolder}/${mainSvgFile}`
const details = await collectDetails()
console.log('\nVertebral formula (counts per region):')
const formula = {
C: await askPositiveInt(' cervical (C)', 7),
T: await askPositiveInt(' thoracic (T)', 13),
L: await askPositiveInt(' lumbar (L)', 6),
S: await askPositiveInt(' sacral (S)', 5),
Cd: await askPositiveInt(' caudal (Cd)', 18),
}
const formulaConstName = `${id.replace(/-/g, '_').toUpperCase()}_VERTEBRAL_FORMULA`
const speciesDir = resolve(PROJECT_ROOT, 'src/domain/species', id)
const targets = {
'index.ts': indexTs({ id, labelFr, labelEn, mainSvgPath, details, formulaConstName }),
'vertebrae.ts': vertebraeTs({ formulaConstName, labelFr, formula }),
'pathologies.ts': pathologiesTs(),
'pathologies.json': pathologiesJsonTemplate({ id, labelFr, labelEn }),
}
// Refuse to clobber.
for (const file of Object.keys(targets)) {
const p = resolve(speciesDir, file)
if (existsSync(p)) {
console.error(`\n✖ ${p} already exists. Aborting to protect existing work.`)
process.exit(1)
}
}
await mkdir(speciesDir, { recursive: true })
for (const [file, body] of Object.entries(targets)) {
await writeFile(resolve(speciesDir, file), body)
}
const publicDir = resolve(PROJECT_ROOT, 'public/species', assetFolder)
await mkdir(publicDir, { recursive: true })
console.log(`\n✓ Created src/domain/species/${id}/`)
for (const file of Object.keys(targets)) console.log(` - ${file}`)
console.log(`✓ Ensured public/species/${assetFolder}/ exists`)
console.log('\nNext steps:')
console.log(` 1. Drop your SVG assets into public/species/${assetFolder}/`)
console.log(` - main: ${mainSvgFile}`)
for (const d of details) {
const file = d.path.split('/').pop()
console.log(` - detail "${d.key}": ${file}`)
}
console.log(` 2. Author the findings tree in src/domain/species/${id}/pathologies.json`)
console.log(` (schema documented in src/domain/schema/findings.ts).`)
console.log(` 3. Adjust the vertebral counts in vertebrae.ts if needed.`)
console.log(` 4. Run: pnpm typecheck && pnpm test:run && pnpm dev`)
console.log(' The new species will appear automatically in the animal picker.\n')
}
main()
.catch((err) => {
console.error('Scaffold failed:', err)
process.exit(1)
})
.finally(() => {
rl.close()
})
+97
View File
@@ -0,0 +1,97 @@
import {
createLayerElement,
renderAnnotationLayer,
viewBoxOf,
} from '@faunosteo/anatomy/render'
import type { SheetView } from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
/**
* Builds the inline SVG of one view: the sheet's drawing (sanitised asset
* text) framed on the view's box, plus the annotation layer generated from
* the document. The drawing is parsed once per asset and cloned per view.
*/
const SVG_NS = 'http://www.w3.org/2000/svg'
const FORBIDDEN_TAGS = ['script', 'foreignObject', 'iframe', 'object', 'embed']
export type ViewStates = ReadonlyMap<string, 'current'>
/** Drops scripts, embedded documents, event handlers and script URLs (LRN-025). */
export function sanitizeSvg(root: Element): void {
for (const tag of FORBIDDEN_TAGS) {
for (const el of Array.from(root.getElementsByTagName(tag))) el.remove()
}
for (const el of Array.from(root.querySelectorAll('*'))) {
for (const attr of Array.from(el.attributes)) {
const name = attr.name.toLowerCase()
const value = attr.value.trim().toLowerCase()
if (name.startsWith('on') || value.startsWith('javascript:')) {
el.removeAttribute(attr.name)
}
}
}
}
export function parseDrawing(svgText: string): SVGSVGElement {
const doc = new DOMParser().parseFromString(svgText, 'image/svg+xml')
if (doc.querySelector('parsererror')) throw new Error('invalid SVG asset')
const root = doc.documentElement
if (root.tagName.toLowerCase() !== 'svg')
throw new Error('asset root is not <svg>')
sanitizeSvg(root)
return root as unknown as SVGSVGElement
}
const parsed = new Map<string, SVGSVGElement>()
function drawingOf(index: SheetIndex, assetId: string): SVGSVGElement {
const key = `${index.sheet.ref.documentSha256}:${assetId}`
let root = parsed.get(key)
if (!root) {
const text = index.sheet.assets[assetId]
if (text === undefined) throw new Error(`asset ${assetId} not bundled`)
root = parseDrawing(text)
parsed.set(key, root)
}
return root
}
/** The asset a view draws: its own, else its parent's (a crop). */
export function assetOfView(index: SheetIndex, view: SheetView): string {
if (view.svg_asset_id) return view.svg_asset_id
if (view.kind === 'detail') {
const parent = index.view(view.parent_view_id)
if (parent) return assetOfView(index, parent)
}
throw new Error(`view ${view.id} has no asset`)
}
export function buildViewSvg(
index: SheetIndex,
viewId: string,
states: ViewStates,
): SVGSVGElement {
const view = index.view(viewId)
if (!view) throw new Error(`unknown view ${viewId}`)
const source = drawingOf(index, assetOfView(index, view))
const svg = document.createElementNS(SVG_NS, 'svg')
for (const attr of Array.from(source.attributes)) {
if (attr.name === 'width' || attr.name === 'height') continue
svg.setAttribute(attr.name, attr.value)
}
svg.setAttribute(
'viewBox',
viewBoxOf(view) ?? source.getAttribute('viewBox') ?? '0 0 100 100',
)
for (const child of Array.from(source.childNodes)) {
svg.appendChild(document.importNode(child, true))
}
const layer = renderAnnotationLayer({
document: index.sheet.document,
viewId,
states,
})
svg.appendChild(createLayerElement(document, layer) as unknown as Node)
return svg
}
-19
View File
@@ -1,19 +0,0 @@
import type { Locale } from '@/i18n/types'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
import type { Bone } from './types'
/**
* Resolves the user-facing label for an anatomical zone given the active
* locale. Falls back to the opposite language when the requested one is
* missing (some SVG hitboxes carry only `data-anno-name-fr`), then to the
* provided fallback (typically the raw boneId) so the UI never renders
* an empty label.
*/
export function boneLabel(
bone: Bone | undefined,
locale: Locale,
fallback: string,
): string {
if (!bone) return fallback
return pickLocaleLabel(bone.fr, bone.en, locale, fallback)
}
-107
View File
@@ -1,107 +0,0 @@
import { SvgConventionError } from './types'
import type { Bone, BoneCategory } from './types'
/**
* Validates that an annotated SVG element carries the two attributes the
* application needs to wire it up: a stable id (`data-anno-id`) and a
* category bucket (`data-anno-category`). Labels (`data-anno-name-fr/en`)
* and the popup trigger (`data-anno-opens-detail`) are optional and
* checked only at use-site.
*
* The category value itself is opaque to the application — any non-empty
* string is accepted. New SVGs are free to introduce new categories
* without touching this parser.
*/
function validateBoneElement(el: Element): void {
const boneId = el.getAttribute('data-anno-id') ?? ''
if (!boneId) {
throw new SvgConventionError(
'Element with missing data-anno-id',
boneId,
'data-anno-id',
)
}
const cat = el.getAttribute('data-anno-category') ?? ''
if (!cat) {
throw new SvgConventionError(
`Element data-anno-id="${boneId}" missing attribute data-anno-category`,
boneId,
'data-anno-category',
)
}
}
/**
* Parses an SVG document and returns a map of `data-anno-id` → Bone.
*
* Every element carrying `data-anno-id` is collected. Multiple elements
* may share the same id (e.g. hitbox + visible layer); they all end up
* grouped under the same Bone with all elements in `els`.
*
* Throws `SvgConventionError` only on the two required attributes
* (`data-anno-id`, `data-anno-category`). Labels are optional.
*/
export function parseSvgBones(svgRoot: SVGSVGElement): Map<string, Bone> {
const map = new Map<string, Bone>()
const all = svgRoot.querySelectorAll<Element>('[data-anno-id]')
all.forEach((el) => {
validateBoneElement(el)
const id = el.getAttribute('data-anno-id') as string
const fr = el.getAttribute('data-anno-name-fr') ?? ''
const en = el.getAttribute('data-anno-name-en') ?? ''
const category = el.getAttribute('data-anno-category') as BoneCategory
const opensDetail =
el.getAttribute('data-anno-opens-detail') ?? undefined
const special = el.getAttribute('data-anno-special') ?? undefined
const lateral = (el.getAttribute('data-anno-lateral') ?? undefined) as
| 'bilateral'
| 'unpaired'
| undefined
const existing = map.get(id)
if (existing) {
existing.els.push(el)
if (opensDetail && !existing.opensDetail) {
existing.opensDetail = opensDetail
}
if (special && !existing.special) {
existing.special = special
}
if (lateral && !existing.lateral) {
existing.lateral = lateral
}
if (!existing.fr && fr) existing.fr = fr
if (!existing.en && en) existing.en = en
} else {
map.set(id, {
id,
fr,
en,
category,
opensDetail,
special,
lateral,
els: [el],
})
}
})
return map
}
/**
* Walks up from `event.target` to find the nearest element carrying
* `data-anno-id`. Returns null when the click did not land on an
* annotated element.
*/
export function getBoneIdFromEvent(event: Event): string | null {
return getAnnotatedElement(event)?.getAttribute('data-anno-id') || null
}
export function getAnnotatedElement(event: Event): Element | null {
let node = event.target as Element | null
while (node && node.nodeType === 1) {
if (node.hasAttribute('data-anno-id')) return node
node = node.parentElement
}
return null
}
-17
View File
@@ -1,17 +0,0 @@
export async function loadSvg(publicPath: string): Promise<SVGSVGElement> {
const resp = await fetch(publicPath)
if (!resp.ok) {
throw new Error(`Failed to load SVG ${publicPath}: HTTP ${resp.status}`)
}
const text = await resp.text()
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
const parseErr = doc.querySelector('parsererror')
if (parseErr) {
throw new Error(`Invalid SVG at ${publicPath}: ${parseErr.textContent}`)
}
const root = doc.documentElement
if (root.tagName.toLowerCase() !== 'svg') {
throw new Error(`Root element of ${publicPath} is not <svg>`)
}
return root as unknown as SVGSVGElement
}
-55
View File
@@ -1,55 +0,0 @@
/**
* `data-anno-category` is a free-form string supplied by the SVG.
*
* The application never branches on category values — it treats every
* annotation the same way. Categories are kept around because they're
* useful for grouping and future filtering, but no code path here may
* rely on a closed set.
*/
export type BoneCategory = string
/**
* Logical annotation as parsed from an SVG. All DOM elements sharing the
* same `data-anno-id` are grouped into one Bone. `id` is the persisted
* identifier surfaced in the report JSON contract
* (`ObservationZone.boneId`); keep it stable across SVG renames.
*/
export interface Bone {
id: string
/** French label from data-anno-name-fr — may be empty for opens-detail-only triggers */
fr: string
/** English label from data-anno-name-en — may be empty */
en: string
/** Raw value from data-anno-category — opaque to the application */
category: BoneCategory
/** Detail popup id from data-anno-opens-detail, if present */
opensDetail?: string
/**
* Free-form behavior hint from `data-anno-special`.
*
* Known values consumed by the application:
* - `vertebral-precision`: clicking the zone opens VertebraPicker.
*
* Opaque to the parser; new values are accepted without code changes.
*/
special?: string
/** Laterality hint from data-anno-lateral — bilateral or unpaired */
lateral?: 'bilateral' | 'unpaired'
/** All DOM elements carrying this annotation (used for colorization) */
els: Element[]
}
/** Visual state applied to SVG elements (active-observation highlight). */
export type BoneState = 'current' | 'default'
/** Error thrown when SVG violates the convention. */
export class SvgConventionError extends Error {
constructor(
message: string,
public readonly boneId: string,
public readonly missingAttribute: string,
) {
super(message)
this.name = 'SvgConventionError'
}
}
+2 -7
View File
@@ -1,15 +1,12 @@
import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom' import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { ConfigProvider } from './providers/ConfigProvider' import { ConfigProvider } from './providers/ConfigProvider'
import Footer from '@/components/brand/Footer' import Footer from '@/components/brand/Footer'
import HomeRoute from './routes/HomeRoute' import HomeRoute from './routes/HomeRoute'
import NewReportRoute from './routes/NewReportRoute' import NewReportRoute from './routes/NewReportRoute'
import EditorRoute from './routes/EditorRoute' import EditorRoute from './routes/EditorRoute'
import SvgEditorRoute from './routes/SvgEditorRoute'
import EditorsRoute from './routes/EditorsRoute'
import NotFoundRoute from './routes/NotFoundRoute' import NotFoundRoute from './routes/NotFoundRoute'
function AppShell() { function AppShell() {
const hideFooter = useLocation().pathname === '/svg-editor'
return ( return (
<div className="flex min-h-screen flex-col"> <div className="flex min-h-screen flex-col">
<main className="flex-1 flex flex-col"> <main className="flex-1 flex flex-col">
@@ -17,12 +14,10 @@ function AppShell() {
<Route path="/" element={<HomeRoute />} /> <Route path="/" element={<HomeRoute />} />
<Route path="/new" element={<NewReportRoute />} /> <Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<EditorRoute />} /> <Route path="/editor" element={<EditorRoute />} />
<Route path="/svg-editor" element={<SvgEditorRoute />} />
<Route path="/editors" element={<EditorsRoute />} />
<Route path="*" element={<NotFoundRoute />} /> <Route path="*" element={<NotFoundRoute />} />
</Routes> </Routes>
</main> </main>
{!hideFooter && <Footer />} <Footer />
</div> </div>
) )
} }
+183 -448
View File
@@ -1,329 +1,151 @@
import { useEffect, useMemo, useState } from 'react' import { useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import DetailModal from '@/components/canvas/DetailModal' import DetailModal from '@/components/canvas/DetailModal'
import ObservationList from '@/components/observation/ObservationList' import ObservationList from '@/components/observation/ObservationList'
import VertebraPicker from '@/components/observation/VertebraPicker' import ObservationPickers from '@/components/observation/ObservationPickers'
import { regionFromLabel } from '@/lib/spineZones'
import LateralityPicker from '@/components/observation/LateralityPicker'
import type { LateralSide } from '@/domain/schema/observation'
import ConclusionPanel from '@/components/report/ConclusionPanel' import ConclusionPanel from '@/components/report/ConclusionPanel'
import ReportHeader from '@/components/report/ReportHeader' import ReportHeader from '@/components/report/ReportHeader'
import PractitionerForm from '@/components/report/PractitionerForm' import EditInfosDialog, {
import AnimalForm from '@/components/report/AnimalForm' isIdentityComplete,
type Identity,
} from '@/components/report/EditInfosDialog'
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { useReportStore } from '@/state/reportStore' import { useReportStore } from '@/state/reportStore'
import { writeCachedPractitioner } from '@/state/practitionerCache' import { writeCachedPractitioner } from '@/state/practitionerCache'
import { getSpecies } from '@/domain/species/registry' import { useLocaleStore } from '@/state/localeStore'
import { loadSvg } from '@/anatomy/svgLoader' import { useSheet } from '@/sheets/useSheet'
import { parseSvgBones } from '@/anatomy/svgConvention' import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
import { collectSpineVertebrae, syncSpineZones } from '@/lib/spineZones' import {
import type { Bone, BoneState } from '@/anatomy/types' decideZoneClick,
import type { Observation, ObservationZone } from '@/domain/schema/observation' ensureZone,
import type { Report } from '@/domain/schema/report' refOf,
import type { SpeciesFindings } from '@/domain/schema/findings' removeAllSides,
import type { Practitioner } from '@/domain/schema/practitioner' removeZoneAt,
import type { Animal, Owner } from '@/domain/schema/animal' toggleZone,
type ZoneRef,
} from '@/services/zoneInteraction'
import type { ViewStates } from '@/anatomy/drawing'
import { exportReportToPdf } from '@/pdf/export' import { exportReportToPdf } from '@/pdf/export'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore' import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { boneLabel } from '@/anatomy/labels'
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
/** Merges newly parsed bones into the accumulated map without overwriting. */ /** Editor on the reference sheet: wires the canvas, the pickers and the store. */
function mergeBones(prev: Map<string, Bone>, parsed: Map<string, Bone>) {
const merged = new Map(prev)
parsed.forEach((b, id) => {
if (!merged.has(id)) merged.set(id, b)
})
return merged
}
export default function EditorRoute() { export default function EditorRoute() {
const navigate = useNavigate() const navigate = useNavigate()
const t = useT() const t = useT()
const locale = useLocaleStore((s) => s.locale) const locale = useLocaleStore((s) => s.locale)
const report = useReportStore((s) => s.report) const store = useReportStore()
const activeIndex = useReportStore((s) => s.activeObservationIndex) const { report, activeObservationIndex: activeIndex } = store
const addObservation = useReportStore((s) => s.addObservation) // Without a report yet (draft restore), the default species' sheet carries the migration map.
const updateObservation = useReportStore((s) => s.updateObservation) const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
const removeObservation = useReportStore((s) => s.removeObservation)
const moveObservationUp = useReportStore((s) => s.moveObservationUp)
const moveObservationDown = useReportStore((s) => s.moveObservationDown)
const setActiveObservation = useReportStore((s) => s.setActiveObservation)
const setConclusion = useReportStore((s) => s.setConclusion)
const setRecommendations = useReportStore((s) => s.setRecommendations)
const setNextAppointment = useReportStore((s) => s.setNextAppointment)
const setPractitioner = useReportStore((s) => s.setPractitioner)
const setAnimal = useReportStore((s) => s.setAnimal)
const setOwner = useReportStore((s) => s.setOwner)
const [bones, setBones] = useState<Map<string, Bone>>(new Map()) const [detailViewId, setDetailViewId] = useState<string | null>(null)
const [detailBones, setDetailBones] = useState<Map<string, Bone>>(new Map())
const [findings, setFindings] = useState<SpeciesFindings | null>(null)
const [disclaimer, setDisclaimer] = useState<string | null>(null)
const [detail, setDetail] = useState<{
id: string
src: string
title: string
} | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null) const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
const [lateralTarget, setLateralTarget] = useState<{ const [lateralTarget, setLateralTarget] = useState<ZoneRef | null>(null)
boneId: string const [disclaimer, setDisclaimer] = useState<string | null>(null)
detailSourceId?: string
} | null>(null)
const [exporting, setExporting] = useState(false) const [exporting, setExporting] = useState(false)
const [editOpen, setEditOpen] = useState(false) const [editDraft, setEditDraft] = useState<Identity | null>(null)
const [editDraft, setEditDraft] = useState<{
practitioner: Practitioner
animal: Animal
owner: Owner
} | null>(null)
function openEditInfos() {
if (!report) return
setEditDraft({
practitioner: report.practitioner,
animal: report.animal,
owner: report.owner,
})
setEditOpen(true)
}
function closeEditInfos() {
setEditOpen(false)
setEditDraft(null)
}
function saveEditInfos() {
if (!editDraft) return closeEditInfos()
const name = editDraft.practitioner.name.trim()
const animalName = editDraft.animal.name.trim()
const ownerName = editDraft.owner.name.trim()
if (!name || !animalName || !ownerName) return
setPractitioner(editDraft.practitioner)
setAnimal(editDraft.animal)
setOwner(editDraft.owner)
writeCachedPractitioner(editDraft.practitioner)
closeEditInfos()
}
function acknowledgeDisclaimer() {
if (typeof sessionStorage !== 'undefined') {
sessionStorage.setItem(DISCLAIMER_FLAG, '1')
}
setDisclaimer(null)
}
useEffect(() => {
if (!report) navigate('/')
}, [report, navigate])
useEffect(() => { useEffect(() => {
window.scrollTo({ top: 0, left: 0, behavior: 'auto' }) window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
}, []) }, [])
const species = useMemo( // No report in memory: restore the per-tab draft once the sheet is known.
() => (report ? getSpecies(report.animal.speciesId) : undefined), useEffect(() => {
[report], if (report) return
) if (sheet.status === 'ready')
store.restoreDraft(sheet.index.sheet.migrationMap)
if (sheet.status !== 'loading' && !useReportStore.getState().report)
navigate('/')
}, [report, sheet, store, navigate])
useEffect(() => { useEffect(() => {
if (!species) return if (sheet.status !== 'ready' || typeof sessionStorage === 'undefined')
loadSvg(species.mainSvg).then((root) => setBones(parseSvgBones(root))) return
species.findings().then((m) => setFindings(m.default))
// Eagerly preload every detail SVG so observation zones imported
// from a PDF (which can carry detail-popup boneIds without the user
// ever re-opening the popup) resolve their labels and findings
// pickers immediately on mount. Each fetch is independent — a 404
// on one detail asset must not prevent the others from loading.
Object.values(species.details).forEach((path) => {
loadSvg(path)
.then((root) => {
const parsed = parseSvgBones(root)
setDetailBones((prev) => mergeBones(prev, parsed))
})
.catch((err) => {
console.warn(`EditorRoute: failed to preload detail SVG ${path}`, err)
})
})
}, [species])
useEffect(() => {
if (!findings) return
if (typeof sessionStorage === 'undefined') return
if (sessionStorage.getItem(DISCLAIMER_FLAG)) return if (sessionStorage.getItem(DISCLAIMER_FLAG)) return
setDisclaimer(findings.scope_disclaimer) const text = sheet.index.sheet.document.scope_disclaimer
}, [findings]) setDisclaimer(
pickLabel({ fr: text.fr ?? '', en: text.en ?? '' }, locale) || null,
useEffect(() => { )
if (!detail) return }, [sheet, locale])
let cancelled = false
loadSvg(detail.src).then((root) => {
if (cancelled) return
const parsed = parseSvgBones(root)
setDetailBones((prev) => mergeBones(prev, parsed))
})
return () => {
cancelled = true
}
}, [detail])
const allBones = useMemo(() => {
const m = new Map(bones)
detailBones.forEach((b, id) => {
if (!m.has(id)) m.set(id, b)
})
return m
}, [bones, detailBones])
const activeObs = const activeObs =
activeIndex >= 0 ? report?.observations[activeIndex] : undefined activeIndex >= 0 ? report?.observations[activeIndex] : undefined
const boneStates = useMemo<Map<string, BoneState>>(() => { const states = useMemo<ViewStates>(() => {
const map = new Map<string, BoneState>() const map = new Map<string, 'current'>()
if (!report || activeIndex < 0) return map activeObs?.zones.forEach((z) => map.set(z.annotationId, 'current'))
const active = report.observations[activeIndex]
if (!active) return map
active.zones.forEach((z) => {
map.set(z.boneId, 'current')
})
return map return map
}, [report, activeIndex]) }, [activeObs])
function onToggleCard(index: number) { const onZoneClick = useCallback(
setActiveObservation(activeIndex === index ? -1 : index) (annotationId: string) => {
} // Fresh state: two clicks may land before React re-renders the handler.
const { report, activeObservationIndex: activeIndex } =
/** Opens the detail-popup modal for a bone that carries data-anno-opens-detail. */ useReportStore.getState()
function handleDetailOpen(bone: Bone, detailId: string, detailSrc: string) { if (sheet.status !== 'ready' || !report) return
setDetail({ const activeObs =
id: detailId, activeIndex >= 0 ? report.observations[activeIndex] : undefined
src: detailSrc, const index = sheet.index
title: boneLabel(bone, locale, detailId), const annotation = index.annotation(annotationId)
}) const decision = decideZoneClick(annotation, activeObs)
} if (!annotation) return
switch (decision.kind) {
/** case 'ignore':
* No expanded observation — auto-expand the most recent one (or the return
* first if no rows yet) so the click lands somewhere. Defers the actual case 'open_view':
* zone add to the next render where activeObs is set. return setDetailViewId(decision.viewId)
*/ case 'activate_fallback':
function activateFallbackObservation(report: Report) { return store.setActiveObservation(report.observations.length - 1)
const fallbackIndex = case 'open_vertebra_picker': {
report.observations.length > 0 ? report.observations.length - 1 : -1 const { observation, index: zoneIndex } = ensureZone(
if (fallbackIndex < 0) return activeObs!,
setActiveObservation(fallbackIndex) annotation,
}
/**
* Spine-zone behavior: always open VertebraPicker on click. Adds the
* zone if missing; never toggles it off here (use the ✕ button).
*/
function handleSpineZone(
activeObs: Observation,
boneId: string,
detailSourceId: string | undefined,
existingIndex: number,
) {
let targetIndex = existingIndex
if (existingIndex < 0) {
const newZone: ObservationZone = {
boneId,
...(detailSourceId ? { detailSourceId } : {}),
}
const nextZones = [...activeObs.zones, newZone]
targetIndex = nextZones.length - 1
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
}
setVertebraTarget(targetIndex)
}
/** Bilateral zone: adding a side, or clearing both once left+right are set. */
function handleBilateralZone(
activeObs: Observation,
boneId: string,
detailSourceId: string | undefined,
) {
const sidesPresent = activeObs.zones
.filter(
(z) => z.boneId === boneId && z.detailSourceId === detailSourceId,
) )
.map((z) => z.side) store.updateObservation(activeIndex, observation)
.filter(Boolean) as LateralSide[] return setVertebraTarget(zoneIndex)
}
if (sidesPresent.includes('left') && sidesPresent.includes('right')) { case 'open_laterality_picker':
const nextZones = activeObs.zones.filter( return setLateralTarget(refOf(annotation))
(z) => !(z.boneId === boneId && z.detailSourceId === detailSourceId), case 'remove_both_sides':
return store.updateObservation(
activeIndex,
removeAllSides(activeObs!, refOf(annotation)),
) )
updateObservation(activeIndex, { ...activeObs, zones: nextZones }) case 'toggle':
return return store.updateObservation(
activeIndex,
toggleZone(activeObs!, annotation),
)
}
},
[sheet, store],
)
function acknowledgeDisclaimer() {
sessionStorage?.setItem(DISCLAIMER_FLAG, '1')
setDisclaimer(null)
} }
setLateralTarget({ function saveEditInfos() {
boneId, if (!editDraft) return
...(detailSourceId ? { detailSourceId } : {}), if (!isIdentityComplete(editDraft)) return
}) store.setPractitioner(editDraft.practitioner)
store.setAnimal(editDraft.animal)
store.setOwner(editDraft.owner)
writeCachedPractitioner(editDraft.practitioner)
setEditDraft(null)
} }
/** Plain zone: toggles it on the active observation. */ async function onExport(index: SheetIndex) {
function toggleZone(
activeObs: Observation,
boneId: string,
detailSourceId: string | undefined,
existingIndex: number,
) {
const newZone: ObservationZone = {
boneId,
...(detailSourceId ? { detailSourceId } : {}),
}
const nextZones =
existingIndex >= 0
? activeObs.zones.filter((_, k) => k !== existingIndex)
: [...activeObs.zones, newZone]
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
}
function onZoneClick(boneId: string, detailSourceId?: string) {
if (!report) return
const bone = bones.get(boneId) ?? detailBones.get(boneId)
if (!bone) return
if (bone.opensDetail && species?.details[bone.opensDetail]) {
handleDetailOpen(bone, bone.opensDetail, species.details[bone.opensDetail])
return
}
if (!activeObs || activeIndex < 0) {
activateFallbackObservation(report)
return
}
const matches = (z: ObservationZone) =>
z.boneId === boneId && z.detailSourceId === detailSourceId
const existingIndex = activeObs.zones.findIndex(matches)
if (bone.special === 'vertebral-precision') {
handleSpineZone(activeObs, boneId, detailSourceId, existingIndex)
return
}
if (bone.lateral === 'bilateral') {
handleBilateralZone(activeObs, boneId, detailSourceId)
return
}
toggleZone(activeObs, boneId, detailSourceId, existingIndex)
}
async function onExport() {
if (!report) return if (!report) return
setExporting(true) setExporting(true)
try { try {
const bytes = await exportReportToPdf(report, { locale }) const bytes = await exportReportToPdf(report, index, { locale })
const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' }) const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' })
const url = URL.createObjectURL(blob) const url = URL.createObjectURL(blob)
const a = document.createElement('a') const a = document.createElement('a')
@@ -339,214 +161,127 @@ export default function EditorRoute() {
} }
} }
if (!report || !species) return null if (!report) return null
if (sheet.status === 'loading') {
return (
<p className="p-6 text-sm text-[var(--color-ink-muted)]">
{t('sheet.loading')}
</p>
)
}
if (sheet.status === 'none') return null
const index = sheet.index
const detailView = detailViewId ? index.view(detailViewId) : undefined
return ( return (
<main className="min-h-screen flex flex-col"> <main className="min-h-screen flex flex-col">
<ReportHeader report={report} onEditInfos={openEditInfos} /> <ReportHeader
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6"> report={report}
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none"> onEditInfos={() =>
<AnatomyCanvas setEditDraft({
src={species.mainSvg} practitioner: report.practitioner,
boneStates={boneStates} animal: report.animal,
onZoneClick={(id) => onZoneClick(id)} owner: report.owner,
})
}
/> />
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
<AnatomyCanvas
index={index}
viewId={index.mainView.id}
states={states}
onZoneClick={onZoneClick}
className="flex-1"
/>
<p
className="px-3 py-1.5 text-xs text-[var(--color-ink-muted)] border-t border-[var(--color-border)]"
data-testid="sheet-status"
>
{t(
index.sheet.status === 'draft'
? 'sheet.status.draft'
: 'sheet.status.published',
)}
</p>
</section> </section>
<section className="space-y-4 sm:space-y-6"> <section className="space-y-4 sm:space-y-6">
<ObservationList <ObservationList
observations={report.observations} observations={report.observations}
activeIndex={activeIndex} activeIndex={activeIndex}
onToggle={onToggleCard} onToggle={(i) =>
onAdd={addObservation} store.setActiveObservation(activeIndex === i ? -1 : i)
onDelete={removeObservation} }
onMoveUp={moveObservationUp} onAdd={store.addObservation}
onMoveDown={moveObservationDown} onDelete={store.removeObservation}
bones={allBones} onMoveUp={store.moveObservationUp}
findings={findings} onMoveDown={store.moveObservationDown}
onChange={(i, next: Observation) => updateObservation(i, next)} sheet={index}
onChange={store.updateObservation}
onOpenVertebraPicker={(_i, zoneIndex) => onOpenVertebraPicker={(_i, zoneIndex) =>
setVertebraTarget(zoneIndex) setVertebraTarget(zoneIndex)
} }
onRemoveZone={(i, zoneIndex) => { onRemoveZone={(i, zoneIndex) => {
const obs = report.observations[i] const obs = report.observations[i]
if (!obs) return if (obs) store.updateObservation(i, removeZoneAt(obs, zoneIndex))
const zones = obs.zones.filter((_, k) => k !== zoneIndex)
updateObservation(i, { ...obs, zones })
}} }}
/> />
<ConclusionPanel <ConclusionPanel
conclusion={report.conclusion} conclusion={report.conclusion}
recommendations={report.recommendations} recommendations={report.recommendations}
nextAppointment={report.nextAppointment} nextAppointment={report.nextAppointment}
onChangeConclusion={setConclusion} onChangeConclusion={store.setConclusion}
onChangeRecommendations={setRecommendations} onChangeRecommendations={store.setRecommendations}
onChangeNextAppointment={setNextAppointment} onChangeNextAppointment={store.setNextAppointment}
/> />
<div className="flex justify-end"> <div className="flex justify-end">
<Button onClick={onExport} disabled={exporting}> <Button onClick={() => onExport(index)} disabled={exporting}>
{exporting ? t('editor.exporting') : t('editor.export')} {exporting ? t('editor.exporting') : t('editor.export')}
</Button> </Button>
</div> </div>
</section> </section>
</div> </div>
{detail && ( {detailView && (
<DetailModal <DetailModal
open open
onClose={() => setDetail(null)} onClose={() => setDetailViewId(null)}
detailSrc={detail.src} index={index}
detailId={detail.id} viewId={detailView.id}
title={`${t('editor.detail_title_prefix')}${detail.title}`} title={pickLabel(detailView.name, locale)}
boneStates={boneStates} states={states}
onZoneClick={(id, did) => onZoneClick(id, did)} onZoneClick={onZoneClick}
/> />
)} )}
{editDraft && ( {editDraft && (
<Dialog <EditInfosDialog
open={editOpen} draft={editDraft}
onClose={closeEditInfos} species={[
title={t('editor.edit_dialog_title')} { id: index.sheet.speciesId, name: index.sheet.document.name },
size="lg" ]}
> onChange={setEditDraft}
<div className="space-y-8"> onCancel={() => setEditDraft(null)}
<PractitionerForm onSave={saveEditInfos}
value={editDraft.practitioner}
onChange={(next) =>
setEditDraft((d) => (d ? { ...d, practitioner: next } : d))
}
/> />
<AnimalForm
animal={editDraft.animal}
owner={editDraft.owner}
onChangeAnimal={(next) =>
setEditDraft((d) => (d ? { ...d, animal: next } : d))
}
onChangeOwner={(next) =>
setEditDraft((d) => (d ? { ...d, owner: next } : d))
}
/>
<div className="flex gap-3 justify-end pt-2 border-t border-[var(--color-border)]">
<Button variant="ghost" onClick={closeEditInfos}>
{t('common.cancel')}
</Button>
<Button
onClick={saveEditInfos}
disabled={
!editDraft.practitioner.name.trim() ||
!editDraft.animal.name.trim() ||
!editDraft.owner.name.trim()
}
>
{t('common.save')}
</Button>
</div>
</div>
</Dialog>
)} )}
{disclaimer && ( {disclaimer && (
<Dialog <DisclaimerDialog
open text={disclaimer}
onClose={acknowledgeDisclaimer} onAcknowledge={acknowledgeDisclaimer}
title={t('editor.disclaimer_title')}
size="md"
>
<div className="space-y-4">
<p className="text-sm text-[var(--color-ink)]">{disclaimer}</p>
<div className="flex justify-end">
<Button onClick={acknowledgeDisclaimer}>{t('common.understood')}</Button>
</div>
</div>
</Dialog>
)}
{vertebraTarget !== null &&
activeObs &&
activeObs.zones[vertebraTarget] && (
<VertebraPicker
open
onClose={() => setVertebraTarget(null)}
onConfirm={(vertebrae) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (!fresh?.zones[vertebraTarget]) {
setVertebraTarget(null)
return
}
// Picker edits every region at once: reconcile all spine zones —
// spawn newly picked regions, prune emptied ones, keep the rest.
const next = syncSpineZones(fresh.zones, vertebrae, bones)
updateObservation(activeIndex, { ...fresh, zones: next })
setVertebraTarget(null)
}}
initial={collectSpineVertebrae(
activeObs.zones,
bones,
activeObs.zones[vertebraTarget].boneId,
)}
formula={species.vertebralFormula}
title={`${t('vertebra.title_prefix')}${boneLabel(
bones.get(activeObs.zones[vertebraTarget].boneId),
locale,
'',
)}`}
initialRegion={(() => {
const b = bones.get(activeObs.zones[vertebraTarget].boneId)
return regionFromLabel(b?.fr ?? '') ?? regionFromLabel(b?.en ?? '')
})()}
/> />
)} )}
{lateralTarget && activeObs && ( <ObservationPickers
<LateralityPicker sheet={index}
open activeIndex={activeIndex}
onClose={() => setLateralTarget(null)} activeObs={activeObs}
title={boneLabel( vertebraTarget={vertebraTarget}
allBones.get(lateralTarget.boneId), lateralTarget={lateralTarget}
locale, onCloseVertebra={() => setVertebraTarget(null)}
lateralTarget.boneId, onCloseLateral={() => setLateralTarget(null)}
)}
existingSides={
activeObs.zones
.filter(
(z) =>
z.boneId === lateralTarget.boneId &&
z.detailSourceId === lateralTarget.detailSourceId &&
z.side,
)
.map((z) => z.side!) as LateralSide[]
}
onSelect={(sides) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (!fresh) {
setLateralTarget(null)
return
}
const newSideZones = sides
.filter(
(side) =>
!fresh.zones.some(
(z) =>
z.boneId === lateralTarget.boneId &&
z.detailSourceId === lateralTarget.detailSourceId &&
z.side === side,
),
)
.map((side) => ({
boneId: lateralTarget.boneId,
...(lateralTarget.detailSourceId
? { detailSourceId: lateralTarget.detailSourceId }
: {}),
side,
}))
const nextZones = [...fresh.zones, ...newSideZones]
updateObservation(activeIndex, { ...fresh, zones: nextZones })
setLateralTarget(null)
}}
/> />
)}
</main> </main>
) )
} }
-42
View File
@@ -1,42 +0,0 @@
import { Link } from 'react-router-dom'
import AppHeader from '@/components/brand/AppHeader'
import Card from '@/components/ui/Card'
import { useT } from '@/i18n/useT'
export default function EditorsRoute() {
const t = useT()
return (
<main className="flex-1 flex flex-col">
<AppHeader />
<section className="flex-1 grid place-items-center px-4 sm:px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">{t('editors.svg.title')}</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editors.svg.description')}
</p>
<Link
to="/svg-editor"
className="inline-block rounded-lg bg-[var(--color-accent)] px-5 py-2 text-sm font-medium text-white hover:bg-[var(--color-accent-strong)] transition-colors"
>
{t('editors.svg.cta')}
</Link>
</Card>
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">{t('editors.pathology.title')}</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editors.pathology.description')}
</p>
<a
href="/pathology-editor.html"
className="inline-block rounded-lg bg-[var(--color-accent)] px-5 py-2 text-sm font-medium text-white hover:bg-[var(--color-accent-strong)] transition-colors"
>
{t('editors.pathology.cta')}
</a>
</Card>
</div>
</section>
</main>
)
}
+64 -10
View File
@@ -5,25 +5,42 @@ import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card' import Card from '@/components/ui/Card'
import { importReportFromPdf, ImportError } from '@/pdf/import' import { importReportFromPdf, ImportError } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore' import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
export default function HomeRoute() { export default function HomeRoute() {
const navigate = useNavigate() const navigate = useNavigate()
const fileRef = useRef<HTMLInputElement | null>(null) const fileRef = useRef<HTMLInputElement | null>(null)
const hydrate = useReportStore((s) => s.hydrateReport) const hydrate = useReportStore((s) => s.hydrateReport)
const sheet = useSheet(DEFAULT_SPECIES_ID)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const t = useT() const t = useT()
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) { async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0] const file = e.target.files?.[0]
if (!file) return if (!file || sheet.status !== 'ready') return
setBusy(true) setBusy(true)
setError(null) setError(null)
try { try {
const bytes = new Uint8Array(await file.arrayBuffer()) const bytes = new Uint8Array(await file.arrayBuffer())
const report = await importReportFromPdf(bytes) const outcome = await importReportFromPdf(
hydrate(report) bytes,
sheet.index.sheet.migrationMap,
)
if (
outcome.migrated &&
outcome.unresolvedFindings + outcome.unresolvedZones > 0
) {
window.alert(
t('home.import.migrated').replace(
'{count}',
String(outcome.unresolvedFindings + outcome.unresolvedZones),
),
)
}
hydrate(outcome.report)
navigate('/editor') navigate('/editor')
} catch (err) { } catch (err) {
if (err instanceof ImportError) { if (err instanceof ImportError) {
@@ -48,21 +65,58 @@ export default function HomeRoute() {
} }
} }
const noSheet = sheet.status === 'none'
return ( return (
<main className="flex-1 flex flex-col"> <main className="flex-1 flex flex-col">
<AppHeader /> <AppHeader />
<section className="flex-1 grid place-items-center px-4 sm:px-6"> <section className="flex-1 grid place-items-center px-4 sm:px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full"> <div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
{noSheet && (
<Card className="p-4 sm:p-6 space-y-2 md:col-span-2">
<h2 className="font-serif text-xl sm:text-2xl">
{t('home.no_sheet.title')}
</h2>
<p className="text-sm text-red-700">
{t('home.no_sheet.description')}
</p>
</Card>
)}
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4"> <Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">{t('home.new_report.title')}</h2> <h2 className="font-serif text-xl sm:text-2xl">
<p className="text-sm text-[var(--color-ink-muted)]">{t('home.new_report.description')}</p> {t('home.new_report.title')}
<Button onClick={() => navigate('/new')} size="lg">{t('home.new_report.cta')}</Button> </h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('home.new_report.description')}
</p>
<Button
onClick={() => navigate('/new')}
size="lg"
disabled={noSheet}
>
{t('home.new_report.cta')}
</Button>
</Card> </Card>
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4"> <Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">{t('home.import.title')}</h2> <h2 className="font-serif text-xl sm:text-2xl">
<p className="text-sm text-[var(--color-ink-muted)]">{t('home.import.description')}</p> {t('home.import.title')}
<input ref={fileRef} type="file" accept="application/pdf,.pdf" className="hidden" onChange={onPickFile} /> </h2>
<Button variant="secondary" size="lg" onClick={() => fileRef.current?.click()} disabled={busy}> <p className="text-sm text-[var(--color-ink-muted)]">
{t('home.import.description')}
</p>
<input
ref={fileRef}
type="file"
accept="application/pdf,.pdf"
className="hidden"
onChange={onPickFile}
/>
<Button
variant="secondary"
size="lg"
onClick={() => fileRef.current?.click()}
disabled={busy || sheet.status !== 'ready'}
>
{busy ? t('home.import.loading') : t('home.import.cta')} {busy ? t('home.import.loading') : t('home.import.cta')}
</Button> </Button>
{error && <p className="text-sm text-red-700">{error}</p>} {error && <p className="text-sm text-red-700">{error}</p>}
+68 -13
View File
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
import PractitionerForm from '@/components/report/PractitionerForm' import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm' import AnimalForm from '@/components/report/AnimalForm'
import AppHeader from '@/components/brand/AppHeader' import AppHeader from '@/components/brand/AppHeader'
@@ -7,18 +8,29 @@ import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import { todayIso } from '@/lib/dates' import { todayIso } from '@/lib/dates'
import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache' import {
readCachedPractitioner,
writeCachedPractitioner,
} from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore' import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
/** The one species this build ships a sheet for. */
export const DEFAULT_SPECIES_ID = 'equine'
export default function NewReportRoute() { export default function NewReportRoute() {
const navigate = useNavigate() const navigate = useNavigate()
const initReport = useReportStore((s) => s.initReport) const initReport = useReportStore((s) => s.initReport)
const t = useT() const t = useT()
const sheet = useSheet(DEFAULT_SPECIES_ID)
const [practitioner, setPractitioner] = useState({ name: '' }) const [practitioner, setPractitioner] = useState<Practitioner>({ name: '' })
const [animal, setAnimal] = useState({ speciesId: 'equine', name: '' }) const [animal, setAnimal] = useState<Animal>({
const [owner, setOwner] = useState({ name: '' }) speciesId: DEFAULT_SPECIES_ID,
name: '',
})
const [owner, setOwner] = useState<Owner>({ name: '' })
const [date, setDate] = useState(todayIso()) const [date, setDate] = useState(todayIso())
useEffect(() => { useEffect(() => {
@@ -26,12 +38,17 @@ export default function NewReportRoute() {
if (cached) setPractitioner(cached) if (cached) setPractitioner(cached)
}, []) }, [])
const canSubmit = practitioner.name.trim() && animal.name.trim() && owner.name.trim() const canSubmit =
practitioner.name.trim() &&
animal.name.trim() &&
owner.name.trim() &&
sheet.status === 'ready'
function submit() { function submit() {
if (!canSubmit) return if (!canSubmit || sheet.status !== 'ready') return
writeCachedPractitioner(practitioner) writeCachedPractitioner(practitioner)
initReport({ initReport(
{
date, date,
practitioner, practitioner,
animal, animal,
@@ -39,7 +56,9 @@ export default function NewReportRoute() {
observations: [], observations: [],
conclusion: '', conclusion: '',
recommendations: '', recommendations: '',
}) },
sheet.index.sheet.ref,
)
navigate('/editor') navigate('/editor')
} }
@@ -47,16 +66,52 @@ export default function NewReportRoute() {
<main className="min-h-screen"> <main className="min-h-screen">
<AppHeader /> <AppHeader />
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8"> <div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8">
<h1 className="font-serif text-2xl sm:text-3xl">{t('new_report.title')}</h1> <h1 className="font-serif text-2xl sm:text-3xl">
{t('new_report.title')}
</h1>
{sheet.status === 'none' && (
<p className="text-sm text-red-700">
{t('home.no_sheet.description')}
</p>
)}
<div> <div>
<Label htmlFor="date">{t('new_report.date_label')}</Label> <Label htmlFor="date">{t('new_report.date_label')}</Label>
<Input id="date" type="date" value={date} onChange={(e) => setDate(e.target.value)} /> <Input
id="date"
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
</div> </div>
<PractitionerForm value={practitioner} onChange={setPractitioner} /> <PractitionerForm value={practitioner} onChange={setPractitioner} />
<AnimalForm animal={animal} owner={owner} onChangeAnimal={setAnimal} onChangeOwner={setOwner} /> <AnimalForm
animal={animal}
owner={owner}
species={
sheet.status === 'ready'
? [
{
id: sheet.index.sheet.speciesId,
name: sheet.index.sheet.document.name,
},
]
: [
{
id: DEFAULT_SPECIES_ID,
name: { fr: 'Cheval', en: 'Horse' },
},
]
}
onChangeAnimal={setAnimal}
onChangeOwner={setOwner}
/>
<div className="flex gap-3 justify-end"> <div className="flex gap-3 justify-end">
<Button variant="ghost" onClick={() => navigate('/')}>{t('common.cancel')}</Button> <Button variant="ghost" onClick={() => navigate('/')}>
<Button disabled={!canSubmit} onClick={submit}>{t('new_report.submit')}</Button> {t('common.cancel')}
</Button>
<Button disabled={!canSubmit} onClick={submit}>
{t('new_report.submit')}
</Button>
</div> </div>
</div> </div>
</main> </main>
+6 -2
View File
@@ -9,8 +9,12 @@ export default function NotFoundRoute() {
<main className="min-h-screen grid place-items-center"> <main className="min-h-screen grid place-items-center">
<div className="text-center space-y-4"> <div className="text-center space-y-4">
<h1 className="font-serif text-4xl">{t('not_found.title')}</h1> <h1 className="font-serif text-4xl">{t('not_found.title')}</h1>
<p className="text-[var(--color-ink-muted)]">{t('not_found.description')}</p> <p className="text-[var(--color-ink-muted)]">
<Button onClick={() => navigate('/')}>{t('common.back_to_home')}</Button> {t('not_found.description')}
</p>
<Button onClick={() => navigate('/')}>
{t('common.back_to_home')}
</Button>
</div> </div>
</main> </main>
) )
File diff suppressed because it is too large. Load diff
+1 -9
View File
@@ -1,4 +1,3 @@
import { Link } from 'react-router-dom'
import { useConfig } from '@/app/providers/ConfigProvider' import { useConfig } from '@/app/providers/ConfigProvider'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
@@ -9,14 +8,7 @@ export default function Footer() {
return ( return (
<footer className="mt-8 sm:mt-12 border-t border-neutral-200 bg-neutral-50 py-4 sm:py-6 text-center text-xs sm:text-sm text-neutral-600"> <footer className="mt-8 sm:mt-12 border-t border-neutral-200 bg-neutral-50 py-4 sm:py-6 text-center text-xs sm:text-sm text-neutral-600">
<p className="mb-3"> <p className="mb-3">
© {year} {cfg.footerName}. {t('footer.all_rights_reserved')}{' '} © {year} {cfg.footerName}. {t('footer.all_rights_reserved')}
<span className="text-neutral-300">·</span>{' '}
<Link
to="/editors"
className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors"
>
{t('footer.editors')}
</Link>
</p> </p>
<div className="flex flex-wrap items-center justify-center gap-2 sm:gap-4"> <div className="flex flex-wrap items-center justify-center gap-2 sm:gap-4">
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
@@ -1,77 +1,86 @@
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useLayoutEffect, useRef } from 'react'
import { loadSvg } from '@/anatomy/svgLoader' import { buildViewSvg, type ViewStates } from '@/anatomy/drawing'
import { import type { SheetIndex } from '@/services/sheetIndex'
getBoneIdFromEvent,
getAnnotatedElement,
} from '@/anatomy/svgConvention'
import type { BoneState } from '@/anatomy/types'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
export interface AnatomyCanvasProps { export interface AnatomyCanvasProps {
src: string index: SheetIndex
boneStates: Map<string, BoneState> viewId: string
onZoneClick: (boneId: string) => void states: ViewStates
onZoneClick: (annotationId: string, viewId: string) => void
className?: string className?: string
} }
const ANNOTATED = '[data-anno-id]'
function annotatedTarget(event: Event): Element | null {
const target = event.target
return target instanceof Element ? target.closest(ANNOTATED) : null
}
/**
* One view of the sheet: the drawing plus the annotation layer generated
* from the document, rebuilt when the view changes and restyled in place
* when the selection changes. Clicks are delegated on `data-anno-id`.
*/
export default function AnatomyCanvas({ export default function AnatomyCanvas({
src, index,
boneStates, viewId,
states,
onZoneClick, onZoneClick,
className = '', className = '',
}: AnatomyCanvasProps) { }: AnatomyCanvasProps) {
const wrapperRef = useRef<HTMLDivElement | null>(null) const wrapperRef = useRef<HTMLDivElement | null>(null)
const svgRef = useRef<HTMLDivElement | null>(null) const svgRef = useRef<HTMLDivElement | null>(null)
const tooltipRef = useRef<HTMLDivElement | null>(null) const tooltipRef = useRef<HTMLDivElement | null>(null)
const [loadedSrc, setLoadedSrc] = useState<string | null>(null)
const locale = useLocaleStore((s) => s.locale) const locale = useLocaleStore((s) => s.locale)
// Latest states for the build effect, which must only re-run on a view change.
const statesRef = useRef(states)
useLayoutEffect(() => {
statesRef.current = states
}, [states])
useEffect(() => { useEffect(() => {
let cancelled = false const host = svgRef.current
const c = svgRef.current if (!host) return
if (!c) return host.replaceChildren(buildViewSvg(index, viewId, statesRef.current))
c.replaceChildren() }, [index, viewId])
setLoadedSrc(null)
loadSvg(src).then((root) => {
if (cancelled || !c) return
c.appendChild(root)
setLoadedSrc(src)
})
return () => { cancelled = true }
}, [src])
useEffect(() => { useEffect(() => {
const c = svgRef.current const host = svgRef.current
if (!c) return if (!host) return
const onClick = (e: Event) => { host.querySelectorAll<Element>(ANNOTATED).forEach((el) => {
const id = getBoneIdFromEvent(e) const state = states.get(el.getAttribute('data-anno-id') ?? '')
if (id) onZoneClick(id) if (state) el.setAttribute('data-state', state)
}
c.addEventListener('click', onClick)
return () => c.removeEventListener('click', onClick)
}, [onZoneClick])
useEffect(() => {
const c = svgRef.current
if (!c || loadedSrc !== src) return
const all = c.querySelectorAll<Element>('[data-anno-id]')
all.forEach((el) => {
const id = el.getAttribute('data-anno-id') as string
const state = boneStates.get(id)
if (state && state !== 'default') el.setAttribute('data-state', state)
else el.removeAttribute('data-state') else el.removeAttribute('data-state')
}) })
}, [boneStates, loadedSrc, src]) }, [states, index, viewId])
useEffect(() => {
const host = svgRef.current
if (!host) return
const onClick = (e: Event) => {
const id = annotatedTarget(e)?.getAttribute('data-anno-id')
if (id) onZoneClick(id, viewId)
}
host.addEventListener('click', onClick)
return () => host.removeEventListener('click', onClick)
}, [onZoneClick, viewId])
const showTooltip = useCallback( const showTooltip = useCallback(
(el: Element, x: number, y: number) => { (el: Element, x: number, y: number) => {
const tip = tooltipRef.current const tip = tooltipRef.current
if (!tip) return if (!tip) return
const fr = el.getAttribute('data-anno-name-fr') ?? '' const label = pickLocaleLabel(
const en = el.getAttribute('data-anno-name-en') ?? '' el.getAttribute('data-anno-name-fr') ?? '',
const label = pickLocaleLabel(fr, en, locale) el.getAttribute('data-anno-name-en') ?? '',
if (!label) { tip.style.opacity = '0'; return } locale,
)
if (!label) {
tip.style.opacity = '0'
return
}
tip.textContent = label tip.textContent = label
tip.style.opacity = '1' tip.style.opacity = '1'
tip.style.left = `${x + 12}px` tip.style.left = `${x + 12}px`
@@ -80,46 +89,40 @@ export default function AnatomyCanvas({
[locale], [locale],
) )
const hideTooltip = useCallback(() => {
const tip = tooltipRef.current
if (tip) tip.style.opacity = '0'
}, [])
useEffect(() => { useEffect(() => {
const c = svgRef.current const host = svgRef.current
if (!c || loadedSrc !== src) return if (!host) return
const hide = () => {
if (tooltipRef.current) tooltipRef.current.style.opacity = '0'
}
const onMove = (e: MouseEvent) => { const onMove = (e: MouseEvent) => {
const el = getAnnotatedElement(e) const el = annotatedTarget(e)
if (el && !el.hasAttribute('data-anno-opens-detail')) { const wrapper = wrapperRef.current
const w = wrapperRef.current if (!el || !wrapper || el.hasAttribute('data-anno-opens-view'))
if (!w) return return hide()
const rect = w.getBoundingClientRect() const rect = wrapper.getBoundingClientRect()
showTooltip(el, e.clientX - rect.left, e.clientY - rect.top) showTooltip(el, e.clientX - rect.left, e.clientY - rect.top)
} else {
hideTooltip()
} }
} host.addEventListener('mousemove', onMove)
const onLeave = () => hideTooltip() host.addEventListener('mouseleave', hide)
c.addEventListener('mousemove', onMove)
c.addEventListener('mouseleave', onLeave)
return () => { return () => {
c.removeEventListener('mousemove', onMove) host.removeEventListener('mousemove', onMove)
c.removeEventListener('mouseleave', onLeave) host.removeEventListener('mouseleave', hide)
} }
}, [loadedSrc, src, showTooltip, hideTooltip]) }, [showTooltip])
return ( return (
<div <div
data-testid="anatomy-canvas" data-testid="anatomy-canvas"
data-view-id={viewId}
ref={wrapperRef} ref={wrapperRef}
className={`svg-canvas relative w-full h-full ${className}`} className={`svg-canvas relative w-full h-full ${className}`}
> >
<div ref={svgRef} className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto" />
<div <div
ref={tooltipRef} ref={svgRef}
className="zone-tooltip" className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto"
style={{ opacity: 0 }}
/> />
<div ref={tooltipRef} className="zone-tooltip" style={{ opacity: 0 }} />
</div> </div>
) )
} }
+14 -11
View File
@@ -1,25 +1,27 @@
import Dialog from '@/components/ui/Dialog' import Dialog from '@/components/ui/Dialog'
import AnatomyCanvas from './AnatomyCanvas' import AnatomyCanvas from './AnatomyCanvas'
import type { BoneState } from '@/anatomy/types' import type { ViewStates } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
export interface DetailModalProps { export interface DetailModalProps {
open: boolean open: boolean
onClose: () => void onClose: () => void
detailSrc: string index: SheetIndex
detailId: string viewId: string
title: string title: string
boneStates: Map<string, BoneState> states: ViewStates
onZoneClick: (boneId: string, detailId: string) => void onZoneClick: (annotationId: string, viewId: string) => void
} }
/** A detail view of the sheet (a crop or its own drawing) in a dialog. */
export default function DetailModal({ export default function DetailModal({
open, open,
onClose, onClose,
detailSrc, index,
detailId, viewId,
title, title,
boneStates, states,
onZoneClick, onZoneClick,
}: DetailModalProps) { }: DetailModalProps) {
const t = useT() const t = useT()
@@ -27,9 +29,10 @@ export default function DetailModal({
<Dialog open={open} onClose={onClose} title={title} size="xl"> <Dialog open={open} onClose={onClose} title={title} size="xl">
<div className="aspect-[4/3] w-full"> <div className="aspect-[4/3] w-full">
<AnatomyCanvas <AnatomyCanvas
src={detailSrc} index={index}
boneStates={boneStates} viewId={viewId}
onZoneClick={(id) => onZoneClick(id, detailId)} states={states}
onZoneClick={onZoneClick}
/> />
</div> </div>
<p className="mt-4 text-sm text-[var(--color-ink-muted)]"> <p className="mt-4 text-sm text-[var(--color-ink-muted)]">
@@ -1,75 +1,84 @@
import { useMemo, useState } from 'react' import { useMemo, useState } from 'react'
import { motion } from 'motion/react' import { motion } from 'motion/react'
import type { import type {
Finding,
FindingCategory,
FindingNode, FindingNode,
ZoneFindings, FindingZone,
} from '@/domain/schema/findings' LateralSide,
import type { Finding, LateralSide } from '@/domain/schema/observation' LocalizedOptionalText,
} from '@faunosteo/domain'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import { pickLabel } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
const levelVariants = { const levelVariants = {
enter: (dir: 1 | -1) => ({ opacity: 0, x: dir * 32 }), enter: (dir: 1 | -1) => ({ opacity: 0, x: dir * 32 }),
center: { opacity: 1, x: 0 }, center: { opacity: 1, x: 0 },
} }
type TreeNode = FindingCategory | FindingNode
export interface FindingsTreePickerProps { export interface FindingsTreePickerProps {
zoneId: string zone: FindingZone
tree: ZoneFindings
side?: LateralSide side?: LateralSide
selected: Finding[] selected: Finding[]
onChange: (next: Finding[]) => void onChange: (next: Finding[]) => void
} }
function isLeaf(node: FindingNode): boolean { function isLeaf(node: TreeNode): boolean {
return !node.children || node.children.length === 0 return node.children.length === 0
} }
function samePath(a: string[], b: string[]): boolean { function samePath(a: readonly string[], b: readonly string[]): boolean {
if (a.length !== b.length) return false return a.length === b.length && a.every((seg, i) => seg === b[i])
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) return false
}
return true
} }
function pathStartsWith(full: string[], prefix: string[]): boolean { function pathStartsWith(
if (full.length < prefix.length) return false full: readonly string[],
for (let i = 0; i < prefix.length; i += 1) { prefix: readonly string[],
if (full[i] !== prefix[i]) return false ): boolean {
} return (
return true full.length >= prefix.length && prefix.every((seg, i) => full[i] === seg)
)
} }
function findNode( function findNode(
categories: FindingNode[], categories: readonly FindingCategory[],
path: string[], path: readonly string[],
): FindingNode | undefined { ): TreeNode | undefined {
let nodes: FindingNode[] = categories let nodes: readonly TreeNode[] = categories
let node: FindingNode | undefined let node: TreeNode | undefined
for (const segment of path) { for (const segment of path) {
node = nodes.find((n) => n.id === segment) node = nodes.find((n) => n.id === segment)
if (!node) return undefined if (!node) return undefined
nodes = node.children ?? [] nodes = node.children
} }
return node return node
} }
function descriptionOf(node: TreeNode, locale: Locale): string | undefined {
const text: LocalizedOptionalText | undefined = node.description
if (!text) return undefined
return (
(locale === 'en' ? text.en || text.fr : text.fr || text.en) || undefined
)
}
/**
* Drill-down picker over one finding zone of the sheet. A finding is keyed
* by `(findingZoneId, path, side)`; labels are snapshotted at selection.
*/
export default function FindingsTreePicker({ export default function FindingsTreePicker({
zoneId, zone,
tree,
side, side,
selected, selected,
onChange, onChange,
}: FindingsTreePickerProps) { }: FindingsTreePickerProps) {
const t = useT() const t = useT()
const locale = useLocaleStore((s) => s.locale) const locale = useLocaleStore((s) => s.locale)
const nameOf = (node: { name_fr: string; name_en: string }) =>
locale === 'en' ? node.name_en : node.name_fr
const descOf = (node: { description_fr?: string; description_en?: string }) =>
locale === 'en' ? node.description_en : node.description_fr
const [path, setPath] = useState<string[]>([]) const [path, setPath] = useState<string[]>([])
const [direction, setDirection] = useState<1 | -1>(1) const [direction, setDirection] = useState<1 | -1>(1)
@@ -86,74 +95,57 @@ export default function FindingsTreePicker({
setPath(path.slice(0, depth)) setPath(path.slice(0, depth))
} }
const currentNodes = useMemo<FindingNode[]>(() => { const currentNodes = useMemo<readonly TreeNode[]>(() => {
if (path.length === 0) return tree.categories if (path.length === 0) return zone.categories
const node = findNode(tree.categories, path) return findNode(zone.categories, path)?.children ?? []
return node?.children ?? [] }, [zone, path])
}, [tree, path])
const focusedNode = useMemo( const focusedNode = useMemo(
() => (path.length === 0 ? undefined : findNode(tree.categories, path)), () => (path.length === 0 ? undefined : findNode(zone.categories, path)),
[tree, path], [zone, path],
) )
const breadcrumb = useMemo<{ label: string; depth: number }[]>(() => { const breadcrumb = useMemo<{ label: string; depth: number }[]>(() => {
const pick = (z: { name_fr: string; name_en: string }) => const crumbs = [{ label: pickLabel(zone.name, locale), depth: 0 }]
locale === 'en' ? z.name_en : z.name_fr let nodes: readonly TreeNode[] = zone.categories
const crumbs: { label: string; depth: number }[] = [
{ label: pick(tree), depth: 0 },
]
let nodes: FindingNode[] = tree.categories
path.forEach((seg, i) => { path.forEach((seg, i) => {
const n = nodes.find((x) => x.id === seg) const n = nodes.find((x) => x.id === seg)
if (n) { if (n) {
crumbs.push({ label: pick(n), depth: i + 1 }) crumbs.push({ label: pickLabel(n.name, locale), depth: i + 1 })
nodes = n.children ?? [] nodes = n.children
} }
}) })
return crumbs return crumbs
}, [tree, path, locale]) }, [zone, path, locale])
function matchesSide(f: Finding): boolean { const matches = (f: Finding) => f.findingZoneId === zone.id && f.side === side
return f.zoneId === zoneId && f.side === side const isLeafSelected = (leafPath: string[]) =>
} selected.some((f) => matches(f) && samePath(f.path, leafPath))
const countSelectedUnder = (nodePath: string[]) =>
selected.filter((f) => matches(f) && pathStartsWith(f.path, nodePath))
.length
function isLeafSelected(leafPath: string[]): boolean { function toggleLeaf(leafPath: string[], leaf: TreeNode) {
return selected.some(
(f) => matchesSide(f) && samePath(f.path, leafPath),
)
}
function countSelectedUnder(nodePath: string[]): number {
let n = 0
for (const f of selected) {
if (!matchesSide(f)) continue
if (!pathStartsWith(f.path, nodePath)) continue
n += 1
}
return n
}
function toggleLeaf(leafPath: string[], leaf: FindingNode) {
if (isLeafSelected(leafPath)) { if (isLeafSelected(leafPath)) {
onChange( onChange(
selected.filter( selected.filter((f) => !(matches(f) && samePath(f.path, leafPath))),
(f) => !(matchesSide(f) && samePath(f.path, leafPath)),
),
) )
return return
} }
const next: Finding = { const next: Finding = {
zoneId, findingZoneId: zone.id,
path: leafPath, path: leafPath,
labelFrSnapshot: leaf.name_fr, labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name_en, labelEnSnapshot: leaf.name.en,
} }
if (leaf.requires_vet_referral) next.requiresVetReferral = true if ('requires_vet_referral' in leaf && leaf.requires_vet_referral)
next.requiresVetReferral = true
if (side) next.side = side if (side) next.side = side
onChange([...selected, next]) onChange([...selected, next])
} }
const focusedDescription = focusedNode && descriptionOf(focusedNode, locale)
return ( return (
<div className="space-y-2"> <div className="space-y-2">
<div className="flex flex-wrap items-center gap-1 text-xs text-[var(--color-ink-muted)]"> <div className="flex flex-wrap items-center gap-1 text-xs text-[var(--color-ink-muted)]">
@@ -179,9 +171,9 @@ export default function FindingsTreePicker({
})} })}
</div> </div>
{focusedNode && descOf(focusedNode) && ( {focusedDescription && (
<p className="text-xs italic text-[var(--color-ink-muted)]"> <p className="text-xs italic text-[var(--color-ink-muted)]">
{descOf(focusedNode)} {focusedDescription}
</p> </p>
)} )}
@@ -203,7 +195,6 @@ export default function FindingsTreePicker({
initial="enter" initial="enter"
animate="center" animate="center"
transition={{ duration: 0.22, ease: 'easeOut' }} transition={{ duration: 0.22, ease: 'easeOut' }}
style={{ willChange: 'transform, opacity' }}
className="space-y-1.5 max-h-64 overflow-auto pr-1" className="space-y-1.5 max-h-64 overflow-auto pr-1"
> >
{currentNodes.length === 0 ? ( {currentNodes.length === 0 ? (
@@ -213,16 +204,17 @@ export default function FindingsTreePicker({
) : ( ) : (
currentNodes.map((node) => { currentNodes.map((node) => {
const nodePath = [...path, node.id] const nodePath = [...path, node.id]
const nodeLabel = pickLabel(node.name, locale)
const nodeDesc = descriptionOf(node, locale)
if (isLeaf(node)) { if (isLeaf(node)) {
const checked = isLeafSelected(nodePath) const vet =
const nodeLabel = nameOf(node) 'requires_vet_referral' in node && node.requires_vet_referral
const nodeDesc = descOf(node)
return ( return (
<li key={node.id}> <li key={node.id}>
<label className="flex items-start gap-2 cursor-pointer"> <label className="flex items-start gap-2 cursor-pointer">
<input <input
type="checkbox" type="checkbox"
checked={checked} checked={isLeafSelected(nodePath)}
onChange={() => toggleLeaf(nodePath, node)} onChange={() => toggleLeaf(nodePath, node)}
className="mt-1 accent-[var(--color-accent)]" className="mt-1 accent-[var(--color-accent)]"
aria-label={nodeLabel} aria-label={nodeLabel}
@@ -232,7 +224,7 @@ export default function FindingsTreePicker({
<span className="text-sm font-medium text-[var(--color-ink)]"> <span className="text-sm font-medium text-[var(--color-ink)]">
{nodeLabel} {nodeLabel}
</span> </span>
{node.requires_vet_referral && ( {vet && (
<span <span
title={t('findings.vet_referral')} title={t('findings.vet_referral')}
aria-label={t('findings.vet_referral')} aria-label={t('findings.vet_referral')}
@@ -253,7 +245,6 @@ export default function FindingsTreePicker({
) )
} }
const selectedCount = countSelectedUnder(nodePath) const selectedCount = countSelectedUnder(nodePath)
const nodeLabel = nameOf(node)
const selectedAria = `${selectedCount} ${ const selectedAria = `${selectedCount} ${
selectedCount > 1 selectedCount > 1
? t('findings.selected_plural') ? t('findings.selected_plural')
@@ -278,7 +269,10 @@ export default function FindingsTreePicker({
</span> </span>
)} )}
</span> </span>
<span aria-hidden="true" className="text-[var(--color-ink-muted)]"> <span
aria-hidden="true"
className="text-[var(--color-ink-muted)]"
>
› ›
</span> </span>
</button> </button>
@@ -1,6 +1,6 @@
import Dialog from '@/components/ui/Dialog' import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import type { LateralSide } from '@/domain/schema/observation' import type { LateralSide } from '@faunosteo/domain'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
export interface LateralityPickerProps { export interface LateralityPickerProps {
@@ -1,16 +1,11 @@
import { useMemo, useState } from 'react' import { useMemo, useState } from 'react'
import type { import type {
Observation, Finding,
ObservationZone, FindingZone,
Vertebra,
LateralSide, LateralSide,
} from '@/domain/schema/observation' Observation,
import type { ReportZone,
SpeciesFindings, } from '@faunosteo/domain'
ZoneFindings,
} from '@/domain/schema/findings'
import type { Bone } from '@/anatomy/types'
import { matchZoneFindings } from '@/lib/zoneMatch'
import { AnimatePresence, motion } from 'motion/react' import { AnimatePresence, motion } from 'motion/react'
import Card from '@/components/ui/Card' import Card from '@/components/ui/Card'
import Badge from '@/components/ui/Badge' import Badge from '@/components/ui/Badge'
@@ -20,9 +15,9 @@ import Textarea from '@/components/ui/Textarea'
import FindingsTreePicker from './FindingsTreePicker' import FindingsTreePicker from './FindingsTreePicker'
import FreeTextFindingInput from './FreeTextFindingInput' import FreeTextFindingInput from './FreeTextFindingInput'
import SeveritySelector from './SeveritySelector' import SeveritySelector from './SeveritySelector'
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import { boneLabel } from '@/anatomy/labels'
import type { Locale } from '@/i18n/types' import type { Locale } from '@/i18n/types'
export interface ObservationCardProps { export interface ObservationCardProps {
@@ -36,35 +31,75 @@ export interface ObservationCardProps {
canMoveUp: boolean canMoveUp: boolean
canMoveDown: boolean canMoveDown: boolean
// Editor body props (used only when expanded) // Editor body props (used only when expanded)
bones: Map<string, Bone> sheet: SheetIndex
findings: SpeciesFindings | null
onChange: (next: Observation) => void onChange: (next: Observation) => void
onOpenVertebraPicker: (zoneIndex: number) => void onOpenVertebraPicker: (zoneIndex: number) => void
onRemoveZone: (zoneIndex: number) => void onRemoveZone: (zoneIndex: number) => void
} }
/** Zone label: the sheet's current name, else the snapshot, else the id. */
export function zoneLabel(
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const annotation = sheet.annotation(z.annotationId)
if (annotation) return pickLabel(sheet.name(annotation), locale)
const snapshot =
locale === 'en'
? z.labelEnSnapshot || z.labelFrSnapshot
: z.labelFrSnapshot || z.labelEnSnapshot
return snapshot || z.annotationId
}
function describeZone( function describeZone(
z: ObservationZone, z: ReportZone,
bones: Map<string, Bone>, sheet: SheetIndex,
locale: Locale, locale: Locale,
t: (key: string) => string, t: (key: string) => string,
): string { ): string {
const label = boneLabel(bones.get(z.boneId), locale, z.boneId) const label = zoneLabel(z, sheet, locale)
if (z.vertebrae?.length) { if (z.vertebrae?.length) {
const vs = z.vertebrae return `${label} (${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')})`
.map((v: Vertebra) => `${v.region}${v.index}`)
.join(', ')
return `${label} (${vs})`
} }
if (z.side) { if (z.side) {
const sideLabel = t( return `${label} (${t(z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`
z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short',
)
return `${label} (${sideLabel})`
} }
return label return label
} }
interface ZoneTree {
zone: FindingZone
side?: LateralSide
}
/** One picker per (finding zone, side) the observation's zones resolve to. */
function zoneTrees(observation: Observation, sheet: SheetIndex): ZoneTree[] {
const seen = new Set<string>()
const out: ZoneTree[] = []
for (const z of observation.zones) {
const annotation = sheet.annotation(z.annotationId)
if (!isObservable(annotation) || !annotation.finding_zone_id) continue
const zone = sheet.findingZone(annotation.finding_zone_id)
if (!zone) continue
const key = z.side ? `${zone.id}:${z.side}` : zone.id
if (seen.has(key)) continue
seen.add(key)
out.push({ zone, side: z.side })
}
return out
}
/** Findings the sheet no longer holds at their path (migrated data, kept verbatim). */
function unresolvedFindings(
observation: Observation,
sheet: SheetIndex,
): Finding[] {
return observation.findings.filter(
(f) => !sheet.nodeAt(f.findingZoneId, f.path),
)
}
export default function ObservationCard({ export default function ObservationCard({
observation, observation,
index, index,
@@ -75,34 +110,37 @@ export default function ObservationCard({
onMoveDown, onMoveDown,
canMoveUp, canMoveUp,
canMoveDown, canMoveDown,
bones, sheet,
findings,
onChange, onChange,
onOpenVertebraPicker, onOpenVertebraPicker,
onRemoveZone, onRemoveZone,
}: ObservationCardProps) { }: ObservationCardProps) {
const t = useT() const t = useT()
const locale = useLocaleStore((s) => s.locale) const locale = useLocaleStore((s) => s.locale)
const nameOf = (z: { name_fr: string; name_en: string }) =>
locale === 'en' ? z.name_en : z.name_fr
// Per-zone picker accordion — only one tree picker open at a time,
// matching the observation-card accordion semantics. Closed by default
// so the card stays compact when first expanded.
const [expandedZoneId, setExpandedZoneId] = useState<string | null>(null) const [expandedZoneId, setExpandedZoneId] = useState<string | null>(null)
const zoneCount = observation.zones.length const zoneCount = observation.zones.length
const findingCount = const findingCount =
observation.findings.length + observation.freeTextFindings.length observation.findings.length + observation.freeTextFindings.length
const zoneCountLabel = t(
const zoneCountLabel =
zoneCount > 1 zoneCount > 1
? t('observation.zone_label_plural') ? 'observation.zone_label_plural'
: t('observation.zone_label_singular') : 'observation.zone_label_singular',
const findingCountLabel = )
const findingCountLabel = t(
findingCount > 1 findingCount > 1
? t('observation.finding_label_plural') ? 'observation.finding_label_plural'
: t('observation.finding_label_singular') : 'observation.finding_label_singular',
)
const trees = useMemo(
() => zoneTrees(observation, sheet),
[observation, sheet],
)
const unresolved = useMemo(
() => unresolvedFindings(observation, sheet),
[observation, sheet],
)
function onHeaderKey(event: React.KeyboardEvent<HTMLDivElement>) { function onHeaderKey(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Enter' || event.key === ' ') { if (event.key === 'Enter' || event.key === ' ') {
@@ -110,39 +148,15 @@ export default function ObservationCard({
onToggle() onToggle()
} }
} }
const stop = (fn: () => void) => (event: React.MouseEvent) => {
function stop(fn: () => void) {
return (event: React.MouseEvent) => {
event.stopPropagation() event.stopPropagation()
fn() fn()
} }
} const removeFinding = (target: Finding) =>
onChange({
const zonesArray = useMemo( ...observation,
() => (findings ? Object.values(findings.zones) : []), findings: observation.findings.filter((f) => f !== target),
[findings], })
)
const zonesWithTree = useMemo(() => {
if (zonesArray.length === 0)
return [] as { tree: ZoneFindings; side?: LateralSide }[]
const seen = new Set<string>()
const out: { tree: ZoneFindings; side?: LateralSide }[] = []
for (const z of observation.zones) {
const bone = bones.get(z.boneId)
if (!bone) continue
const tree = matchZoneFindings(
{ fr: bone.fr, en: bone.en },
zonesArray,
)
if (!tree) continue
const key = z.side ? `${tree.id}:${z.side}` : tree.id
if (seen.has(key)) continue
seen.add(key)
out.push({ tree, side: z.side })
}
return out
}, [observation.zones, bones, zonesArray])
return ( return (
<Card <Card
@@ -164,13 +178,16 @@ export default function ObservationCard({
> >
<div className="flex-1 min-h-[60px] text-left"> <div className="flex-1 min-h-[60px] text-left">
<div className="flex items-center gap-2 mb-2"> <div className="flex items-center gap-2 mb-2">
<Badge tone="neutral">{t('observation.badge_n')}{index + 1}</Badge> <Badge tone="neutral">
{t('observation.badge_n')}
{index + 1}
</Badge>
{observation.severity && ( {observation.severity && (
<Badge <Badge
tone={ tone={
observation.severity === 'sévère' observation.severity === 'severe'
? 'danger' ? 'danger'
: observation.severity === 'modérée' : observation.severity === 'moderate'
? 'warn' ? 'warn'
: 'neutral' : 'neutral'
} }
@@ -248,15 +265,22 @@ export default function ObservationCard({
</p> </p>
) : ( ) : (
<ul className="flex flex-wrap gap-2"> <ul className="flex flex-wrap gap-2">
{observation.zones.map((z, i) => { {observation.zones.map((z, i) => (
const b = bones.get(z.boneId) <li
const supportsVertebrae = key={`${z.annotationId}-${z.viewId}-${z.side ?? ''}-${i}`}
b?.special === 'vertebral-precision' >
return (
<li key={`${z.boneId}-${i}`}>
<Badge tone="accent" className="gap-2"> <Badge tone="accent" className="gap-2">
{describeZone(z, bones, locale, t)} {describeZone(z, sheet, locale, t)}
{supportsVertebrae && ( {z.unresolved &&
!sheet.annotation(z.annotationId) && (
<span
className="text-xs italic"
title={t('observation.zone_unresolved')}
>
{t('observation.unresolved_short')}
</span>
)}
{sheet.isSpine(z.annotationId) && (
<button <button
type="button" type="button"
onClick={() => onOpenVertebraPicker(i)} onClick={() => onOpenVertebraPicker(i)}
@@ -268,7 +292,7 @@ export default function ObservationCard({
)} )}
<button <button
type="button" type="button"
aria-label={`${t('observation.remove_zone')} ${boneLabel(b, locale, z.boneId)}`} aria-label={`${t('observation.remove_zone')} ${zoneLabel(z, sheet, locale)}`}
onClick={() => onRemoveZone(i)} onClick={() => onRemoveZone(i)}
className="ml-1 text-[var(--color-accent-strong)]" className="ml-1 text-[var(--color-accent-strong)]"
> >
@@ -276,15 +300,14 @@ export default function ObservationCard({
</button> </button>
</Badge> </Badge>
</li> </li>
) ))}
})}
</ul> </ul>
)} )}
</section> </section>
<section> <section>
<Label>{t('observation.findings_catalog_label')}</Label> <Label>{t('observation.findings_catalog_label')}</Label>
{zonesWithTree.length === 0 ? ( {trees.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]"> <p className="text-sm text-[var(--color-ink-muted)]">
{observation.zones.length === 0 {observation.zones.length === 0
? t('observation.findings_pick_zone_first') ? t('observation.findings_pick_zone_first')
@@ -292,26 +315,19 @@ export default function ObservationCard({
</p> </p>
) : ( ) : (
<ul className="space-y-2"> <ul className="space-y-2">
{zonesWithTree.map(({ tree, side }) => { {trees.map(({ zone, side }) => {
const pickerKey = side const pickerKey = side ? `${zone.id}:${side}` : zone.id
? `${tree.id}:${side}` const open = expandedZoneId === pickerKey
: tree.id
const expanded = expandedZoneId === pickerKey
const selectedCount = observation.findings.filter( const selectedCount = observation.findings.filter(
(f) => (f) => f.findingZoneId === zone.id && f.side === side,
f.zoneId === tree.id && f.side === side,
).length ).length
const selectedAria = `${selectedCount} ${ const selectedAria = `${selectedCount} ${selectedCount > 1 ? t('findings.selected_plural') : t('findings.selected_singular')}`
selectedCount > 1
? t('findings.selected_plural')
: t('findings.selected_singular')
}`
return ( return (
<li <li
key={pickerKey} key={pickerKey}
className={[ className={[
'rounded-xl border bg-[var(--color-surface)] transition', 'rounded-xl border bg-[var(--color-surface)] transition',
expanded open
? 'border-[var(--color-accent)] ring-1 ring-[var(--color-accent)]' ? 'border-[var(--color-accent)] ring-1 ring-[var(--color-accent)]'
: 'border-[var(--color-border)]', : 'border-[var(--color-border)]',
].join(' ')} ].join(' ')}
@@ -319,16 +335,17 @@ export default function ObservationCard({
<button <button
type="button" type="button"
onClick={() => onClick={() =>
setExpandedZoneId(expanded ? null : pickerKey) setExpandedZoneId(open ? null : pickerKey)
} }
aria-expanded={expanded} aria-expanded={open}
aria-controls={`findings-zone-${pickerKey}`} aria-controls={`findings-zone-${pickerKey}`}
className="w-full flex items-center justify-between gap-2 px-3 py-2 text-left rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40" className="w-full flex items-center justify-between gap-2 px-3 py-2 text-left rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40"
> >
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
<span className="text-sm font-medium text-[var(--color-ink)]"> <span className="text-sm font-medium text-[var(--color-ink)]">
{nameOf(tree)} {pickLabel(zone.name, locale)}
{side && ` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`} {side &&
` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`}
</span> </span>
{selectedCount > 0 && ( {selectedCount > 0 && (
<span <span
@@ -343,11 +360,11 @@ export default function ObservationCard({
aria-hidden="true" aria-hidden="true"
className="text-[var(--color-ink-muted)]" className="text-[var(--color-ink-muted)]"
> >
{expanded ? '▲' : '▼'} {open ? '▲' : '▼'}
</span> </span>
</button> </button>
<AnimatePresence initial={false}> <AnimatePresence initial={false}>
{expanded && ( {open && (
<motion.div <motion.div
key="picker-body" key="picker-body"
id={`findings-zone-${pickerKey}`} id={`findings-zone-${pickerKey}`}
@@ -359,12 +376,14 @@ export default function ObservationCard({
> >
<div className="px-3 pb-3 pt-1 border-t border-[var(--color-border)]"> <div className="px-3 pb-3 pt-1 border-t border-[var(--color-border)]">
<FindingsTreePicker <FindingsTreePicker
zoneId={tree.id} zone={zone}
tree={tree}
side={side} side={side}
selected={observation.findings} selected={observation.findings}
onChange={(next) => onChange={(next) =>
onChange({ ...observation, findings: next }) onChange({
...observation,
findings: next,
})
} }
/> />
</div> </div>
@@ -378,6 +397,40 @@ export default function ObservationCard({
)} )}
</section> </section>
{unresolved.length > 0 && (
<section>
<Label>{t('observation.findings_unresolved_label')}</Label>
<p className="text-xs text-[var(--color-ink-muted)] mb-2">
{t('observation.findings_unresolved_help')}
</p>
<ul className="space-y-1">
{unresolved.map((f, i) => (
<li
key={`${f.findingZoneId}-${f.path.join('/')}-${f.side ?? ''}-${i}`}
className="flex items-center gap-2 text-sm"
>
<span className="text-[var(--color-ink)]">
{f.requiresVetReferral ? '⚠ ' : ''}
{locale === 'en'
? f.labelEnSnapshot
: f.labelFrSnapshot}
{f.side &&
` (${t(f.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`}
</span>
<button
type="button"
aria-label={`${t('common.delete')} ${locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot}`}
onClick={() => removeFinding(f)}
className="text-[var(--color-accent-strong)]"
>
✕
</button>
</li>
))}
</ul>
</section>
)}
<section> <section>
<Label>{t('observation.findings_free_label')}</Label> <Label>{t('observation.findings_free_label')}</Label>
<FreeTextFindingInput <FreeTextFindingInput
@@ -1,8 +1,7 @@
import type { Observation } from '@/domain/schema/observation' import type { Observation } from '@faunosteo/domain'
import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Bone } from '@/anatomy/types'
import ObservationCard from './ObservationCard' import ObservationCard from './ObservationCard'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import type { SheetIndex } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
export interface ObservationListProps { export interface ObservationListProps {
@@ -14,8 +13,7 @@ export interface ObservationListProps {
onMoveUp: (i: number) => void onMoveUp: (i: number) => void
onMoveDown: (i: number) => void onMoveDown: (i: number) => void
// Editor body props forwarded to each card // Editor body props forwarded to each card
bones: Map<string, Bone> sheet: SheetIndex
findings: SpeciesFindings | null
onChange: (i: number, next: Observation) => void onChange: (i: number, next: Observation) => void
onOpenVertebraPicker: (i: number, zoneIndex: number) => void onOpenVertebraPicker: (i: number, zoneIndex: number) => void
onRemoveZone: (i: number, zoneIndex: number) => void onRemoveZone: (i: number, zoneIndex: number) => void
@@ -29,8 +27,7 @@ export default function ObservationList({
onDelete, onDelete,
onMoveUp, onMoveUp,
onMoveDown, onMoveDown,
bones, sheet,
findings,
onChange, onChange,
onOpenVertebraPicker, onOpenVertebraPicker,
onRemoveZone, onRemoveZone,
@@ -64,8 +61,7 @@ export default function ObservationList({
onMoveDown={() => onMoveDown(i)} onMoveDown={() => onMoveDown(i)}
canMoveUp={i > 0} canMoveUp={i > 0}
canMoveDown={i < observations.length - 1} canMoveDown={i < observations.length - 1}
bones={bones} sheet={sheet}
findings={findings}
onChange={(next) => onChange(i, next)} onChange={(next) => onChange(i, next)}
onOpenVertebraPicker={(zoneIndex) => onOpenVertebraPicker={(zoneIndex) =>
onOpenVertebraPicker(i, zoneIndex) onOpenVertebraPicker(i, zoneIndex)
@@ -0,0 +1,95 @@
import type { LateralSide, Observation } from '@faunosteo/domain'
import VertebraPicker from '@/components/observation/VertebraPicker'
import LateralityPicker from '@/components/observation/LateralityPicker'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
import {
addSides,
collectVertebrae,
sidesPresent,
syncVertebrae,
type ZoneRef,
} from '@/services/zoneInteraction'
import { useT } from '@/i18n/useT'
export interface ObservationPickersProps {
sheet: SheetIndex
activeIndex: number
activeObs: Observation | undefined
vertebraTarget: number | null
lateralTarget: ZoneRef | null
onCloseVertebra: () => void
onCloseLateral: () => void
}
/** Vertebra and laterality pickers of the active observation. */
export default function ObservationPickers({
sheet,
activeIndex,
activeObs,
vertebraTarget,
lateralTarget,
onCloseVertebra,
onCloseLateral,
}: ObservationPickersProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const updateObservation = useReportStore((s) => s.updateObservation)
const vertebraZone =
vertebraTarget !== null ? activeObs?.zones[vertebraTarget] : undefined
const vertebraAnnotation =
vertebraZone && sheet.annotation(vertebraZone.annotationId)
const lateralAnnotation =
lateralTarget && sheet.annotation(lateralTarget.annotationId)
return (
<>
{vertebraTarget !== null &&
activeObs &&
vertebraZone &&
isObservable(vertebraAnnotation) && (
<VertebraPicker
open
onClose={onCloseVertebra}
onConfirm={(vertebrae) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (fresh) {
updateObservation(
activeIndex,
syncVertebrae(fresh, vertebrae, sheet, vertebraZone.viewId),
)
}
onCloseVertebra()
}}
initial={collectVertebrae(activeObs, sheet, vertebraTarget)}
regions={sheet.regions()}
title={`${t('vertebra.title_prefix')}${pickLabel(vertebraAnnotation.name, locale)}`}
initialRegion={
vertebraAnnotation.vertebral_region_code ?? undefined
}
/>
)}
{lateralTarget && activeObs && lateralAnnotation && (
<LateralityPicker
open
onClose={onCloseLateral}
title={pickLabel(sheet.name(lateralAnnotation), locale)}
existingSides={sidesPresent(activeObs, lateralTarget)}
onSelect={(sides: LateralSide[]) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (fresh)
updateObservation(
activeIndex,
addSides(fresh, lateralAnnotation, sides),
)
onCloseLateral()
}}
/>
)}
</>
)
}
@@ -1,4 +1,4 @@
import type { Severity } from '@/domain/schema/observation' import type { Severity } from '@faunosteo/domain'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
export interface SeveritySelectorProps { export interface SeveritySelectorProps {
@@ -6,17 +6,25 @@ export interface SeveritySelectorProps {
onChange: (s: Severity | undefined) => void onChange: (s: Severity | undefined) => void
} }
const SEVERITIES: Severity[] = ['légère', 'modérée', 'sévère'] export const SEVERITIES: Severity[] = ['mild', 'moderate', 'severe']
const COLORS: Record<Severity, string> = { const COLORS: Record<Severity, string> = {
'légère': 'border-[var(--severity-mild)] text-[var(--severity-mild)]', mild: 'border-[var(--severity-mild)] text-[var(--severity-mild)]',
'modérée': 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]', moderate: 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]',
'sévère': 'border-[var(--severity-severe)] text-[var(--severity-severe)]', severe: 'border-[var(--severity-severe)] text-[var(--severity-severe)]',
} }
export default function SeveritySelector({ value, onChange }: SeveritySelectorProps) { /** Severity codes are persisted; labels come from the dictionary (D8). */
export default function SeveritySelector({
value,
onChange,
}: SeveritySelectorProps) {
const t = useT() const t = useT()
return ( return (
<div role="radiogroup" aria-label={t('severity.aria')} className="flex gap-2"> <div
role="radiogroup"
aria-label={t('severity.aria')}
className="flex gap-2"
>
{SEVERITIES.map((s) => ( {SEVERITIES.map((s) => (
<button <button
key={s} key={s}
@@ -1,86 +1,93 @@
import { useState } from 'react' import { useState } from 'react'
import type { Vertebra, VertebralRegion } from '@faunosteo/domain'
import Dialog from '@/components/ui/Dialog' import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Chip from '@/components/ui/Chip' import Chip from '@/components/ui/Chip'
import type { Vertebra, VertebralRegion } from '@/domain/schema/observation' import { pickLabel } from '@/services/sheetIndex'
import type { VertebralFormula } from '@/domain/species/types'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
const REGIONS: VertebralRegion[] = ['C', 'T', 'L', 'S', 'Cd']
const REGION_KEY: Record<VertebralRegion, string> = {
C: 'vertebra.region.C',
T: 'vertebra.region.T',
L: 'vertebra.region.L',
S: 'vertebra.region.S',
Cd: 'vertebra.region.Cd',
}
export interface VertebraPickerProps { export interface VertebraPickerProps {
open: boolean open: boolean
onClose: () => void onClose: () => void
onConfirm: (vertebrae: Vertebra[]) => void onConfirm: (vertebrae: Vertebra[]) => void
initial: Vertebra[] initial: Vertebra[]
formula: VertebralFormula /** Ordered regions of the sheet (`vertebral_config.regions`). */
regions: readonly VertebralRegion[]
title: string title: string
/** Tab to open on. Takes priority so a click always lands on its own zone. */ /** Tab to open on. Takes priority so a click always lands on its own zone. */
initialRegion?: VertebralRegion initialRegion?: string
} }
const sameVertebra = (a: Vertebra, r: string, i: number) =>
a.region === r && a.index === i
/**
* Picks vertebrae across every region of the sheet. A region shows its
* usual count; when the sheet documents a wider range (D6), one control
* extends the grid to the documented maximum. Nothing horse-specific here.
*/
export default function VertebraPicker({ export default function VertebraPicker({
open, open,
onClose, onClose,
onConfirm, onConfirm,
initial, initial,
formula, regions,
title, title,
initialRegion, initialRegion,
}: VertebraPickerProps) { }: VertebraPickerProps) {
const t = useT() const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [selected, setSelected] = useState<Vertebra[]>(initial) const [selected, setSelected] = useState<Vertebra[]>(initial)
const [activeRegion, setActiveRegion] = useState<VertebralRegion>( const [activeCode, setActiveCode] = useState<string>(
() => initialRegion ?? initial[0]?.region ?? 'C', () => initialRegion ?? initial[0]?.region ?? regions[0]?.code ?? '',
) )
const [extended, setExtended] = useState<Set<string>>(() => new Set())
const has = (r: VertebralRegion, i: number) => const active = regions.find((r) => r.code === activeCode) ?? regions[0]
selected.some((v) => v.region === r && v.index === i) if (!active) return null
const maxCount = active.count_range?.max ?? active.count
const highestPicked = Math.max(
0,
...selected.filter((v) => v.region === active.code).map((v) => v.index),
)
const canExtend = maxCount > active.count
const showExtended = extended.has(active.code) || highestPicked > active.count
const count = showExtended ? maxCount : active.count
const toggle = (r: VertebralRegion, i: number) => { const has = (r: string, i: number) =>
selected.some((v) => sameVertebra(v, r, i))
const toggle = (r: string, i: number) =>
setSelected((cur) => setSelected((cur) =>
has(r, i) has(r, i)
? cur.filter((v) => !(v.region === r && v.index === i)) ? cur.filter((v) => !sameVertebra(v, r, i))
: [...cur, { region: r, index: i }], : [...cur, { region: r, index: i }],
) )
} const all = (r: string, n: number) =>
setSelected((cur) => [
const all = (r: VertebralRegion, count: number) => { ...cur.filter((v) => v.region !== r),
setSelected((cur) => { ...Array.from({ length: n }, (_, k) => ({ region: r, index: k + 1 })),
const rest = cur.filter((v) => v.region !== r) ])
return [...rest, ...Array.from({ length: count }, (_, k) => ({ region: r, index: k + 1 }))] const none = (r: string) =>
})
}
const none = (r: VertebralRegion) =>
setSelected((cur) => cur.filter((v) => v.region !== r)) setSelected((cur) => cur.filter((v) => v.region !== r))
const count = formula[activeRegion]
return ( return (
<Dialog open={open} onClose={onClose} title={title} size="lg"> <Dialog open={open} onClose={onClose} title={title} size="lg">
<div role="tablist" className="flex flex-wrap gap-2 mb-4"> <div role="tablist" className="flex flex-wrap gap-2 mb-4">
{REGIONS.map((r) => ( {regions.map((r) => (
<button <button
key={r} key={r.code}
role="tab" role="tab"
aria-selected={activeRegion === r} aria-selected={active.code === r.code}
onClick={() => setActiveRegion(r)} onClick={() => setActiveCode(r.code)}
className={[ className={[
'rounded-full px-4 py-2.5 sm:py-1.5 text-sm font-medium border min-h-[2.75rem]', 'rounded-full px-4 py-2.5 sm:py-1.5 text-sm font-medium border min-h-[2.75rem]',
activeRegion === r active.code === r.code
? 'bg-[var(--color-accent)] text-white border-[var(--color-accent)]' ? 'bg-[var(--color-accent)] text-white border-[var(--color-accent)]'
: 'bg-white text-[var(--color-ink)] border-[var(--color-border)]', : 'bg-white text-[var(--color-ink)] border-[var(--color-border)]',
].join(' ')} ].join(' ')}
> >
{t(REGION_KEY[r])} {pickLabel(r.name, locale)}
</button> </button>
))} ))}
</div> </div>
@@ -89,26 +96,52 @@ export default function VertebraPicker({
{Array.from({ length: count }, (_, k) => k + 1).map((i) => ( {Array.from({ length: count }, (_, k) => k + 1).map((i) => (
<Chip <Chip
key={i} key={i}
active={has(activeRegion, i)} active={has(active.code, i)}
onClick={() => toggle(activeRegion, i)} onClick={() => toggle(active.code, i)}
> >
{activeRegion}{i} {active.code}
{i}
</Chip> </Chip>
))} ))}
</div> </div>
<div className="flex flex-wrap items-center gap-2 mb-6"> <div className="flex flex-wrap items-center gap-2 mb-6">
<Button variant="ghost" size="sm" onClick={() => all(activeRegion, count)}> <Button
variant="ghost"
size="sm"
onClick={() => all(active.code, active.count)}
>
{t('vertebra.check_all')} {t('vertebra.check_all')}
</Button> </Button>
<Button variant="ghost" size="sm" onClick={() => none(activeRegion)}> <Button variant="ghost" size="sm" onClick={() => none(active.code)}>
{t('vertebra.uncheck_all')} {t('vertebra.uncheck_all')}
</Button> </Button>
{canExtend && !showExtended && (
<Button
variant="ghost"
size="sm"
onClick={() => setExtended((cur) => new Set(cur).add(active.code))}
>
{t('vertebra.extend_to').replace('{max}', String(maxCount))}
</Button>
)}
{canExtend && showExtended && (
<span className="text-xs text-[var(--color-ink-muted)]">
{t('vertebra.range_note')
.replace('{usual}', String(active.count))
.replace('{min}', String(active.count_range?.min ?? active.count))
.replace('{max}', String(maxCount))}
</span>
)}
</div> </div>
<div className="flex justify-end gap-2"> <div className="flex justify-end gap-2">
<Button variant="ghost" onClick={onClose}>{t('common.cancel')}</Button> <Button variant="ghost" onClick={onClose}>
<Button onClick={() => onConfirm(selected)}>{t('common.confirm')}</Button> {t('common.cancel')}
</Button>
<Button onClick={() => onConfirm(selected)}>
{t('common.confirm')}
</Button>
</div> </div>
</Dialog> </Dialog>
) )
+43 -10
View File
@@ -1,23 +1,36 @@
import type { Animal, Owner } from '@/domain/schema/animal' import type { Animal, LocalizedText, Owner } from '@faunosteo/domain'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import Select from '@/components/ui/Select' import Select from '@/components/ui/Select'
import { getAllSpecies, speciesLabel } from '@/domain/species/registry' import { pickLabel } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
export interface SpeciesOption {
id: string
name: LocalizedText
}
export interface AnimalFormProps { export interface AnimalFormProps {
animal: Animal animal: Animal
owner: Owner owner: Owner
/** Species that have a sheet in this build (one today). */
species: readonly SpeciesOption[]
onChangeAnimal: (next: Animal) => void onChangeAnimal: (next: Animal) => void
onChangeOwner: (next: Owner) => void onChangeOwner: (next: Owner) => void
} }
export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwner }: AnimalFormProps) { export default function AnimalForm({
animal,
owner,
species,
onChangeAnimal,
onChangeOwner,
}: AnimalFormProps) {
const t = useT() const t = useT()
const locale = useLocaleStore((s) => s.locale) const locale = useLocaleStore((s) => s.locale)
const species = getAllSpecies() const setA = (patch: Partial<Animal>) =>
const setA = (patch: Partial<Animal>) => onChangeAnimal({ ...animal, ...patch }) onChangeAnimal({ ...animal, ...patch })
return ( return (
<fieldset className="space-y-3"> <fieldset className="space-y-3">
<legend className="font-serif text-xl mb-2 text-[var(--color-ink)]"> <legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">
@@ -31,25 +44,45 @@ export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwne
onChange={(e) => setA({ speciesId: e.target.value })} onChange={(e) => setA({ speciesId: e.target.value })}
> >
{species.map((s) => ( {species.map((s) => (
<option key={s.id} value={s.id}>{speciesLabel(s, locale)}</option> <option key={s.id} value={s.id}>
{pickLabel(s.name, locale)}
</option>
))} ))}
</Select> </Select>
</div> </div>
<div> <div>
<Label htmlFor="an-name">{t('form.animal.name')}</Label> <Label htmlFor="an-name">{t('form.animal.name')}</Label>
<Input id="an-name" required value={animal.name} onChange={(e) => setA({ name: e.target.value })} /> <Input
id="an-name"
required
value={animal.name}
onChange={(e) => setA({ name: e.target.value })}
/>
</div> </div>
<div> <div>
<Label htmlFor="an-breed">{t('form.animal.breed')}</Label> <Label htmlFor="an-breed">{t('form.animal.breed')}</Label>
<Input id="an-breed" value={animal.breed ?? ''} onChange={(e) => setA({ breed: e.target.value || undefined })} /> <Input
id="an-breed"
value={animal.breed ?? ''}
onChange={(e) => setA({ breed: e.target.value || undefined })}
/>
</div> </div>
<div> <div>
<Label htmlFor="an-age">{t('form.animal.age')}</Label> <Label htmlFor="an-age">{t('form.animal.age')}</Label>
<Input id="an-age" value={animal.age ?? ''} onChange={(e) => setA({ age: e.target.value || undefined })} /> <Input
id="an-age"
value={animal.age ?? ''}
onChange={(e) => setA({ age: e.target.value || undefined })}
/>
</div> </div>
<div> <div>
<Label htmlFor="own-name">{t('form.owner.name')}</Label> <Label htmlFor="own-name">{t('form.owner.name')}</Label>
<Input id="own-name" required value={owner.name} onChange={(e) => onChangeOwner({ name: e.target.value })} /> <Input
id="own-name"
required
value={owner.name}
onChange={(e) => onChangeOwner({ name: e.target.value })}
/>
</div> </div>
</fieldset> </fieldset>
) )
@@ -1,4 +1,4 @@
import type { Report } from '@/domain/schema/report' import type { Report } from '@faunosteo/domain'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import Textarea from '@/components/ui/Textarea' import Textarea from '@/components/ui/Textarea'
import NextAppointmentPicker from './NextAppointmentPicker' import NextAppointmentPicker from './NextAppointmentPicker'
@@ -29,13 +29,26 @@ export default function ConclusionPanel({
</h2> </h2>
<div> <div>
<Label htmlFor="conclusion">{t('conclusion.conclusion')}</Label> <Label htmlFor="conclusion">{t('conclusion.conclusion')}</Label>
<Textarea id="conclusion" value={conclusion} onChange={(e) => onChangeConclusion(e.target.value)} /> <Textarea
id="conclusion"
value={conclusion}
onChange={(e) => onChangeConclusion(e.target.value)}
/>
</div> </div>
<div> <div>
<Label htmlFor="recommendations">{t('conclusion.recommendations')}</Label> <Label htmlFor="recommendations">
<Textarea id="recommendations" value={recommendations} onChange={(e) => onChangeRecommendations(e.target.value)} /> {t('conclusion.recommendations')}
</Label>
<Textarea
id="recommendations"
value={recommendations}
onChange={(e) => onChangeRecommendations(e.target.value)}
/>
</div> </div>
<NextAppointmentPicker value={nextAppointment} onChange={onChangeNextAppointment} /> <NextAppointmentPicker
value={nextAppointment}
onChange={onChangeNextAppointment}
/>
</section> </section>
) )
} }
@@ -0,0 +1,31 @@
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { useT } from '@/i18n/useT'
export interface DisclaimerDialogProps {
text: string
onAcknowledge: () => void
}
/** Scope disclaimer of the sheet, shown once per tab session. */
export default function DisclaimerDialog({
text,
onAcknowledge,
}: DisclaimerDialogProps) {
const t = useT()
return (
<Dialog
open
onClose={onAcknowledge}
title={t('editor.disclaimer_title')}
size="md"
>
<div className="space-y-4">
<p className="text-sm text-[var(--color-ink)]">{text}</p>
<div className="flex justify-end">
<Button onClick={onAcknowledge}>{t('common.understood')}</Button>
</div>
</div>
</Dialog>
)
}
@@ -0,0 +1,71 @@
import type { ComponentProps } from 'react'
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm'
import { useT } from '@/i18n/useT'
export interface Identity {
practitioner: Practitioner
animal: Animal
owner: Owner
}
export interface EditInfosDialogProps {
draft: Identity
species: ComponentProps<typeof AnimalForm>['species']
onChange: (next: Identity) => void
onCancel: () => void
onSave: () => void
}
/** The three names are mandatory to save the identity block. */
export function isIdentityComplete(identity: Identity): boolean {
return [
identity.practitioner.name,
identity.animal.name,
identity.owner.name,
].every((v) => v.trim())
}
/** Identity edit dialog of the editor: practitioner, animal and owner. */
export default function EditInfosDialog({
draft,
species,
onChange,
onCancel,
onSave,
}: EditInfosDialogProps) {
const t = useT()
return (
<Dialog
open
onClose={onCancel}
title={t('editor.edit_dialog_title')}
size="lg"
>
<div className="space-y-8">
<PractitionerForm
value={draft.practitioner}
onChange={(next) => onChange({ ...draft, practitioner: next })}
/>
<AnimalForm
animal={draft.animal}
owner={draft.owner}
species={species}
onChangeAnimal={(next) => onChange({ ...draft, animal: next })}
onChangeOwner={(next) => onChange({ ...draft, owner: next })}
/>
<div className="flex gap-3 justify-end pt-2 border-t border-[var(--color-border)]">
<Button variant="ghost" onClick={onCancel}>
{t('common.cancel')}
</Button>
<Button onClick={onSave} disabled={!isIdentityComplete(draft)}>
{t('common.save')}
</Button>
</div>
</div>
</Dialog>
)
}
@@ -1,4 +1,4 @@
import type { Report } from '@/domain/schema/report' import type { Report } from '@faunosteo/domain'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
@@ -1,4 +1,4 @@
import type { Practitioner } from '@/domain/schema/practitioner' import type { Practitioner } from '@faunosteo/domain'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
@@ -8,7 +8,10 @@ export interface PractitionerFormProps {
onChange: (next: Practitioner) => void onChange: (next: Practitioner) => void
} }
export default function PractitionerForm({ value, onChange }: PractitionerFormProps) { export default function PractitionerForm({
value,
onChange,
}: PractitionerFormProps) {
const t = useT() const t = useT()
const set = (patch: Partial<Practitioner>) => onChange({ ...value, ...patch }) const set = (patch: Partial<Practitioner>) => onChange({ ...value, ...patch })
return ( return (
@@ -18,19 +21,36 @@ export default function PractitionerForm({ value, onChange }: PractitionerFormPr
</legend> </legend>
<div> <div>
<Label htmlFor="prac-name">{t('form.practitioner.name')}</Label> <Label htmlFor="prac-name">{t('form.practitioner.name')}</Label>
<Input id="prac-name" required value={value.name} onChange={(e) => set({ name: e.target.value })} /> <Input
id="prac-name"
required
value={value.name}
onChange={(e) => set({ name: e.target.value })}
/>
</div> </div>
<div> <div>
<Label htmlFor="prac-cabinet">{t('form.practitioner.cabinet')}</Label> <Label htmlFor="prac-cabinet">{t('form.practitioner.cabinet')}</Label>
<Input id="prac-cabinet" value={value.cabinet ?? ''} onChange={(e) => set({ cabinet: e.target.value || undefined })} /> <Input
id="prac-cabinet"
value={value.cabinet ?? ''}
onChange={(e) => set({ cabinet: e.target.value || undefined })}
/>
</div> </div>
<div> <div>
<Label htmlFor="prac-contact">{t('form.practitioner.contact')}</Label> <Label htmlFor="prac-contact">{t('form.practitioner.contact')}</Label>
<Input id="prac-contact" value={value.contact ?? ''} onChange={(e) => set({ contact: e.target.value || undefined })} /> <Input
id="prac-contact"
value={value.contact ?? ''}
onChange={(e) => set({ contact: e.target.value || undefined })}
/>
</div> </div>
<div> <div>
<Label htmlFor="prac-siret">{t('form.practitioner.siret')}</Label> <Label htmlFor="prac-siret">{t('form.practitioner.siret')}</Label>
<Input id="prac-siret" value={value.siret ?? ''} onChange={(e) => set({ siret: e.target.value || undefined })} /> <Input
id="prac-siret"
value={value.siret ?? ''}
onChange={(e) => set({ siret: e.target.value || undefined })}
/>
</div> </div>
</fieldset> </fieldset>
) )
@@ -1,4 +1,4 @@
import type { Report } from '@/domain/schema/report' import type { Report } from '@faunosteo/domain'
import AppHeader from '@/components/brand/AppHeader' import AppHeader from '@/components/brand/AppHeader'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import { formatDate } from '@/lib/dates' import { formatDate } from '@/lib/dates'
@@ -10,7 +10,10 @@ export interface ReportHeaderProps {
onEditInfos?: () => void onEditInfos?: () => void
} }
export default function ReportHeader({ report, onEditInfos }: ReportHeaderProps) { export default function ReportHeader({
report,
onEditInfos,
}: ReportHeaderProps) {
const t = useT() const t = useT()
const locale = useLocaleStore((s) => s.locale) const locale = useLocaleStore((s) => s.locale)
return ( return (
+5 -1
View File
@@ -6,7 +6,11 @@ export interface CardProps {
as?: 'div' | 'section' | 'article' as?: 'div' | 'section' | 'article'
} }
export default function Card({ children, className = '', as: Tag = 'div' }: CardProps) { export default function Card({
children,
className = '',
as: Tag = 'div',
}: CardProps) {
return ( return (
<Tag <Tag
className={[ className={[
+4 -1
View File
@@ -5,7 +5,10 @@ export default function Chip({
children, children,
className = '', className = '',
...rest ...rest
}: ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean; children: ReactNode }) { }: ButtonHTMLAttributes<HTMLButtonElement> & {
active?: boolean
children: ReactNode
}) {
return ( return (
<button <button
type="button" type="button"
+10 -2
View File
@@ -17,7 +17,13 @@ const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
xl: 'max-w-4xl', xl: 'max-w-4xl',
} }
export default function Dialog({ open, onClose, title, children, size = 'md' }: DialogProps) { export default function Dialog({
open,
onClose,
title,
children,
size = 'md',
}: DialogProps) {
const t = useT() const t = useT()
useEffect(() => { useEffect(() => {
if (!open) return if (!open) return
@@ -50,7 +56,9 @@ export default function Dialog({ open, onClose, title, children, size = 'md' }:
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`} className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
> >
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]"> <header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
<h2 className="text-lg font-semibold text-[var(--color-ink)]">{title}</h2> <h2 className="text-lg font-semibold text-[var(--color-ink)]">
{title}
</h2>
<button <button
type="button" type="button"
aria-label={t('common.close')} aria-label={t('common.close')}
+5 -4
View File
@@ -1,7 +1,9 @@
import { forwardRef, type InputHTMLAttributes } from 'react' import { forwardRef, type InputHTMLAttributes } from 'react'
const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>( const Input = forwardRef<
({ className = '', ...rest }, ref) => ( HTMLInputElement,
InputHTMLAttributes<HTMLInputElement>
>(({ className = '', ...rest }, ref) => (
<input <input
ref={ref} ref={ref}
className={[ className={[
@@ -10,7 +12,6 @@ const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>
].join(' ')} ].join(' ')}
{...rest} {...rest}
/> />
), ))
)
Input.displayName = 'Input' Input.displayName = 'Input'
export default Input export default Input
+5 -4
View File
@@ -1,7 +1,9 @@
import { forwardRef, type SelectHTMLAttributes } from 'react' import { forwardRef, type SelectHTMLAttributes } from 'react'
const Select = forwardRef<HTMLSelectElement, SelectHTMLAttributes<HTMLSelectElement>>( const Select = forwardRef<
({ className = '', children, ...rest }, ref) => ( HTMLSelectElement,
SelectHTMLAttributes<HTMLSelectElement>
>(({ className = '', children, ...rest }, ref) => (
<select <select
ref={ref} ref={ref}
className={[ className={[
@@ -12,7 +14,6 @@ const Select = forwardRef<HTMLSelectElement, SelectHTMLAttributes<HTMLSelectElem
> >
{children} {children}
</select> </select>
), ))
)
Select.displayName = 'Select' Select.displayName = 'Select'
export default Select export default Select
+5 -4
View File
@@ -1,7 +1,9 @@
import { forwardRef, type TextareaHTMLAttributes } from 'react' import { forwardRef, type TextareaHTMLAttributes } from 'react'
const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement>>( const Textarea = forwardRef<
({ className = '', ...rest }, ref) => ( HTMLTextAreaElement,
TextareaHTMLAttributes<HTMLTextAreaElement>
>(({ className = '', ...rest }, ref) => (
<textarea <textarea
ref={ref} ref={ref}
className={[ className={[
@@ -10,7 +12,6 @@ const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLText
].join(' ')} ].join(' ')}
{...rest} {...rest}
/> />
), ))
)
Textarea.displayName = 'Textarea' Textarea.displayName = 'Textarea'
export default Textarea export default Textarea
-17
View File
@@ -1,17 +0,0 @@
import { z } from 'zod'
export const AnimalSchema = z.object({
/** Must match a registered species id (e.g. 'equine') */
speciesId: z.string().min(1),
name: z.string().min(1),
breed: z.string().optional(),
age: z.string().optional(),
})
export type Animal = z.infer<typeof AnimalSchema>
export const OwnerSchema = z.object({
name: z.string().min(1),
})
export type Owner = z.infer<typeof OwnerSchema>
-67
View File
@@ -1,67 +0,0 @@
import { z } from 'zod'
/**
* Schema for the species findings tree.
*
* Source of truth for what a practitioner can attach to an observation:
* a hierarchical tree of dysfunctions/observations per anatomical zone,
* authored by the domain expert in JSON and parsed at boot.
*
* Field names match the JSON authoring contract (snake_case).
* Recursive children are typed via z.lazy + an explicit ZodType annotation
* so TS can resolve the self-reference.
*/
export const SourceRefSchema = z.object({
type: z.enum(['manual', 'journal', 'database', 'web']),
citation: z.string().min(1),
url: z.string().url().optional(),
})
export type SourceRef = z.infer<typeof SourceRefSchema>
export interface FindingNode {
id: string
name_fr: string
name_en: string
description_fr?: string
description_en?: string
requires_vet_referral?: boolean
sources?: SourceRef[]
children?: FindingNode[]
}
export const FindingNodeSchema: z.ZodType<FindingNode> = z.lazy(() =>
z.object({
id: z.string().min(1),
name_fr: z.string().min(1),
name_en: z.string().min(1),
description_fr: z.string().optional(),
description_en: z.string().optional(),
requires_vet_referral: z.boolean().optional(),
sources: z.array(SourceRefSchema).optional(),
children: z.array(FindingNodeSchema).optional(),
}),
)
export const ZoneFindingsSchema = z.object({
id: z.string().min(1),
name_fr: z.string().min(1),
name_en: z.string().min(1),
categories: z.array(FindingNodeSchema),
})
export type ZoneFindings = z.infer<typeof ZoneFindingsSchema>
export const SpeciesFindingsSchema = z.object({
schema_version: z.string().min(1),
scope_disclaimer: z.string().min(1),
species: z.object({
id: z.string().min(1),
name_fr: z.string().min(1),
name_en: z.string().min(1),
}),
zones: z.record(z.string(), ZoneFindingsSchema),
})
export type SpeciesFindings = z.infer<typeof SpeciesFindingsSchema>
-61
View File
@@ -1,61 +0,0 @@
import { z } from 'zod'
export const SeveritySchema = z.enum(['légère', 'modérée', 'sévère'])
export type Severity = z.infer<typeof SeveritySchema>
export const VertebralRegionSchema = z.enum(['C', 'T', 'L', 'S', 'Cd'])
export type VertebralRegion = z.infer<typeof VertebralRegionSchema>
export const VertebraSchema = z.object({
region: VertebralRegionSchema,
index: z.number().int().positive(),
})
export type Vertebra = z.infer<typeof VertebraSchema>
export const LateralSideSchema = z.enum(['left', 'right'])
export type LateralSide = z.infer<typeof LateralSideSchema>
export const ObservationZoneSchema = z.object({
/** Must match data-anno-id attribute on the SVG element */
boneId: z.string().min(1),
/** Set when zone originates from a detail popup SVG */
detailSourceId: z.string().optional(),
/** Set when boneId is a spine-zone; replaces the block semantically */
vertebrae: z.array(VertebraSchema).optional(),
/** Set for bilateral zones to distinguish left from right */
side: LateralSideSchema.optional(),
})
export type ObservationZone = z.infer<typeof ObservationZoneSchema>
/**
* A selected leaf from the species findings tree. The path is anchored at the
* zone root (categories array), e.g. ['sphenoid-dysfunctions', 'physiological',
* 'flexion']. Labels are snapshotted at selection time so previously exported
* reports remain readable if the catalog is later edited.
*/
export const FindingSchema = z.object({
zoneId: z.string().min(1),
path: z.array(z.string().min(1)).min(1),
labelFrSnapshot: z.string().min(1),
labelEnSnapshot: z.string().min(1),
requiresVetReferral: z.boolean().optional(),
side: LateralSideSchema.optional(),
})
export type Finding = z.infer<typeof FindingSchema>
export const ObservationSchema = z.object({
id: z.string().min(1),
zones: z.array(ObservationZoneSchema),
findings: z.array(FindingSchema),
/** Free-text additions when the tree does not cover a finding */
freeTextFindings: z.array(z.string()),
severity: SeveritySchema.optional(),
comment: z.string(),
})
export type Observation = z.infer<typeof ObservationSchema>
@@ -1,11 +0,0 @@
import { z } from 'zod'
export const PractitionerSchema = z.object({
name: z.string().min(1),
cabinet: z.string().optional(),
contact: z.string().optional(),
/** SIRET — 14-digit French business identifier */
siret: z.string().optional(),
})
export type Practitioner = z.infer<typeof PractitionerSchema>
-33
View File
@@ -1,33 +0,0 @@
import { z } from 'zod'
import { PractitionerSchema } from './practitioner'
import { AnimalSchema, OwnerSchema } from './animal'
import { ObservationSchema } from './observation'
const NextAppointmentSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('date'), date: z.string() }),
z.object({ kind: z.literal('period'), text: z.string() }),
])
export type NextAppointment = z.infer<typeof NextAppointmentSchema>
export const ReportSchema = z.object({
/**
* Schema version. v2 introduced the hierarchical findings tree
* (replacing the flat pathology list). Bump on breaking changes.
*/
version: z.literal(2),
id: z.string().min(1),
/** ISO timestamp of report creation */
createdAt: z.string(),
/** ISO date of clinical encounter */
date: z.string(),
practitioner: PractitionerSchema,
animal: AnimalSchema,
owner: OwnerSchema,
observations: z.array(ObservationSchema),
conclusion: z.string(),
recommendations: z.string(),
nextAppointment: NextAppointmentSchema.optional(),
})
export type Report = z.infer<typeof ReportSchema>
@@ -1,18 +0,0 @@
import type { SpeciesManifest } from '@/domain/species/types'
import { EQUINE_VERTEBRAL_FORMULA } from './vertebrae'
const equine: SpeciesManifest = {
id: 'equine',
labelFr: 'Cheval',
labelEn: 'Horse',
mainSvg: '/species/equine/Horse.svg',
details: {
head: '/species/equine/Horse_head.svg',
},
vertebralFormula: EQUINE_VERTEBRAL_FORMULA,
findings: () => import('./pathologies'),
}
// Default export is the convention picked up by the registry's
// import.meta.glob() auto-discovery.
export default equine
File diff suppressed because it is too large. Load diff
@@ -1,13 +0,0 @@
import {
SpeciesFindingsSchema,
type SpeciesFindings,
} from '@/domain/schema/findings'
import data from './pathologies.json'
/**
* Equine findings tree. Authored as JSON, parsed via Zod at boot so any
* malformed data crashes loudly instead of corrupting an observation later.
*/
const EQUINE_FINDINGS: SpeciesFindings = SpeciesFindingsSchema.parse(data)
export default EQUINE_FINDINGS
-57
View File
@@ -1,57 +0,0 @@
import type { SpeciesManifest } from './types'
import type { Locale } from '@/i18n/types'
/**
* Auto-discovers every species manifest in `src/domain/species/*\/index.ts`
* via Vite's `import.meta.glob`. Each manifest module must default-export
* its `SpeciesManifest`. Drop a new folder with a conforming `index.ts`
* (and its `vertebrae.ts` + `pathologies.ts` siblings) and the species
* shows up everywhere — the AnimalForm dropdown, the editor canvas,
* the PDF export — without any registry edit.
*
* `eager: true` resolves modules synchronously at build time so the
* registry is a plain object literal in the bundled output (no async
* loading required to enumerate species).
*/
const modules = import.meta.glob<{ default: SpeciesManifest }>(
'./*/index.ts',
{ eager: true },
)
function buildRegistry(): Record<string, SpeciesManifest> {
const reg: Record<string, SpeciesManifest> = {}
for (const [path, mod] of Object.entries(modules)) {
const manifest = mod.default
if (!manifest || typeof manifest.id !== 'string' || !manifest.id) {
console.warn(`Species manifest at ${path} has no valid default export — skipping.`)
continue
}
if (reg[manifest.id]) {
console.warn(
`Duplicate species id "${manifest.id}" — keeping the first one (from ${path} ignored).`,
)
continue
}
reg[manifest.id] = manifest
}
return reg
}
const SPECIES_REGISTRY: Record<string, SpeciesManifest> = buildRegistry()
/** Returns a species manifest by id, or undefined if not registered. */
export function getSpecies(id: string): SpeciesManifest | undefined {
return SPECIES_REGISTRY[id]
}
/** Returns all registered species manifests, sorted alphabetically by labelFr. */
export function getAllSpecies(): SpeciesManifest[] {
return Object.values(SPECIES_REGISTRY).sort((a, b) =>
a.labelFr.localeCompare(b.labelFr, 'fr'),
)
}
/** Display label of a species for the given locale. */
export function speciesLabel(s: SpeciesManifest, locale: Locale): string {
return locale === 'en' ? s.labelEn : s.labelFr
}
-32
View File
@@ -1,32 +0,0 @@
import type { SpeciesFindings } from '@/domain/schema/findings'
/** Vertebral formula defines segment counts for a species. */
export interface VertebralFormula {
C: number
T: number
L: number
S: number
Cd: number
}
/** Lazy import returning a module with a default export of SpeciesFindings. */
export type FindingsLoader = () => Promise<{ default: SpeciesFindings }>
/** Species manifest — one per registered species. */
export interface SpeciesManifest {
id: string
/** Display name in French */
labelFr: string
/** Display name in English */
labelEn: string
/** Absolute public path to the main anatomy SVG */
mainSvg: string
/**
* Map of detail popup id → absolute public path to detail SVG.
* Keys match data-anno-opens-detail attribute values in the main SVG.
*/
details: Record<string, string>
vertebralFormula: VertebralFormula
/** Lazy-loaded findings tree (zones + categories + leaves) for this species */
findings: FindingsLoader
}
+37 -99
View File
@@ -16,10 +16,12 @@ export const en: Dict = {
'common.back_to_home': 'Back to home', 'common.back_to_home': 'Back to home',
'home.new_report.title': 'New report', 'home.new_report.title': 'New report',
'home.new_report.description': 'Start a new osteopathic report for an animal.', 'home.new_report.description':
'Start a new osteopathic report for an animal.',
'home.new_report.cta': 'Start', 'home.new_report.cta': 'Start',
'home.import.title': 'Import a PDF', 'home.import.title': 'Import a PDF',
'home.import.description': 'Reopen a previous report generated by this app to follow up.', 'home.import.description':
'Reopen a previous report generated by this app to follow up.',
'home.import.cta': 'Choose a PDF', 'home.import.cta': 'Choose a PDF',
'home.import.loading': 'Reading…', 'home.import.loading': 'Reading…',
'home.import.error_generic': 'Failed to read the PDF.', 'home.import.error_generic': 'Failed to read the PDF.',
@@ -27,24 +29,18 @@ export const en: Dict = {
'home.import.error_no_attachment': 'home.import.error_no_attachment':
'This PDF was not generated by Faunosteo (no data detected).', 'This PDF was not generated by Faunosteo (no data detected).',
'home.import.error_incompatible_version': 'home.import.error_incompatible_version':
'This PDF uses format v{version}, incompatible with the current version (v2). Re-export the report from a recent version of the app.', 'This PDF uses format v{version}, which this version of the application cannot read (accepted formats: v2 and v3).',
'home.import.migrated':
'Report imported from an older format. Findings not found in the current sheet: {count} (kept with their labels).',
'home.no_sheet.title': 'No anatomical sheet',
'home.no_sheet.description':
'This build of the application carries no anatomical sheet: no report can be created or imported.',
// footer // footer
'footer.all_rights_reserved': 'All rights reserved.', 'footer.all_rights_reserved': 'All rights reserved.',
'footer.powered_by': 'Powered by', 'footer.powered_by': 'Powered by',
'footer.editors': 'Editors',
'footer.in_partnership': 'In partnership with', 'footer.in_partnership': 'In partnership with',
// editors page
'editors.svg.title': 'SVG Editor',
'editors.svg.description':
'Annotate an anatomical SVG file: add clickable zones, categories, and FR/EN labels.',
'editors.svg.cta': 'Open',
'editors.pathology.title': 'Pathology Editor',
'editors.pathology.description':
'Create and edit the pathology catalog (JSON tree) for a species.',
'editors.pathology.cta': 'Open',
'not_found.title': 'Page not found', 'not_found.title': 'Page not found',
'not_found.description': 'The requested path does not exist.', 'not_found.description': 'The requested path does not exist.',
@@ -58,20 +54,22 @@ export const en: Dict = {
'editor.edit_infos': 'Edit info', 'editor.edit_infos': 'Edit info',
'editor.edit_dialog_title': 'Edit information', 'editor.edit_dialog_title': 'Edit information',
'editor.disclaimer_title': 'Legal scope of animal osteopathy', 'editor.disclaimer_title': 'Legal scope of animal osteopathy',
'editor.detail_title_prefix': 'Detail — ',
'detail.click_to_add': 'Click the zones to add them to the current observation.', 'detail.click_to_add':
'Click the zones to add them to the current observation.',
'observation.section_title': 'Observations', 'observation.section_title': 'Observations',
'observation.add': '+ New observation', 'observation.add': '+ New observation',
'observation.empty': 'No observation. Click "+ New observation" then on the zones in the diagram.', 'observation.empty':
'No observation. Click "+ New observation" then on the zones in the diagram.',
'observation.badge_n': 'Observation #', 'observation.badge_n': 'Observation #',
'observation.zone_label_singular': 'zone', 'observation.zone_label_singular': 'zone',
'observation.zone_label_plural': 'zones', 'observation.zone_label_plural': 'zones',
'observation.finding_label_singular': 'finding', 'observation.finding_label_singular': 'finding',
'observation.finding_label_plural': 'findings', 'observation.finding_label_plural': 'findings',
'observation.zones_label': 'Selected zones', 'observation.zones_label': 'Selected zones',
'observation.zones_empty': 'Click on the zones in the diagram to add them to this observation.', 'observation.zones_empty':
'Click on the zones in the diagram to add them to this observation.',
'observation.findings_catalog_label': 'Findings (catalog)', 'observation.findings_catalog_label': 'Findings (catalog)',
'observation.findings_pick_zone_first': 'Pick a zone to access the catalog.', 'observation.findings_pick_zone_first': 'Pick a zone to access the catalog.',
'observation.findings_no_catalog': 'observation.findings_no_catalog':
@@ -118,13 +116,26 @@ export const en: Dict = {
'conclusion.next_period_placeholder': 'e.g. in 3 weeks', 'conclusion.next_period_placeholder': 'e.g. in 3 weeks',
'vertebra.title_prefix': 'Specify vertebrae — ', 'vertebra.title_prefix': 'Specify vertebrae — ',
'vertebra.region.C': 'Cervical',
'vertebra.region.T': 'Thoracic',
'vertebra.region.L': 'Lumbar',
'vertebra.region.S': 'Sacral',
'vertebra.region.Cd': 'Caudal',
'vertebra.check_all': 'Select all', 'vertebra.check_all': 'Select all',
'vertebra.uncheck_all': 'Clear all', 'vertebra.uncheck_all': 'Clear all',
'vertebra.extend_to': 'Show up to {max}',
'vertebra.range_note':
'Usual count: {usual}; documented variation: {min} to {max}.',
// sheet
'sheet.status.draft':
'Anatomical sheet: reference draft, not medically validated',
'sheet.status.published': 'Official anatomical sheet',
'sheet.loading': 'Loading the anatomical sheet…',
// unresolved (migrated) data
'observation.unresolved_short': 'inherited',
'observation.zone_unresolved':
'Zone inherited from an older report, absent from the current sheet',
'observation.findings_unresolved_label':
'Inherited findings (outside the current catalog)',
'observation.findings_unresolved_help':
'Findings imported from an older report whose path no longer exists in the sheet: kept with their original labels.',
// laterality // laterality
'lateral.which_side': 'Which side?', 'lateral.which_side': 'Which side?',
@@ -135,9 +146,9 @@ export const en: Dict = {
'lateral.right_short': 'R', 'lateral.right_short': 'R',
'severity.aria': 'Severity', 'severity.aria': 'Severity',
'severity.légère': 'mild', 'severity.mild': 'mild',
'severity.modérée': 'moderate', 'severity.moderate': 'moderate',
'severity.sévère': 'severe', 'severity.severe': 'severe',
'pdf.eyebrow.observation': 'OBSERVATION', 'pdf.eyebrow.observation': 'OBSERVATION',
'pdf.eyebrow.synthesis': 'SYNTHESIS', 'pdf.eyebrow.synthesis': 'SYNTHESIS',
@@ -163,77 +174,4 @@ export const en: Dict = {
'lang.switch_to_en': 'Switch to English', 'lang.switch_to_en': 'Switch to English',
'lang.fr': 'FR', 'lang.fr': 'FR',
'lang.en': 'EN', 'lang.en': 'EN',
// svg editor
'svg_editor.title': 'SVG Anatomy Editor',
'svg_editor.subtitle': 'Points, zones & clickable categories',
'svg_editor.file': 'File',
'svg_editor.choose_file': 'Choose an SVG file',
'svg_editor.change_file': 'Change SVG file',
'svg_editor.export': 'Export SVG',
'svg_editor.mode': 'Mode',
'svg_editor.mode_select': 'Select / move',
'svg_editor.mode_point': 'Add point',
'svg_editor.mode_polygon': 'Add polygon',
'svg_editor.validate_polygon': 'Validate polygon (Enter)',
'svg_editor.cancel_polygon': 'Cancel (Esc)',
'svg_editor.category_for_new': 'Category for new elements',
'svg_editor.categories': 'Categories',
'svg_editor.shared_color': '(shared color)',
'svg_editor.category_placeholder': 'Category name',
'svg_editor.selected_element': 'Selected element',
'svg_editor.opens_detail': 'This zone opens a detail view',
'svg_editor.detail_id_label': 'Detail view ID (e.g. head, front-leg)',
'svg_editor.detail_id_placeholder': 'head',
'svg_editor.name_fr': 'French name',
'svg_editor.name_fr_placeholder': 'e.g. Hanche',
'svg_editor.name_en': 'English name',
'svg_editor.name_en_placeholder': 'e.g. Hip joint',
'svg_editor.category': 'Category',
'svg_editor.radius': 'Radius (circle)',
'svg_editor.fill_opacity': 'Fill opacity',
'svg_editor.polygon_editing': 'Polygon editing:',
'svg_editor.polygon_drag': 'Drag a yellow handle to move it',
'svg_editor.polygon_insert': 'Click a white mid-handle to insert a vertex',
'svg_editor.polygon_delete': 'Alt+click or right-click a yellow handle to delete it',
'svg_editor.redraw_polygon': 'Redraw this polygon',
'svg_editor.delete': 'Delete',
'svg_editor.elements': 'Elements',
'svg_editor.filter_placeholder': 'Filter...',
'svg_editor.welcome_title': 'SVG Anatomy Editor',
'svg_editor.welcome_text': 'Upload an SVG file to begin. If your file already has points/zones with ',
'svg_editor.welcome_text_suffix': ', they will be detected and configured automatically.',
'svg_editor.welcome_drag_hint': 'or drag & drop an SVG file anywhere',
'svg_editor.no_categories': 'No categories yet. Use the form below to add one.',
'svg_editor.new_point_fr': 'Nouveau point',
'svg_editor.new_point_en': 'New point',
'svg_editor.new_zone_fr': 'Nouvelle zone',
'svg_editor.new_zone_en': 'New zone',
'svg_editor.alert_drop_svg': 'Drop an SVG file.',
'svg_editor.alert_invalid_svg': 'Invalid file: no SVG element found.',
'svg_editor.alert_min_3': 'Need at least 3 points.',
'svg_editor.alert_min_3_vertices': 'A polygon must have at least 3 vertices.',
'svg_editor.alert_upload_first': 'Upload an SVG first.',
'svg_editor.alert_no_svg_loaded': 'No SVG loaded. Upload a file first.',
'svg_editor.alert_cat_name_required': 'Give the category a name.',
'svg_editor.alert_cat_invalid_name': 'Invalid name.',
'svg_editor.alert_cat_exists': 'This category already exists.',
'svg_editor.confirm_delete_element': 'Delete this element?',
'svg_editor.confirm_delete_cat': 'Delete category "{name}"?',
'svg_editor.confirm_delete_cat_count': '\n\nIt contains {count} element(s) that will also be deleted.',
'svg_editor.confirm_redraw': 'Erase this polygon and redraw it?',
'svg_editor.handle_drag': 'Drag to move | Alt+click or right-click to delete',
'svg_editor.handle_insert': 'Click to insert a vertex here',
'svg_editor.polygon_vertices': 'polygon ({count} vertices)',
'svg_editor.drop_svg_here': 'Drop SVG here',
'svg_editor.lateral': 'Laterality',
'svg_editor.lateral_unpaired': 'Unilateral (no side)',
'svg_editor.lateral_bilateral': 'Bilateral (left / right)',
'svg_editor.source_project': 'Project SVGs',
'svg_editor.source_upload': 'Upload a file',
'svg_editor.species': 'Species',
'svg_editor.view': 'View',
'svg_editor.view_main': 'Full body',
'svg_editor.view_detail': 'Detail: {name}',
'svg_editor.load': 'Load',
} }
+41 -103
View File
@@ -18,37 +18,31 @@ export const fr: Dict = {
// home // home
'home.new_report.title': 'Nouveau bilan', 'home.new_report.title': 'Nouveau bilan',
'home.new_report.description': "Démarrer un nouveau bilan d'ostéopathie sur un animal.", 'home.new_report.description':
"Démarrer un nouveau bilan d'ostéopathie sur un animal.",
'home.new_report.cta': 'Commencer', 'home.new_report.cta': 'Commencer',
'home.import.title': 'Importer un PDF', 'home.import.title': 'Importer un PDF',
'home.import.description': 'home.import.description':
"Reprendre un bilan précédent généré par cette application pour effectuer un suivi.", 'Reprendre un bilan précédent généré par cette application pour effectuer un suivi.',
'home.import.cta': 'Choisir un PDF', 'home.import.cta': 'Choisir un PDF',
'home.import.loading': 'Lecture…', 'home.import.loading': 'Lecture…',
'home.import.error_generic': 'Erreur de lecture du PDF.', 'home.import.error_generic': 'Erreur de lecture du PDF.',
'home.import.error_invalid_pdf': 'home.import.error_invalid_pdf': "Ce fichier n'est pas un PDF lisible.",
"Ce fichier n'est pas un PDF lisible.",
'home.import.error_no_attachment': 'home.import.error_no_attachment':
"Ce PDF n'a pas été généré par Faunosteo (pas de données détectées).", "Ce PDF n'a pas été généré par Faunosteo (pas de données détectées).",
'home.import.error_incompatible_version': 'home.import.error_incompatible_version':
"Ce PDF est au format v{version}, incompatible avec la version actuelle (v2). Réexportez le bilan depuis une version récente de l'application.", "Ce PDF est au format v{version}, que cette version de l'application ne sait pas lire (formats acceptés : v2 et v3).",
'home.import.migrated':
'Bilan importé depuis un ancien format. Constats non retrouvés dans la fiche actuelle : {count} (conservés avec leurs libellés).',
'home.no_sheet.title': 'Aucune fiche anatomique',
'home.no_sheet.description':
"Cette version de l'application n'embarque aucune fiche anatomique : aucun bilan ne peut être créé ni importé.",
// footer // footer
'footer.all_rights_reserved': 'Tous droits réservés.', 'footer.all_rights_reserved': 'Tous droits réservés.',
'footer.powered_by': 'Propulsé par', 'footer.powered_by': 'Propulsé par',
'footer.editors': 'Éditeurs',
'footer.in_partnership': 'En partenariat avec', 'footer.in_partnership': 'En partenariat avec',
// editors page
'editors.svg.title': 'Éditeur SVG',
'editors.svg.description':
'Annoter un fichier SVG anatomique : ajouter des zones cliquables, catégories et labels FR/EN.',
'editors.svg.cta': 'Ouvrir',
'editors.pathology.title': 'Éditeur de pathologies',
'editors.pathology.description':
'Créer et modifier le référentiel de pathologies (arbre JSON) pour une espèce.',
'editors.pathology.cta': 'Ouvrir',
// not found // not found
'not_found.title': 'Page introuvable', 'not_found.title': 'Page introuvable',
'not_found.description': "Le chemin demandé n'existe pas.", 'not_found.description': "Le chemin demandé n'existe pas.",
@@ -61,14 +55,15 @@ export const fr: Dict = {
// editor // editor
'editor.export': 'Exporter en PDF', 'editor.export': 'Exporter en PDF',
'editor.exporting': 'Génération…', 'editor.exporting': 'Génération…',
'editor.export_failed': 'Échec de la génération du PDF. Réessayez ou contactez le support.', 'editor.export_failed':
'Échec de la génération du PDF. Réessayez ou contactez le support.',
'editor.edit_infos': 'Modifier les infos', 'editor.edit_infos': 'Modifier les infos',
'editor.edit_dialog_title': 'Modifier les informations', 'editor.edit_dialog_title': 'Modifier les informations',
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale", 'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
'editor.detail_title_prefix': 'Détail — ',
// detail modal // detail modal
'detail.click_to_add': "Cliquez sur les zones pour les ajouter à l'observation en cours.", 'detail.click_to_add':
"Cliquez sur les zones pour les ajouter à l'observation en cours.",
// observation list / card // observation list / card
'observation.section_title': 'Observations', 'observation.section_title': 'Observations',
@@ -81,9 +76,11 @@ export const fr: Dict = {
'observation.finding_label_singular': 'constat', 'observation.finding_label_singular': 'constat',
'observation.finding_label_plural': 'constats', 'observation.finding_label_plural': 'constats',
'observation.zones_label': 'Zones sélectionnées', 'observation.zones_label': 'Zones sélectionnées',
'observation.zones_empty': 'Cliquez sur les zones du schéma pour les ajouter à cette observation.', 'observation.zones_empty':
'Cliquez sur les zones du schéma pour les ajouter à cette observation.',
'observation.findings_catalog_label': 'Constats (référentiel)', 'observation.findings_catalog_label': 'Constats (référentiel)',
'observation.findings_pick_zone_first': 'Sélectionnez une zone pour accéder au référentiel.', 'observation.findings_pick_zone_first':
'Sélectionnez une zone pour accéder au référentiel.',
'observation.findings_no_catalog': 'observation.findings_no_catalog':
'Aucun référentiel disponible pour ces zones. Utilisez le texte libre ci-dessous.', 'Aucun référentiel disponible pour ces zones. Utilisez le texte libre ci-dessous.',
'observation.findings_free_label': 'Constats (texte libre)', 'observation.findings_free_label': 'Constats (texte libre)',
@@ -93,7 +90,8 @@ export const fr: Dict = {
'observation.comment_label': 'Commentaire', 'observation.comment_label': 'Commentaire',
'observation.comment_placeholder': 'Notes cliniques détaillées…', 'observation.comment_placeholder': 'Notes cliniques détaillées…',
'observation.vertebrae_button': 'Vertèbres…', 'observation.vertebrae_button': 'Vertèbres…',
'observation.vertebrae_button_title': 'Préciser les vertèbres pour cette zone', 'observation.vertebrae_button_title':
'Préciser les vertèbres pour cette zone',
'observation.remove_zone': 'Retirer', 'observation.remove_zone': 'Retirer',
'observation.expand_aria': "Développer l'observation", 'observation.expand_aria': "Développer l'observation",
'observation.collapse_aria': "Réduire l'observation", 'observation.collapse_aria': "Réduire l'observation",
@@ -132,13 +130,26 @@ export const fr: Dict = {
// vertebra picker // vertebra picker
'vertebra.title_prefix': 'Préciser les vertèbres — ', 'vertebra.title_prefix': 'Préciser les vertèbres — ',
'vertebra.region.C': 'Cervicales',
'vertebra.region.T': 'Thoraciques',
'vertebra.region.L': 'Lombaires',
'vertebra.region.S': 'Sacrales',
'vertebra.region.Cd': 'Caudales',
'vertebra.check_all': 'Tout cocher', 'vertebra.check_all': 'Tout cocher',
'vertebra.uncheck_all': 'Tout décocher', 'vertebra.uncheck_all': 'Tout décocher',
'vertebra.extend_to': "Afficher jusqu'à {max}",
'vertebra.range_note':
'Nombre usuel : {usual} ; variation documentée : {min} à {max}.',
// sheet
'sheet.status.draft':
'Fiche anatomique : brouillon de référence, non validé médicalement',
'sheet.status.published': 'Fiche anatomique officielle',
'sheet.loading': 'Chargement de la fiche anatomique…',
// unresolved (migrated) data
'observation.unresolved_short': 'hérité',
'observation.zone_unresolved':
"Zone héritée d'un ancien bilan, absente de la fiche actuelle",
'observation.findings_unresolved_label':
'Constats hérités (hors référentiel actuel)',
'observation.findings_unresolved_help':
"Constats importés d'un ancien bilan dont le chemin n'existe plus dans la fiche : conservés avec leurs libellés d'origine.",
// laterality // laterality
'lateral.which_side': 'Quel côté ?', 'lateral.which_side': 'Quel côté ?',
@@ -150,9 +161,9 @@ export const fr: Dict = {
// severity // severity
'severity.aria': 'Sévérité', 'severity.aria': 'Sévérité',
'severity.légère': 'légère', 'severity.mild': 'légère',
'severity.modérée': 'modérée', 'severity.moderate': 'modérée',
'severity.sévère': 'sévère', 'severity.severe': 'sévère',
// pdf // pdf
'pdf.eyebrow.observation': 'OBSERVATION', 'pdf.eyebrow.observation': 'OBSERVATION',
@@ -180,77 +191,4 @@ export const fr: Dict = {
'lang.switch_to_en': 'Switch to English', 'lang.switch_to_en': 'Switch to English',
'lang.fr': 'FR', 'lang.fr': 'FR',
'lang.en': 'EN', 'lang.en': 'EN',
// svg editor
'svg_editor.title': 'Editeur SVG anatomique',
'svg_editor.subtitle': 'Points, zones & catégories cliquables',
'svg_editor.file': 'Fichier',
'svg_editor.choose_file': 'Choisir un fichier SVG',
'svg_editor.change_file': 'Changer de fichier SVG',
'svg_editor.export': 'Exporter le SVG',
'svg_editor.mode': 'Mode',
'svg_editor.mode_select': 'Sélectionner / déplacer',
'svg_editor.mode_point': 'Ajouter un point',
'svg_editor.mode_polygon': 'Ajouter un polygone',
'svg_editor.validate_polygon': 'Valider le polygone (Entrée)',
'svg_editor.cancel_polygon': 'Annuler (Echap)',
'svg_editor.category_for_new': 'Catégorie des nouveaux éléments',
'svg_editor.categories': 'Catégories',
'svg_editor.shared_color': '(couleur partagée)',
'svg_editor.category_placeholder': 'Nom de catégorie',
'svg_editor.selected_element': 'Elément sélectionné',
'svg_editor.opens_detail': 'Cette zone ouvre une vue détaillée',
'svg_editor.detail_id_label': 'ID vue détaillée (ex. head, front-leg)',
'svg_editor.detail_id_placeholder': 'head',
'svg_editor.name_fr': 'Nom français',
'svg_editor.name_fr_placeholder': 'ex: Hanche',
'svg_editor.name_en': 'Nom anglais',
'svg_editor.name_en_placeholder': 'ex: Hip joint',
'svg_editor.category': 'Catégorie',
'svg_editor.radius': 'Rayon (cercle)',
'svg_editor.fill_opacity': 'Opacité du remplissage',
'svg_editor.polygon_editing': 'Edition du polygone :',
'svg_editor.polygon_drag': 'Glissez une poignée jaune pour la déplacer',
'svg_editor.polygon_insert': 'Cliquez une poignée blanche pour insérer un sommet',
'svg_editor.polygon_delete': 'Alt+clic ou clic droit sur une poignée jaune pour la supprimer',
'svg_editor.redraw_polygon': 'Redessiner ce polygone',
'svg_editor.delete': 'Supprimer',
'svg_editor.elements': 'Eléments',
'svg_editor.filter_placeholder': 'Filtrer...',
'svg_editor.welcome_title': 'Editeur SVG anatomique',
'svg_editor.welcome_text': 'Importez un fichier SVG pour commencer. Si votre fichier contient déjà des points/zones avec ',
'svg_editor.welcome_text_suffix': ', ils seront détectés et configurés automatiquement.',
'svg_editor.welcome_drag_hint': 'ou glissez-déposez un fichier SVG n\'importe où',
'svg_editor.no_categories': 'Aucune catégorie. Utilisez le formulaire ci-dessous pour en ajouter une.',
'svg_editor.new_point_fr': 'Nouveau point',
'svg_editor.new_point_en': 'New point',
'svg_editor.new_zone_fr': 'Nouvelle zone',
'svg_editor.new_zone_en': 'New zone',
'svg_editor.alert_drop_svg': 'Déposez un fichier SVG.',
'svg_editor.alert_invalid_svg': 'Fichier invalide : aucun élément SVG trouvé.',
'svg_editor.alert_min_3': 'Il faut au moins 3 points.',
'svg_editor.alert_min_3_vertices': 'Un polygone doit avoir au moins 3 sommets.',
'svg_editor.alert_upload_first': 'Importez d\'abord un SVG.',
'svg_editor.alert_no_svg_loaded': 'Aucun SVG chargé. Importez d\'abord un fichier.',
'svg_editor.alert_cat_name_required': 'Donnez un nom à la catégorie.',
'svg_editor.alert_cat_invalid_name': 'Nom invalide.',
'svg_editor.alert_cat_exists': 'Cette catégorie existe déjà.',
'svg_editor.confirm_delete_element': 'Supprimer cet élément ?',
'svg_editor.confirm_delete_cat': 'Supprimer la catégorie "{name}" ?',
'svg_editor.confirm_delete_cat_count': '\n\nElle contient {count} élément(s) qui seront aussi supprimés.',
'svg_editor.confirm_redraw': 'Effacer ce polygone et le redessiner ?',
'svg_editor.handle_drag': 'Glisser pour déplacer | Alt+clic ou clic droit pour supprimer',
'svg_editor.handle_insert': 'Cliquez pour insérer un sommet ici',
'svg_editor.polygon_vertices': 'polygone ({count} sommets)',
'svg_editor.drop_svg_here': 'Déposez le SVG ici',
'svg_editor.lateral': 'Latéralité',
'svg_editor.lateral_unpaired': 'Unilatéral (pas de côté)',
'svg_editor.lateral_bilateral': 'Bilatéral (gauche / droite)',
'svg_editor.source_project': 'SVG du projet',
'svg_editor.source_upload': 'Importer un fichier',
'svg_editor.species': 'Espèce',
'svg_editor.view': 'Vue',
'svg_editor.view_main': 'Corps entier',
'svg_editor.view_detail': 'Détail : {name}',
'svg_editor.load': 'Charger',
} }
+2 -1
View File
@@ -18,7 +18,8 @@ export function formatDate(isoDate: string, locale: Locale): string {
if (!match) throw new Error(`Invalid ISO date: ${isoDate}`) if (!match) throw new Error(`Invalid ISO date: ${isoDate}`)
const [, y, mo, d] = match const [, y, mo, d] = match
const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d))) const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d)))
if (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date: ${isoDate}`) if (Number.isNaN(date.getTime()))
throw new Error(`Invalid ISO date: ${isoDate}`)
return new Intl.DateTimeFormat(LOCALE_TAG[locale], { return new Intl.DateTimeFormat(LOCALE_TAG[locale], {
day: 'numeric', day: 'numeric',
month: 'long', month: 'long',
-131
View File
@@ -1,131 +0,0 @@
import type {
ObservationZone,
Vertebra,
VertebralRegion,
} from '@/domain/schema/observation'
import type { Bone } from '@/anatomy/types'
/**
* Infers the matching vertebral region from a free-form anatomical label
* (zone name in FR or EN). Matches on substring roots, case-insensitive,
* accent-insensitive. Returns undefined when no root matches.
*/
export function regionFromLabel(label: string): VertebralRegion | undefined {
const norm = label
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase()
if (norm.includes('cervic')) return 'C'
if (norm.includes('thorac') || norm.includes('dors')) return 'T'
if (norm.includes('lombair') || norm.includes('lumbar')) return 'L'
if (norm.includes('sacral') || norm.includes('sacre')) return 'S'
if (norm.includes('caudal') || norm.includes('coccyg')) return 'Cd'
return undefined
}
/**
* Finds the spine-zone boneId whose label maps to the given vertebral region.
* Spine zones are the SVG elements flagged data-anno-special="vertebral-precision".
* Returns undefined when the SVG exposes no zone for that region.
*/
export function findSpineZoneId(
region: VertebralRegion,
bones: Map<string, Bone>,
): string | undefined {
for (const [id, bone] of bones) {
if (bone.special !== 'vertebral-precision') continue
const r = regionFromLabel(bone.fr) ?? regionFromLabel(bone.en)
if (r === region) return id
}
return undefined
}
const key = (v: Vertebra) => `${v.region}${v.index}`
const isSpineZone = (z: ObservationZone, bones: Map<string, Bone>) =>
!z.detailSourceId && bones.get(z.boneId)?.special === 'vertebral-precision'
/**
* Gathers the union of vertebrae across every spine zone of an observation so
* the picker can show selections from all regions at once. `priorityBoneId`'s
* vertebrae are listed first so the picker opens on the clicked zone's tab
* (the picker keys its default tab off the first vertebra's region).
*
* Deduplicated by region+index; order otherwise follows zone order.
*/
export function collectSpineVertebrae(
zones: ObservationZone[],
bones: Map<string, Bone>,
priorityBoneId?: string,
): Vertebra[] {
const spine = zones.filter((z) => isSpineZone(z, bones))
const ordered = priorityBoneId
? [
...spine.filter((z) => z.boneId === priorityBoneId),
...spine.filter((z) => z.boneId !== priorityBoneId),
]
: spine
const out: Vertebra[] = []
const seen = new Set<string>()
for (const z of ordered) {
for (const v of z.vertebrae ?? []) {
if (seen.has(key(v))) continue
seen.add(key(v))
out.push(v)
}
}
return out
}
/**
* Reconciles the observation's spine zones with the full set of vertebrae the
* picker confirmed (the picker shows and edits every region at once).
*
* Authoritative per region: each region's zone gets exactly the vertebrae
* picked for it (replace, so unchecking sticks); a region with no vertebrae
* left has its spine zone pruned; a region picked for the first time spawns its
* zone so the SVG highlights it and its findings picker appears. Non-spine
* zones (and their order) are preserved untouched.
*
* Returns a new zones array; the original is not mutated.
*/
export function syncSpineZones(
zones: ObservationZone[],
vertebrae: Vertebra[],
bones: Map<string, Bone>,
): ObservationZone[] {
const byRegion = new Map<VertebralRegion, Vertebra[]>()
for (const v of vertebrae) {
byRegion.set(v.region, [...(byRegion.get(v.region) ?? []), v])
}
const result: ObservationZone[] = []
const handled = new Set<VertebralRegion>()
for (const z of zones) {
const bone = bones.get(z.boneId)
const region =
!z.detailSourceId && bone?.special === 'vertebral-precision'
? (regionFromLabel(bone.fr) ?? regionFromLabel(bone.en))
: undefined
// Non-spine, detail-sourced, or unrecognized-label zones pass through.
if (!region) {
result.push(z)
continue
}
const verts = byRegion.get(region)
if (!verts) continue // region deselected to zero → prune the zone
result.push({ ...z, vertebrae: verts })
handled.add(region)
}
// Regions picked that had no existing zone yet → spawn one.
for (const [region, verts] of byRegion) {
if (handled.has(region)) continue
const zoneId = findSpineZoneId(region, bones)
if (zoneId) result.push({ boneId: zoneId, vertebrae: verts })
}
return result
}
-130
View File
@@ -1,130 +0,0 @@
import type { ZoneFindings } from '@/domain/schema/findings'
/**
* Bridges SVG anatomy labels to the JSON findings catalog when the two
* carry slightly different strings (casse, accents, abbreviations like
* "(ATM)" vs "Articulation Temporo-Mandibulaire (ATM)", or genuine typos).
*
* Strategy: normalize aggressively (lowercase + NFD-strip accents + drop
* non-alphanumerics), then score each (boneLabel, zoneLabel) pair:
*
* 0 exact normalized match
* 1 one normalized string is contained in the other (substring)
* 2+d Levenshtein distance d, within a length-relative threshold
* ∞ beyond tolerance — discarded
*
* Language strategy: English first (no accents → fewer normalization
* edge cases), French as fallback, fuzzy matching across both languages
* as last resort. Falls through silently when nothing matches.
*/
export function normalizeLabel(s: string | undefined | null): string {
if (!s) return ''
return s
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9]+/g, '')
}
export function levenshtein(a: string, b: string): number {
if (a === b) return 0
const al = a.length
const bl = b.length
if (al === 0) return bl
if (bl === 0) return al
let prev: number[] = new Array(bl + 1)
let curr: number[] = new Array(bl + 1)
for (let j = 0; j <= bl; j += 1) prev[j] = j
for (let i = 1; i <= al; i += 1) {
curr[0] = i
for (let j = 1; j <= bl; j += 1) {
const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost)
}
const tmp = prev
prev = curr
curr = tmp
}
return prev[bl]
}
const SCORE_EXACT = 0
const SCORE_SUBSTRING = 1
const SCORE_FUZZY_BASE = 2
const SCORE_NO_MATCH = Number.POSITIVE_INFINITY
/**
* Compares two raw labels after normalization. Lower scores beat higher
* ones; SCORE_NO_MATCH means the inputs are too dissimilar to be linked
* confidently.
*/
export function scorePair(boneLabel: string, zoneLabel: string): number {
const a = normalizeLabel(boneLabel)
const b = normalizeLabel(zoneLabel)
if (!a || !b) return SCORE_NO_MATCH
if (a === b) return SCORE_EXACT
if (a.includes(b) || b.includes(a)) return SCORE_SUBSTRING
const distance = levenshtein(a, b)
const longest = Math.max(a.length, b.length)
// 25% character tolerance, with a minimum of 2 edits so short labels
// (e.g. "Hip") still admit one typo without exploding into the matcher.
const threshold = Math.max(2, Math.floor(longest * 0.25))
if (distance > threshold) return SCORE_NO_MATCH
return SCORE_FUZZY_BASE + distance
}
export interface BoneLabels {
fr: string
en: string
}
interface ScoredZone {
zone: ZoneFindings
score: number
}
function bestOnLanguage(
boneLabel: string,
zones: ZoneFindings[],
pickZoneLabel: (zone: ZoneFindings) => string,
): ScoredZone | undefined {
let best: ScoredZone | undefined
for (const zone of zones) {
const score = scorePair(boneLabel, pickZoneLabel(zone))
if (score === SCORE_NO_MATCH) continue
if (!best || score < best.score) best = { zone, score }
}
return best
}
/**
* Pick the findings tree most likely to describe a clicked SVG zone.
*
* 1. If the English bone label exactly matches (or is contained in) an
* English zone label, return that zone — cheapest, most reliable.
* 2. Otherwise try the same on the French side.
* 3. As a last resort, take the lowest fuzzy score across all four
* (bone-lang, zone-lang) pairings.
*/
export function matchZoneFindings(
bone: BoneLabels,
zones: ZoneFindings[],
): ZoneFindings | undefined {
if (zones.length === 0) return undefined
const enOnEn = bestOnLanguage(bone.en, zones, (z) => z.name_en)
if (enOnEn && enOnEn.score <= SCORE_SUBSTRING) return enOnEn.zone
const frOnFr = bestOnLanguage(bone.fr, zones, (z) => z.name_fr)
if (frOnFr && frOnFr.score <= SCORE_SUBSTRING) return frOnFr.zone
const enOnFr = bestOnLanguage(bone.en, zones, (z) => z.name_fr)
const frOnEn = bestOnLanguage(bone.fr, zones, (z) => z.name_en)
const candidates = [enOnEn, frOnFr, enOnFr, frOnEn].filter(
(x): x is ScoredZone => x !== undefined,
)
if (candidates.length === 0) return undefined
candidates.sort((a, b) => a.score - b.score)
return candidates[0].zone
}
+105 -37
View File
@@ -1,59 +1,112 @@
import { AFRelationship, type PDFDocument } from 'pdf-lib' import { AFRelationship, type PDFDocument } from 'pdf-lib'
import { ReportSchema, type Report } from '@/domain/schema/report' import {
readReportDocument,
REPORT_VERSION,
UnsupportedReportVersionError,
type MigrationOutcome,
type Report,
type ReportMigrationMap,
} from '@faunosteo/domain'
/**
* The report document travels inside the PDF as a native attachment.
* Written as v3; read back as v3, or as v2 migrated through the sheet's
* migration map (the practitioner's archive). Any other version is refused
* with the found version.
*/
const FILENAME = 'osteo-report.json' const FILENAME = 'osteo-report.json'
/**
* Internal sentinel raised when the attached JSON's `version` field is
* present but not 2. The UI-facing message is composed by the importer
* caller against the active i18n dict — this error only carries the
* discriminating data.
*/
export class IncompatibleReportVersionError extends Error { export class IncompatibleReportVersionError extends Error {
constructor(public readonly foundVersion: number) { constructor(public readonly foundVersion: number | null) {
super(`incompatible_version:${foundVersion}`) super(`incompatible_version:${foundVersion ?? 'unknown'}`)
this.name = 'IncompatibleReportVersionError' this.name = 'IncompatibleReportVersionError'
} }
} }
export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise<void> { export async function attachReportJson(
pdfDoc: PDFDocument,
report: Report,
): Promise<void> {
const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2)) const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2))
await pdfDoc.attach(bytes, FILENAME, { await pdfDoc.attach(bytes, FILENAME, {
mimeType: 'application/json', mimeType: 'application/json',
description: 'Faunosteo state v2', description: `Faunosteo state v${REPORT_VERSION}`,
creationDate: new Date(), creationDate: new Date(),
modificationDate: new Date(), modificationDate: new Date(),
afRelationship: AFRelationship.Data, afRelationship: AFRelationship.Data,
}) })
} }
export async function extractReportJson(pdfDoc: PDFDocument): Promise<Report> { export interface ExtractedReport extends MigrationOutcome {
const maybeApi = pdfDoc as unknown as { getAttachments?: () => Array<{ name: string; data: Uint8Array }> } /** True when the attachment was an older version lifted to v3. */
migrated: boolean
}
/**
* The raw report document carried by the PDF, of whatever version, before
* any migration: what the archive check tool shows next to the v3 result.
* Throws when the PDF carries no Faunosteo attachment or an oversized one.
*/
export async function readAttachedDocument(
pdfDoc: PDFDocument,
): Promise<unknown> {
const bytes = await attachmentBytes(pdfDoc)
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) {
throw new Error('attachment too large')
}
const data: unknown = JSON.parse(new TextDecoder().decode(bytes))
// No numeric version at all: not a Faunosteo attachment (legacy message), not an old one.
if (versionOf(data) === null) {
throw new Error('attachment carries no report version')
}
return data
}
export async function extractReportJson(
pdfDoc: PDFDocument,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
const data = await readAttachedDocument(pdfDoc)
try {
return {
...readReportDocument(data, map),
migrated: versionOf(data) !== REPORT_VERSION,
}
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new IncompatibleReportVersionError(err.foundVersion)
}
throw err
}
}
async function attachmentBytes(pdfDoc: PDFDocument): Promise<Uint8Array> {
const maybeApi = pdfDoc as unknown as {
getAttachments?: () => Array<{ name: string; data: Uint8Array }>
}
if (typeof maybeApi.getAttachments === 'function') { if (typeof maybeApi.getAttachments === 'function') {
const list = maybeApi.getAttachments() const list = maybeApi.getAttachments()
if (list && list.length) { if (list && list.length) {
const hit = list.find((a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json')) ?? list[0] const hit =
return parseAttachment(hit.data) list.find(
(a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json'),
) ?? list[0]
return hit.data
} }
} }
const fallback = await traverseForJsonAttachment(pdfDoc) const fallback = await traverseForJsonAttachment(pdfDoc)
if (!fallback) throw new Error('No osteo-report attachment found') if (!fallback) throw new Error('No osteo-report attachment found')
return parseAttachment(fallback) return fallback
} }
function parseAttachment(bytes: Uint8Array): Report { /** Hard ceiling on an attachment (inflated or not): a report is a few hundred KB at most. */
const text = new TextDecoder().decode(bytes) const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024
const data: unknown = JSON.parse(text)
if ( function versionOf(data: unknown): number | null {
data !== null && if (data === null || typeof data !== 'object') return null
typeof data === 'object' && const v = (data as { version?: unknown }).version
'version' in data && return typeof v === 'number' ? v : null
typeof (data as { version: unknown }).version === 'number' &&
(data as { version: number }).version !== 2
) {
throw new IncompatibleReportVersionError((data as { version: number }).version)
}
return ReportSchema.parse(data)
} }
interface RawObj { interface RawObj {
@@ -65,13 +118,17 @@ interface RawObj {
* Hard ceiling on inflated attachment size. A valid report JSON is far * Hard ceiling on inflated attachment size. A valid report JSON is far
* smaller; anything bigger is a decompression bomb or corruption. * smaller; anything bigger is a decompression bomb or corruption.
*/ */
const MAX_INFLATED_BYTES = 16 * 1024 * 1024 const MAX_INFLATED_BYTES = MAX_ATTACHMENT_BYTES
/** Exported for tests. Returns null on failure or when the cap is exceeded. */ /** Exported for tests. Returns null on failure or when the cap is exceeded. */
export async function inflateFlate(bytes: Uint8Array): Promise<Uint8Array | null> { export async function inflateFlate(
bytes: Uint8Array,
): Promise<Uint8Array | null> {
if (typeof DecompressionStream === 'undefined') return null if (typeof DecompressionStream === 'undefined') return null
try { try {
const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate')) const stream = new Blob([bytes as BlobPart])
.stream()
.pipeThrough(new DecompressionStream('deflate'))
const reader = stream.getReader() const reader = stream.getReader()
const chunks: Uint8Array[] = [] const chunks: Uint8Array[] = []
let total = 0 let total = 0
@@ -99,13 +156,20 @@ export async function inflateFlate(bytes: Uint8Array): Promise<Uint8Array | null
function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean { function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean {
for (const [k, v] of entries) { for (const [k, v] of entries) {
if (String(k).includes('Filter') && String(v).includes('FlateDecode')) return true if (String(k).includes('Filter') && String(v).includes('FlateDecode'))
return true
} }
return false return false
} }
async function traverseForJsonAttachment(pdfDoc: PDFDocument): Promise<Uint8Array | null> { async function traverseForJsonAttachment(
const ctx = (pdfDoc as unknown as { context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> } }).context pdfDoc: PDFDocument,
): Promise<Uint8Array | null> {
const ctx = (
pdfDoc as unknown as {
context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> }
}
).context
for (const [, obj] of ctx.enumerateIndirectObjects()) { for (const [, obj] of ctx.enumerateIndirectObjects()) {
if (!obj || typeof obj !== 'object') continue if (!obj || typeof obj !== 'object') continue
if (!(obj.contents instanceof Uint8Array)) continue if (!(obj.contents instanceof Uint8Array)) continue
@@ -115,9 +179,13 @@ async function traverseForJsonAttachment(pdfDoc: PDFDocument): Promise<Uint8Arra
for (const [k, v] of entries) { for (const [k, v] of entries) {
const ks = String(k) const ks = String(k)
const vs = String(v) const vs = String(v)
if (ks.includes('Type') && vs.includes('EmbeddedFile')) isEmbeddedFile = true if (ks.includes('Type') && vs.includes('EmbeddedFile'))
isEmbeddedFile = true
// PDF name syntax escapes '/' as '#2F': /application#2Fjson // PDF name syntax escapes '/' as '#2F': /application#2Fjson
if (ks.includes('Subtype') && (vs.includes('application/json') || vs.includes('application#2Fjson'))) { if (
ks.includes('Subtype') &&
(vs.includes('application/json') || vs.includes('application#2Fjson'))
) {
isJsonSubtype = true isJsonSubtype = true
} }
} }
+18 -90
View File
@@ -1,94 +1,32 @@
import { PDFDocument } from 'pdf-lib' import { PDFDocument } from 'pdf-lib'
import type { Report } from '@/domain/schema/report' import type { Report } from '@faunosteo/domain'
import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Locale } from '@/i18n/types' import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n' import { getDict } from '@/i18n'
import type { SheetIndex } from '@/services/sheetIndex'
import { embedFonts } from './fonts' import { embedFonts } from './fonts'
import { addObservationPage } from './render/observationPage' import { addObservationPage } from './render/observationPage'
import { addConclusionPage } from './render/conclusionPage' import { addConclusionPage } from './render/conclusionPage'
import { attachReportJson } from './attachment' import { attachReportJson } from './attachment'
import { drawFooter } from './render/footer' import { drawFooter } from './render/footer'
import { loadFaunosteoLogo, loadFaunosteoComLogo, loadZenqualityLogo } from './render/logo' import {
loadFaunosteoLogo,
loadFaunosteoComLogo,
loadZenqualityLogo,
} from './render/logo'
import { rasterizeSvg } from './render/svgToPng' import { rasterizeSvg } from './render/svgToPng'
import { loadSvg } from '@/anatomy/svgLoader'
import { parseSvgBones } from '@/anatomy/svgConvention'
import { getSpecies } from '@/domain/species/registry'
export interface PdfExportOptions { export interface PdfExportOptions {
locale: Locale locale: Locale
} }
/** Bilingual label pair surfaced to the PDF render layer. */
export interface ZoneLabelPair {
fr: string
en: string
}
/** /**
* Builds a `data-anno-id → { fr, en }` map by parsing every SVG the * Exports a report to PDF from the in-memory document and the loaded sheet:
* species manifest knows about. Each SVG is loaded independently so a * labels and drawings come from the sheet, nothing is fetched except the
* failure on the detail asset never prevents the main labels (or vice * partner logos. The v3 document is attached for re-import.
* versa) from making it into the returned map. The PDF render layer
* picks the locale-appropriate label at draw time (falls back to the
* opposite language when one side is missing).
*
* Exported for unit testing — the editor calls it indirectly via
* `exportReportToPdf`.
*/ */
export async function buildZoneLabels(
report: Report,
): Promise<Map<string, ZoneLabelPair>> {
const labels = new Map<string, ZoneLabelPair>()
const species = getSpecies(report.animal.speciesId)
if (!species) return labels
const sources: string[] = [
species.mainSvg,
...Object.values(species.details),
]
await Promise.all(
sources.map(async (src) => {
try {
const root = await loadSvg(src)
parseSvgBones(root).forEach((b, id) => {
const existing = labels.get(id)
if (existing) {
if (!existing.fr && b.fr) existing.fr = b.fr
if (!existing.en && b.en) existing.en = b.en
} else if (b.fr || b.en) {
labels.set(id, { fr: b.fr, en: b.en })
}
})
} catch (err) {
console.warn(`buildZoneLabels: skipped ${src}`, err)
}
}),
)
return labels
}
/**
* Loads the parsed findings catalog for a species so the PDF renderer
* can resolve a Finding's `zoneId` (JSON catalog key) back to its
* human-readable zone name.
*/
async function loadSpeciesFindings(
speciesId: string,
): Promise<SpeciesFindings | null> {
const species = getSpecies(speciesId)
if (!species) return null
try {
const m = await species.findings()
return m.default
} catch (err) {
console.warn(`loadSpeciesFindings: failed for ${speciesId}`, err)
return null
}
}
export async function exportReportToPdf( export async function exportReportToPdf(
report: Report, report: Report,
sheet: SheetIndex,
opts: PdfExportOptions, opts: PdfExportOptions,
): Promise<Uint8Array> { ): Promise<Uint8Array> {
const { locale } = opts const { locale } = opts
@@ -101,53 +39,43 @@ export async function exportReportToPdf(
pdfDoc.setModificationDate(new Date()) pdfDoc.setModificationDate(new Date())
const fonts = await embedFonts(pdfDoc) const fonts = await embedFonts(pdfDoc)
const zoneLabels = await buildZoneLabels(report)
const findingsTree = await loadSpeciesFindings(report.animal.speciesId)
let headerLogoPdf = null let headerLogoPdf = null
let footerLogoPdf = null let footerLogoPdf = null
let zqLogoPdfImage = null let zqLogoPdfImage = null
let pawsLogoPdf = null let pawsLogoPdf = null
try { try {
const bytes = await loadFaunosteoLogo() headerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoLogo())
headerLogoPdf = await pdfDoc.embedPng(bytes)
} catch (err) { } catch (err) {
console.warn('Faunosteo logo embed failed:', err) console.warn('Faunosteo logo embed failed:', err)
} }
try { try {
const bytes = await loadFaunosteoComLogo() footerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoComLogo())
footerLogoPdf = await pdfDoc.embedPng(bytes)
} catch (err) { } catch (err) {
console.warn('Faunosteo -com logo embed failed:', err) console.warn('Faunosteo -com logo embed failed:', err)
} }
try { try {
const zqPngBytes = await loadZenqualityLogo() zqLogoPdfImage = await pdfDoc.embedPng(await loadZenqualityLogo())
zqLogoPdfImage = await pdfDoc.embedPng(zqPngBytes)
} catch (err) { } catch (err) {
console.warn('ZenQuality logo embed failed:', err) console.warn('ZenQuality logo embed failed:', err)
} }
try { try {
const resp = await fetch('/Paws_in_harmony.svg') const resp = await fetch('/Paws_in_harmony.svg')
if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`) if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`)
const svgText = await resp.text() pawsLogoPdf = await pdfDoc.embedPng(await rasterizeSvg(await resp.text()))
const pawsPngBytes = await rasterizeSvg(svgText)
pawsLogoPdf = await pdfDoc.embedPng(pawsPngBytes)
} catch (err) { } catch (err) {
console.warn('Paws in Harmony logo embed failed:', err) console.warn('Paws in Harmony logo embed failed:', err)
} }
const headerAssets = { logoPng: headerLogoPdf } const headerAssets = { logoPng: headerLogoPdf }
const totalObs = report.observations.length for (let i = 0; i < report.observations.length; i += 1) {
for (let i = 0; i < totalObs; i += 1) {
await addObservationPage({ await addObservationPage({
pdfDoc, pdfDoc,
report, report,
observation: report.observations[i], observation: report.observations[i]!,
obsIndex: i, obsIndex: i,
fonts, fonts,
zoneLabels, sheet,
findingsTree,
locale, locale,
headerAssets, headerAssets,
}) })
+21 -5
View File
@@ -1,6 +1,10 @@
import { PDFDocument } from 'pdf-lib' import { PDFDocument } from 'pdf-lib'
import { extractReportJson, IncompatibleReportVersionError } from './attachment' import type { ReportMigrationMap } from '@faunosteo/domain'
import type { Report } from '@/domain/schema/report' import {
extractReportJson,
IncompatibleReportVersionError,
type ExtractedReport,
} from './attachment'
export type ImportErrorKind = export type ImportErrorKind =
| 'invalid_pdf' | 'invalid_pdf'
@@ -15,14 +19,26 @@ export type ImportErrorKind =
export class ImportError extends Error { export class ImportError extends Error {
constructor( constructor(
public readonly kind: ImportErrorKind, public readonly kind: ImportErrorKind,
public readonly foundVersion?: number, public readonly foundVersion?: number | null,
) { ) {
super(kind) super(kind)
this.name = 'ImportError' this.name = 'ImportError'
} }
} }
export async function importReportFromPdf(pdfBytes: Uint8Array): Promise<Report> { /** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */
export const MAX_PDF_BYTES = 50 * 1024 * 1024
/**
* Reads a Faunosteo PDF back into a report document (v3, or v2 migrated
* through the reference sheet's map). The outcome says whether a migration
* happened and how many zones or findings it could not place.
*/
export async function importReportFromPdf(
pdfBytes: Uint8Array,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
if (pdfBytes.byteLength > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
let pdfDoc: PDFDocument let pdfDoc: PDFDocument
try { try {
pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true }) pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
@@ -30,7 +46,7 @@ export async function importReportFromPdf(pdfBytes: Uint8Array): Promise<Report>
throw new ImportError('invalid_pdf') throw new ImportError('invalid_pdf')
} }
try { try {
return await extractReportJson(pdfDoc) return await extractReportJson(pdfDoc, map)
} catch (err) { } catch (err) {
if (err instanceof IncompatibleReportVersionError) { if (err instanceof IncompatibleReportVersionError) {
throw new ImportError('incompatible_version', err.foundVersion) throw new ImportError('incompatible_version', err.foundVersion)
+14 -4
View File
@@ -1,6 +1,6 @@
import { PageSizes, type PDFDocument } from 'pdf-lib' import { PageSizes, type PDFDocument } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts' import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report' import type { Report } from '@faunosteo/domain'
import type { Locale } from '@/i18n/types' import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n' import { getDict } from '@/i18n'
import { drawHeader, type HeaderAssets } from './header' import { drawHeader, type HeaderAssets } from './header'
@@ -61,9 +61,19 @@ export async function addConclusionPage(
let cursorY = titleY - SECTION_TOP_GAP let cursorY = titleY - SECTION_TOP_GAP
const sections: Array<{ label: string; body: string; color?: typeof COLOR_INK }> = [ const sections: Array<{
{ label: dict['pdf.section.conclusion'], body: report.conclusion || dict['pdf.empty'] }, label: string
{ label: dict['pdf.section.recommendations'], body: report.recommendations || dict['pdf.empty'] }, body: string
color?: typeof COLOR_INK
}> = [
{
label: dict['pdf.section.conclusion'],
body: report.conclusion || dict['pdf.empty'],
},
{
label: dict['pdf.section.recommendations'],
body: report.recommendations || dict['pdf.empty'],
},
] ]
if (report.nextAppointment) { if (report.nextAppointment) {
const txt = const txt =
+10 -3
View File
@@ -55,7 +55,10 @@ export function drawFooter(
} }
const poweredLabel = `${dict['footer.powered_by']} ` const poweredLabel = `${dict['footer.powered_by']} `
const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize(poweredLabel, FONT_SIZE) const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize(
poweredLabel,
FONT_SIZE,
)
const zqLogoW = 70 const zqLogoW = 70
const zqLogoH = 16 const zqLogoH = 16
const zqFallback = 'zenquality.fr' const zqFallback = 'zenquality.fr'
@@ -106,12 +109,16 @@ export function drawFooter(
} }
const partnerLabel = `${dict['footer.in_partnership']} ` const partnerLabel = `${dict['footer.in_partnership']} `
const partnerLabelW = fonts.bodyRegular.widthOfTextAtSize(partnerLabel, FONT_SIZE) const partnerLabelW = fonts.bodyRegular.widthOfTextAtSize(
partnerLabel,
FONT_SIZE,
)
const partnerUrl = 'https://www.instagram.com/paws.iin.harmony' const partnerUrl = 'https://www.instagram.com/paws.iin.harmony'
if (assets.pawsLogoPng) { if (assets.pawsLogoPng) {
const pawsLogoH = 16 const pawsLogoH = 16
const pawsLogoW = pawsLogoH * (assets.pawsLogoPng.width / assets.pawsLogoPng.height) const pawsLogoW =
pawsLogoH * (assets.pawsLogoPng.width / assets.pawsLogoPng.height)
const partnerX = width - MARGIN_X - partnerLabelW - pawsLogoW const partnerX = width - MARGIN_X - partnerLabelW - pawsLogoW
page.drawText(partnerLabel, { page.drawText(partnerLabel, {
x: partnerX, x: partnerX,
+1 -1
View File
@@ -1,6 +1,6 @@
import type { PDFPage, PDFImage } from 'pdf-lib' import type { PDFPage, PDFImage } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts' import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report' import type { Report } from '@faunosteo/domain'
import type { Locale } from '@/i18n/types' import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n' import { getDict } from '@/i18n'
import { formatDate } from '@/lib/dates' import { formatDate } from '@/lib/dates'
+168 -192
View File
@@ -1,19 +1,25 @@
import { rgb, PageSizes, type PDFDocument, type PDFPage, type PDFImage } from 'pdf-lib' import {
rgb,
PageSizes,
type PDFDocument,
type PDFPage,
type PDFImage,
} from 'pdf-lib'
import type {
Finding,
Observation,
Report,
ReportZone,
Severity,
} from '@faunosteo/domain'
import type { EmbeddedFonts } from '@/pdf/fonts' import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report'
import type { Finding, Observation } from '@/domain/schema/observation'
import type { SpeciesFindings } from '@/domain/schema/findings'
import type { SpeciesManifest } from '@/domain/species/types'
import type { Locale, Dict } from '@/i18n/types' import type { Locale, Dict } from '@/i18n/types'
import { getDict } from '@/i18n' import { getDict } from '@/i18n'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
import type { ZoneLabelPair } from '@/pdf/export' import { buildViewSvg } from '@/anatomy/drawing'
import { drawHeader, type HeaderAssets } from './header' import { drawHeader, type HeaderAssets } from './header'
import { rasterizeSvg } from './svgToPng' import { rasterizeSvg } from './svgToPng'
import { wrapLines } from './text' import { wrapLines } from './text'
import { loadSvg } from '@/anatomy/svgLoader'
import { parseSvgBones } from '@/anatomy/svgConvention'
import { getSpecies } from '@/domain/species/registry'
import { import {
MARGIN_X, MARGIN_X,
EYEBROW_Y_OFFSET, EYEBROW_Y_OFFSET,
@@ -39,10 +45,10 @@ const SECTION_BLOCK_GAP = 10
const COLOR_WHITE = rgb(1, 1, 1) const COLOR_WHITE = rgb(1, 1, 1)
const SEVERITY_BG: Record<string, ReturnType<typeof rgb>> = { const SEVERITY_BG: Record<Severity, ReturnType<typeof rgb>> = {
'légère': rgb(0.55, 0.65, 0.45), mild: rgb(0.55, 0.65, 0.45),
'modérée': rgb(0.85, 0.55, 0.18), moderate: rgb(0.85, 0.55, 0.18),
'sévère': rgb(0.78, 0.20, 0.20), severe: rgb(0.78, 0.2, 0.2),
} }
const SECTION_TEXT_SIZE = 10 const SECTION_TEXT_SIZE = 10
@@ -70,7 +76,7 @@ function countSegmentedLines(
let x = 0 let x = 0
for (let i = 0; i < items.length; i += 1) { for (let i = 0; i < items.length; i += 1) {
const itemW = fonts.bodyRegular.widthOfTextAtSize( const itemW = fonts.bodyRegular.widthOfTextAtSize(
items[i], items[i]!,
SECTION_TEXT_SIZE, SECTION_TEXT_SIZE,
) )
if (x + itemW > maxWidth && x > 0) { if (x + itemW > maxWidth && x > 0) {
@@ -92,8 +98,7 @@ function countSegmentedLines(
/** /**
* Renders a list of items separated by a visibly larger accent-coloured * Renders a list of items separated by a visibly larger accent-coloured
* bullet. Returns the cursor y *below* the last line drawn so the * bullet. Returns the cursor y *below* the last line drawn.
* caller can keep advancing the page cursor like a plain wrapLines run.
*/ */
function drawSegmentedText( function drawSegmentedText(
page: PDFPage, page: PDFPage,
@@ -105,15 +110,11 @@ function drawSegmentedText(
): number { ): number {
if (items.length === 0) return startY - TEXT_LINE_HEIGHT if (items.length === 0) return startY - TEXT_LINE_HEIGHT
const sepW = separatorWidth(fonts) const sepW = separatorWidth(fonts)
// The bullet's larger size pushes its baseline above the surrounding
// text. Shift it down a touch so it visually centers on the x-height
// of the items it separates.
const sepBaselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3 const sepBaselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3
let x = startX let x = startX
let y = startY let y = startY
for (let i = 0; i < items.length; i += 1) { for (let i = 0; i < items.length; i += 1) {
const item = items[i] const item = items[i]!
const itemW = fonts.bodyRegular.widthOfTextAtSize(item, SECTION_TEXT_SIZE) const itemW = fonts.bodyRegular.widthOfTextAtSize(item, SECTION_TEXT_SIZE)
if (x + itemW > startX + maxWidth && x > startX) { if (x + itemW > startX + maxWidth && x > startX) {
x = startX x = startX
@@ -150,22 +151,17 @@ const SVG_NS = 'http://www.w3.org/2000/svg'
const HALO_FILTER_ID = 'osteo-halo' const HALO_FILTER_ID = 'osteo-halo'
/** /**
* Adds a Gaussian-blur "halo" filter to the SVG defs the first time it * Adds a Gaussian-blur "halo" filter so the highlighted markers stay
* is called on a root. The filter widens the visible footprint of the * visible on the whole-animal view once rasterised at print scale.
* highlighted zones on the whole-animal view, where individual point
* markers are otherwise tiny relative to the full body silhouette.
*/ */
function ensureHaloFilter(root: SVGSVGElement): void { function ensureHaloFilter(root: SVGSVGElement): void {
const doc = root.ownerDocument const doc = root.ownerDocument
if (!doc) return if (root.querySelector(`#${HALO_FILTER_ID}`)) return
if (doc.getElementById(HALO_FILTER_ID)) return
let defs = root.querySelector('defs') let defs = root.querySelector('defs')
if (!defs) { if (!defs) {
defs = doc.createElementNS(SVG_NS, 'defs') defs = doc.createElementNS(SVG_NS, 'defs')
root.insertBefore(defs, root.firstChild) root.insertBefore(defs, root.firstChild)
} }
const filter = doc.createElementNS(SVG_NS, 'filter') const filter = doc.createElementNS(SVG_NS, 'filter')
filter.setAttribute('id', HALO_FILTER_ID) filter.setAttribute('id', HALO_FILTER_ID)
filter.setAttribute('x', '-100%') filter.setAttribute('x', '-100%')
@@ -173,84 +169,63 @@ function ensureHaloFilter(root: SVGSVGElement): void {
filter.setAttribute('width', '300%') filter.setAttribute('width', '300%')
filter.setAttribute('height', '300%') filter.setAttribute('height', '300%')
filter.setAttribute('filterUnits', 'userSpaceOnUse') filter.setAttribute('filterUnits', 'userSpaceOnUse')
// Two-stage blur: a wide outer halo for "spotted from across the
// room" visibility, plus a tighter inner halo that keeps the
// selection anchored to the original point so it doesn't dissolve.
const wide = doc.createElementNS(SVG_NS, 'feGaussianBlur') const wide = doc.createElementNS(SVG_NS, 'feGaussianBlur')
wide.setAttribute('in', 'SourceGraphic') wide.setAttribute('in', 'SourceGraphic')
wide.setAttribute('stdDeviation', '18') wide.setAttribute('stdDeviation', '18')
wide.setAttribute('result', 'haloWide') wide.setAttribute('result', 'haloWide')
filter.appendChild(wide) filter.appendChild(wide)
const tight = doc.createElementNS(SVG_NS, 'feGaussianBlur') const tight = doc.createElementNS(SVG_NS, 'feGaussianBlur')
tight.setAttribute('in', 'SourceGraphic') tight.setAttribute('in', 'SourceGraphic')
tight.setAttribute('stdDeviation', '8') tight.setAttribute('stdDeviation', '8')
tight.setAttribute('result', 'haloTight') tight.setAttribute('result', 'haloTight')
filter.appendChild(tight) filter.appendChild(tight)
const merge = doc.createElementNS(SVG_NS, 'feMerge') const merge = doc.createElementNS(SVG_NS, 'feMerge')
// Stack the wide halo three times so its contribution survives the for (const input of [
// SVG → PNG → pdf-lib pipeline (each pass attenuates alpha) and 'haloWide',
// still reads as a strong glow at print scale. 'haloWide',
for (let i = 0; i < 3; i += 1) { 'haloWide',
'haloTight',
'haloTight',
'SourceGraphic',
]) {
const n = doc.createElementNS(SVG_NS, 'feMergeNode') const n = doc.createElementNS(SVG_NS, 'feMergeNode')
n.setAttribute('in', 'haloWide') n.setAttribute('in', input)
merge.appendChild(n) merge.appendChild(n)
} }
for (let i = 0; i < 2; i += 1) {
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
n.setAttribute('in', 'haloTight')
merge.appendChild(n)
}
const source = doc.createElementNS(SVG_NS, 'feMergeNode')
source.setAttribute('in', 'SourceGraphic')
merge.appendChild(source)
filter.appendChild(merge) filter.appendChild(merge)
defs.appendChild(filter) defs.appendChild(filter)
} }
async function colorizedSvgString( /**
speciesSvgPath: string, * The view rendered from the sheet with the observation's zones of that
* view highlighted (legacy picture: accent fill, halo on the main view,
* other markers hidden, no data attributes left).
*/
export function highlightedViewSvg(
sheet: SheetIndex,
viewId: string,
observation: Observation, observation: Observation,
sourceDetailId: string | undefined, ): string {
): Promise<string> { const selected = new Set(
const root = await loadSvg(speciesSvgPath)
const bones = parseSvgBones(root)
const selectedIds = new Set(
observation.zones observation.zones
.filter((z) => z.detailSourceId === sourceDetailId) .filter((z) => z.viewId === viewId)
.map((z) => z.boneId), .map((z) => z.annotationId),
) )
const root = buildViewSvg(sheet, viewId, new Map())
// Whole-animal view: zone hitboxes are tiny markers on a big const applyHalo = sheet.view(viewId)?.kind === 'main'
// silhouette, so we apply a blurred halo to make selections pop.
// Detail views are already zoomed in and don't need it.
const applyHalo = sourceDetailId === undefined
if (applyHalo) ensureHaloFilter(root) if (applyHalo) ensureHaloFilter(root)
root.querySelectorAll<Element>('[data-anno-id]').forEach((el) => {
bones.forEach((bone, id) => { if (selected.has(el.getAttribute('data-anno-id') ?? '')) {
const selected = selectedIds.has(id)
bone.els.forEach((el) => {
if (selected) {
el.setAttribute('fill', '#b85a3f') el.setAttribute('fill', '#b85a3f')
el.setAttribute('fill-opacity', '0.85') el.setAttribute('fill-opacity', '0.85')
if (applyHalo) { if (applyHalo) el.setAttribute('filter', `url(#${HALO_FILTER_ID})`)
el.setAttribute('filter', `url(#${HALO_FILTER_ID})`)
}
} else { } else {
el.setAttribute('display', 'none') el.setAttribute('display', 'none')
} }
})
})
root.querySelectorAll('[data-anno-id]').forEach((el) => {
Array.from(el.attributes) Array.from(el.attributes)
.filter((a) => a.name.startsWith('data-anno-')) .filter((a) => a.name.startsWith('data-'))
.forEach((a) => el.removeAttribute(a.name)) .forEach((a) => el.removeAttribute(a.name))
}) })
return new XMLSerializer().serializeToString(root) return new XMLSerializer().serializeToString(root)
} }
@@ -261,49 +236,40 @@ export interface ObservationPageContext {
observation: Observation observation: Observation
obsIndex: number obsIndex: number
fonts: EmbeddedFonts fonts: EmbeddedFonts
zoneLabels: Map<string, ZoneLabelPair> sheet: SheetIndex
findingsTree: SpeciesFindings | null
locale: Locale locale: Locale
headerAssets: HeaderAssets headerAssets: HeaderAssets
} }
/** Shared draw handles threaded through the observation-page sub-renderers. */
interface PageDrawContext { interface PageDrawContext {
page: PDFPage page: PDFPage
fonts: EmbeddedFonts fonts: EmbeddedFonts
width: number width: number
} }
/** One rasterized anatomy view (main body or a detail popup) ready to embed. */
interface RenderedImage { interface RenderedImage {
label: string label: string
img: PDFImage img: PDFImage
aspect: number aspect: number
} }
/** One label/value block drawn under the images (zones, findings, comment...). */
interface ObservationSection { interface ObservationSection {
label: string label: string
value: string value: string
} }
/**
* Draws the eyebrow, index/severity title, and accent rule for an
* observation page. Returns titleY so callers can lay out the content
* below it.
*/
function drawObservationTitleBlock( function drawObservationTitleBlock(
ctx: PageDrawContext, ctx: PageDrawContext,
dict: Dict, dict: Dict,
obsIndex: number, obsIndex: number,
severity: Observation['severity'], severity: Severity | undefined,
): number { ): number {
const { page, fonts } = ctx const { page, fonts } = ctx
const { height } = page.getSize() const { height } = page.getSize()
const eyebrowY = height - EYEBROW_Y_OFFSET const eyebrowY = height - EYEBROW_Y_OFFSET
const titleY = height - TITLE_Y_OFFSET const titleY = height - TITLE_Y_OFFSET
const obsLabel = String(obsIndex + 1).padStart(2, '0') const obsLabel = String(obsIndex + 1).padStart(2, '0')
page.drawText(dict['pdf.eyebrow.observation'], { page.drawText(dict['pdf.eyebrow.observation']!, {
x: MARGIN_X, x: MARGIN_X,
y: eyebrowY, y: eyebrowY,
size: 9, size: 9,
@@ -319,14 +285,11 @@ function drawObservationTitleBlock(
}) })
if (severity) { if (severity) {
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22) const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
const sev = severity const sevText = (dict[`severity.${severity}`] ?? severity).toUpperCase()
const sevLabel = dict[`severity.${sev}`] ?? sev
const sevText = sevLabel.toUpperCase()
const sevSize = 9 const sevSize = 9
const sevTextW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize)
const padX = 8 const padX = 8
const padY = 4 const padY = 4
const pillW = sevTextW + padX * 2 const pillW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize) + padX * 2
const pillH = sevSize + padY * 2 const pillH = sevSize + padY * 2
const pillX = MARGIN_X + numW + 14 const pillX = MARGIN_X + numW + 14
const pillY = titleY + 4 const pillY = titleY + 4
@@ -335,7 +298,7 @@ function drawObservationTitleBlock(
y: pillY, y: pillY,
width: pillW, width: pillW,
height: pillH, height: pillH,
color: SEVERITY_BG[sev] ?? COLOR_MUTED, color: SEVERITY_BG[severity] ?? COLOR_MUTED,
}) })
page.drawText(sevText, { page.drawText(sevText, {
x: pillX + padX, x: pillX + padX,
@@ -354,100 +317,97 @@ function drawObservationTitleBlock(
return titleY return titleY
} }
/** /** Every view the observation touches, main first, each rasterised with its highlights. */
* Resolves the main-body view plus every detail-popup view referenced by
* the observation, rasterizing each to a PNG ready for pdf-lib.
*/
async function buildObservationImages( async function buildObservationImages(
pdfDoc: PDFDocument, pdfDoc: PDFDocument,
species: SpeciesManifest, sheet: SheetIndex,
observation: Observation, observation: Observation,
locale: Locale,
dict: Dict, dict: Dict,
): Promise<RenderedImage[]> { ): Promise<RenderedImage[]> {
const hasMainZones = observation.zones.some((z) => !z.detailSourceId) const viewIds = [...new Set(observation.zones.map((z) => z.viewId))]
const detailIds = Array.from( .filter((id) => sheet.view(id))
new Set(observation.zones.map((z) => z.detailSourceId).filter(Boolean) as string[]), .sort(
(a, b) =>
Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id),
) )
const items: Array<{ label: string; src: string; sourceId: string | undefined }> = []
if (hasMainZones) {
items.push({ label: dict['pdf.view.general'], src: species.mainSvg, sourceId: undefined })
}
for (const detailId of detailIds) {
const detailPath = species.details[detailId]
if (!detailPath) continue
items.push({
label: `${dict['pdf.view.detail_prefix']}${detailId.toUpperCase()}`,
src: detailPath,
sourceId: detailId,
})
}
return Promise.all( return Promise.all(
items.map(async (it) => { viewIds.map(async (viewId) => {
const svgStr = await colorizedSvgString(it.src, observation, it.sourceId) const view = sheet.view(viewId)!
const png = await rasterizeSvg(svgStr) const label =
view.kind === 'main'
? dict['pdf.view.general']!
: `${dict['pdf.view.detail_prefix']}${pickLabel(view.name, locale).toUpperCase()}`
const png = await rasterizeSvg(
highlightedViewSvg(sheet, viewId, observation),
)
const img = await pdfDoc.embedPng(png) const img = await pdfDoc.embedPng(png)
const aspect = img.width > 0 ? img.height / img.width : 0.6 return {
return { label: it.label, img, aspect } label,
img,
aspect: img.width > 0 ? img.height / img.width : 0.6,
}
}), }),
) )
} }
/** Renders the "Zones" section value: bilingual labels + vertebra/side suffixes. */ function zoneText(z: ReportZone, sheet: SheetIndex, locale: Locale): string {
const annotation = sheet.annotation(z.annotationId)
if (annotation) return pickLabel(sheet.name(annotation), locale)
const snapshot =
locale === 'en'
? z.labelEnSnapshot || z.labelFrSnapshot
: z.labelFrSnapshot || z.labelEnSnapshot
return snapshot || z.annotationId
}
function describeObservationZones( function describeObservationZones(
zones: Observation['zones'], zones: ReportZone[],
zoneLabels: Map<string, ZoneLabelPair>, sheet: SheetIndex,
locale: Locale, locale: Locale,
dict: Dict, dict: Dict,
): string { ): string {
return zones return zones
.map((z) => { .map((z) => {
const pair = zoneLabels.get(z.boneId)
const label = pickLocaleLabel(pair?.fr, pair?.en, locale, z.boneId)
const v = z.vertebrae?.length const v = z.vertebrae?.length
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})` ? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
: '' : ''
const side = z.side const side = z.side
? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})` ? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})`
: '' : ''
return `${label}${v}${side}` return `${zoneText(z, sheet, locale)}${v}${side}`
}) })
.join(' · ') .join(' · ')
} }
/** Groups findings by zone+side, one label/value section entry per group. */ function findingZoneName(
zoneId: string,
sheet: SheetIndex,
locale: Locale,
): string {
const zone = sheet.findingZone(zoneId)
return zone ? pickLabel(zone.name, locale) : zoneId
}
/** Groups findings by zone+side, one section per group; snapshots give the text. */
function buildFindingsSections( function buildFindingsSections(
findings: Finding[], findings: Finding[],
findingsTree: SpeciesFindings | null, sheet: SheetIndex,
locale: Locale, locale: Locale,
dict: Dict, dict: Dict,
): ObservationSection[] { ): ObservationSection[] {
const byZoneSide = new Map<string, Finding[]>() const byZoneSide = new Map<string, Finding[]>()
for (const f of findings) { for (const f of findings) {
const key = f.side ? `${f.zoneId}:${f.side}` : f.zoneId const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId
const list = byZoneSide.get(key) byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f])
if (list) {
list.push(f)
} else {
byZoneSide.set(key, [f])
} }
}
const sections: ObservationSection[] = [] const sections: ObservationSection[] = []
for (const [key, group] of byZoneSide) { for (const [key, group] of byZoneSide) {
const zoneId = key.split(':')[0] const zoneId = key.split(':')[0]!
const side = group[0]?.side const side = group[0]?.side
const zoneTree = findingsTree?.zones[zoneId] let zoneName = findingZoneName(zoneId, sheet, locale)
let zoneName = zoneTree if (side)
? locale === 'en' zoneName = `${zoneName} (${dict[side === 'left' ? 'lateral.left' : 'lateral.right']})`
? zoneTree.name_en
: zoneTree.name_fr
: zoneId
if (side) {
const sideLabel = dict[side === 'left' ? 'lateral.left' : 'lateral.right']
zoneName = `${zoneName} (${sideLabel})`
}
const value = group const value = group
.map((f) => { .map((f) => {
const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
@@ -462,37 +422,46 @@ function buildFindingsSections(
return sections return sections
} }
/** Assembles the ordered label/value sections drawn below the images. */
function buildObservationSections( function buildObservationSections(
observation: Observation, observation: Observation,
zoneLabels: Map<string, ZoneLabelPair>, sheet: SheetIndex,
findingsTree: SpeciesFindings | null,
locale: Locale, locale: Locale,
dict: Dict, dict: Dict,
): ObservationSection[] { ): ObservationSection[] {
const zonesText = describeObservationZones(observation.zones, zoneLabels, locale, dict) const zonesText = describeObservationZones(
observation.zones,
sheet,
locale,
dict,
)
const sections: ObservationSection[] = [ const sections: ObservationSection[] = [
{ label: dict['pdf.section.zones'], value: zonesText || dict['pdf.empty'] }, {
label: dict['pdf.section.zones']!,
value: zonesText || dict['pdf.empty']!,
},
...buildFindingsSections(observation.findings, sheet, locale, dict),
] ]
sections.push(...buildFindingsSections(observation.findings, findingsTree, locale, dict))
if (observation.freeTextFindings.length) { if (observation.freeTextFindings.length) {
sections.push({ sections.push({
label: dict['pdf.section.free_findings'], label: dict['pdf.section.free_findings']!,
value: observation.freeTextFindings.join(' · '), value: observation.freeTextFindings.join(' · '),
}) })
} }
if (observation.severity) { if (observation.severity) {
const sevLabel = dict[`severity.${observation.severity}`] ?? observation.severity sections.push({
sections.push({ label: dict['pdf.section.severity'], value: sevLabel }) label: dict['pdf.section.severity']!,
value: dict[`severity.${observation.severity}`] ?? observation.severity,
})
} }
if (observation.comment.trim()) { if (observation.comment.trim()) {
sections.push({ label: dict['pdf.section.comment'], value: observation.comment.trim() }) sections.push({
label: dict['pdf.section.comment']!,
value: observation.comment.trim(),
})
} }
return sections return sections
} }
/** Estimates the vertical space the given sections will occupy once drawn. */
function estimateSectionsHeight( function estimateSectionsHeight(
sections: ObservationSection[], sections: ObservationSection[],
fonts: EmbeddedFonts, fonts: EmbeddedFonts,
@@ -503,16 +472,13 @@ function estimateSectionsHeight(
const lineCount = value.includes(' · ') const lineCount = value.includes(' · ')
? countSegmentedLines(value.split(' · '), fonts, maxTextW) ? countSegmentedLines(value.split(' · '), fonts, maxTextW)
: wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length : wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length
h += SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP h +=
SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP
} }
return h return h
} }
/** /** Lays out the (up to 2-column) image grid; returns the cursor y below it. */
* Lays out and draws the (up to 2-column) image grid for an observation
* page. Returns the cursor y directly below the images — unchanged from
* startY when there is nothing to draw.
*/
function drawObservationImageGrid( function drawObservationImageGrid(
ctx: PageDrawContext, ctx: PageDrawContext,
rendered: RenderedImage[], rendered: RenderedImage[],
@@ -522,14 +488,10 @@ function drawObservationImageGrid(
const { page, fonts, width } = ctx const { page, fonts, width } = ctx
let cursorY = startY let cursorY = startY
if (rendered.length === 0) return cursorY if (rendered.length === 0) return cursorY
const isSingle = rendered.length === 1 const isSingle = rendered.length === 1
const cols = isSingle ? 1 : 2 const cols = isSingle ? 1 : 2
const rows = Math.ceil(rendered.length / cols) const rows = Math.ceil(rendered.length / cols)
const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols
// Single-image observations get rendered at half the available width
// and centered, so they don't dominate the page when the surrounding
// text is short.
const cellW = isSingle ? fullCellW / 2 : fullCellW const cellW = isSingle ? fullCellW / 2 : fullCellW
const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0 const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0
const availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom) const availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom)
@@ -537,7 +499,6 @@ function drawObservationImageGrid(
IMAGE_MIN_CELL_H, IMAGE_MIN_CELL_H,
(availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows, (availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows,
) )
for (let r = 0; r < rows; r += 1) { for (let r = 0; r < rows; r += 1) {
const rowItems = rendered.slice(r * cols, r * cols + cols) const rowItems = rendered.slice(r * cols, r * cols + cols)
const cellHs = rowItems.map((it) => Math.min(cellW * it.aspect, rowBudget)) const cellHs = rowItems.map((it) => Math.min(cellW * it.aspect, rowBudget))
@@ -557,9 +518,9 @@ function drawObservationImageGrid(
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP) const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
page.drawImage(it.img, { page.drawImage(it.img, {
x, x,
y: cursorY - cellHs[c], y: cursorY - cellHs[c]!,
width: cellW, width: cellW,
height: cellHs[c], height: cellHs[c]!,
}) })
}) })
cursorY -= rowH cursorY -= rowH
@@ -569,7 +530,6 @@ function drawObservationImageGrid(
return cursorY return cursorY
} }
/** Draws each label/value section, returns the cursor y below the last one. */
function drawObservationSections( function drawObservationSections(
ctx: PageDrawContext, ctx: PageDrawContext,
sections: ObservationSection[], sections: ObservationSection[],
@@ -597,8 +557,12 @@ function drawObservationSections(
fonts, fonts,
) )
} else { } else {
const lines = wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW) for (const line of wrapLines(
for (const line of lines) { value,
fonts.bodyRegular,
SECTION_TEXT_SIZE,
maxTextW,
)) {
page.drawText(line, { page.drawText(line, {
x: MARGIN_X, x: MARGIN_X,
y: cursorY, y: cursorY,
@@ -623,8 +587,7 @@ export async function addObservationPage(
observation, observation,
obsIndex, obsIndex,
fonts, fonts,
zoneLabels, sheet,
findingsTree,
locale, locale,
headerAssets, headerAssets,
} = ctx } = ctx
@@ -634,18 +597,31 @@ export async function addObservationPage(
drawHeader(page, report, fonts, locale, headerAssets) drawHeader(page, report, fonts, locale, headerAssets)
const drawCtx: PageDrawContext = { page, fonts, width } const drawCtx: PageDrawContext = { page, fonts, width }
const titleY = drawObservationTitleBlock(drawCtx, dict, obsIndex, observation.severity) const titleY = drawObservationTitleBlock(
drawCtx,
const species = getSpecies(report.animal.speciesId) dict,
if (!species) return obsIndex,
observation.severity,
const rendered = await buildObservationImages(pdfDoc, species, observation, dict) )
const rendered = await buildObservationImages(
pdfDoc,
sheet,
observation,
locale,
dict,
)
const maxTextW = width - MARGIN_X * 2 const maxTextW = width - MARGIN_X * 2
const sections = buildObservationSections(observation, zoneLabels, findingsTree, locale, dict) const sections = buildObservationSections(observation, sheet, locale, dict)
const reservedBottom = MARGIN_BOTTOM + estimateSectionsHeight(sections, fonts, maxTextW) + IMAGE_BOTTOM_GAP const reservedBottom =
MARGIN_BOTTOM +
let cursorY = drawObservationImageGrid(drawCtx, rendered, titleY - IMAGE_TOP_GAP, reservedBottom) estimateSectionsHeight(sections, fonts, maxTextW) +
IMAGE_BOTTOM_GAP
let cursorY = drawObservationImageGrid(
drawCtx,
rendered,
titleY - IMAGE_TOP_GAP,
reservedBottom,
)
cursorY -= TEXT_TOP_GAP cursorY -= TEXT_TOP_GAP
drawObservationSections(drawCtx, sections, cursorY, maxTextW) drawObservationSections(drawCtx, sections, cursorY, maxTextW)
} }
+5 -2
View File
@@ -22,7 +22,8 @@ function ensureSvgAttributes(
root.setAttribute('xmlns', 'http://www.w3.org/2000/svg') root.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
} }
if (!root.getAttribute('width')) root.setAttribute('width', String(widthPx)) if (!root.getAttribute('width')) root.setAttribute('width', String(widthPx))
if (!root.getAttribute('height')) root.setAttribute('height', String(heightPx)) if (!root.getAttribute('height'))
root.setAttribute('height', String(heightPx))
return new XMLSerializer().serializeToString(root) return new XMLSerializer().serializeToString(root)
} }
@@ -77,7 +78,9 @@ async function rasterizeWithImageElement(
return canvas return canvas
} }
async function canvasToPngBytes(canvas: HTMLCanvasElement): Promise<Uint8Array> { async function canvasToPngBytes(
canvas: HTMLCanvasElement,
): Promise<Uint8Array> {
const blob = await new Promise<Blob | null>((resolve) => { const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/png') canvas.toBlob((b) => resolve(b), 'image/png')
}) })
+113
View File
@@ -0,0 +1,113 @@
import type {
Annotation,
FindingCategory,
FindingNode,
FindingZone,
LocalizedText,
SheetView,
VertebralRegion,
} from '@faunosteo/domain'
import type { Locale } from '@/i18n/types'
import type { LoadedSheet } from '@/sheets/provider'
/**
* Read-only lookups over a loaded sheet. Everything the editor used to derive
* from SVG attributes, label matching or the species manifest comes from the
* document here, by stable id: no label drives logic.
*/
export type ObservableAnnotation = Extract<
Annotation,
{ kind: 'point' | 'zone' }
>
export interface SheetIndex {
sheet: LoadedSheet
mainView: SheetView
view(id: string): SheetView | undefined
annotation(id: string): Annotation | undefined
annotationsOfView(viewId: string): Annotation[]
findingZone(id: string): FindingZone | undefined
/** The category or node at a path, undefined when absent from the sheet. */
nodeAt(
zoneId: string,
path: readonly string[],
): FindingCategory | FindingNode | undefined
regions(): VertebralRegion[]
region(code: string): VertebralRegion | undefined
/** The annotation that opens the vertebra picker for a region on a view. */
spineAnnotation(
regionCode: string,
viewId: string,
): ObservableAnnotation | undefined
/** Whether an annotation opens the vertebra picker. */
isSpine(annotationId: string): boolean
name(annotation: Annotation): LocalizedText
}
export function pickLabel(
text: LocalizedText | null | undefined,
locale: Locale,
): string {
if (!text) return ''
return locale === 'en' ? text.en || text.fr : text.fr || text.en
}
export function isObservable(
a: Annotation | undefined,
): a is ObservableAnnotation {
return a !== undefined && a.kind !== 'detail_trigger'
}
export function buildSheetIndex(sheet: LoadedSheet): SheetIndex {
const { document } = sheet
const views = new Map(document.views.map((v) => [v.id, v]))
const annotations = new Map(document.annotations.map((a) => [a.id, a]))
const zones = new Map(document.finding_zones.map((z) => [z.id, z]))
const regions = new Map(
document.vertebral_config.regions.map((r) => [r.code, r]),
)
const mainView = document.views.find((v) => v.kind === 'main')
if (!mainView) throw new Error('sheet has no main view')
const nodeAt: SheetIndex['nodeAt'] = (zoneId, path) => {
const zone = zones.get(zoneId)
if (!zone || path.length === 0) return undefined
let node: FindingCategory | FindingNode | undefined = zone.categories.find(
(c) => c.id === path[0],
)
for (const segment of path.slice(1)) {
if (!node) return undefined
node = node.children.find((n) => n.id === segment)
}
return node
}
return {
sheet,
mainView,
view: (id) => views.get(id),
annotation: (id) => annotations.get(id),
annotationsOfView: (viewId) =>
document.annotations.filter((a) => a.view_id === viewId),
findingZone: (id) => zones.get(id),
nodeAt,
regions: () => document.vertebral_config.regions,
region: (code) => regions.get(code),
spineAnnotation: (code, viewId) =>
document.annotations.find(
(a): a is ObservableAnnotation =>
isObservable(a) &&
a.view_id === viewId &&
a.vertebral_region_code === code,
),
isSpine: (id) => {
const a = annotations.get(id)
return isObservable(a) && a.vertebral_region_code !== null
},
name: (a) =>
a.kind === 'detail_trigger'
? (a.name ?? views.get(a.opens_view_id)?.name ?? { fr: '', en: '' })
: a.name,
}
}
+213
View File
@@ -0,0 +1,213 @@
import type {
Annotation,
LateralSide,
Observation,
ReportZone,
Vertebra,
} from '@faunosteo/domain'
import { isObservable, type SheetIndex } from './sheetIndex'
/**
* Zone interaction rules of the report editor, pure: what a click on an
* annotation means for the active observation, and the observation
* reducers the route applies. The rules are the legacy ones (click chain
* of EditorRoute, BDR-019 vertebra sync), keyed by annotation ids.
*/
export interface ZoneRef {
annotationId: string
viewId: string
}
export type ZoneClickDecision =
| { kind: 'ignore' }
| { kind: 'open_view'; viewId: string }
| { kind: 'activate_fallback' }
| { kind: 'open_vertebra_picker' }
| { kind: 'open_laterality_picker' }
| { kind: 'remove_both_sides' }
| { kind: 'toggle' }
export function sameZone(zone: ReportZone, ref: ZoneRef): boolean {
return zone.annotationId === ref.annotationId && zone.viewId === ref.viewId
}
export function refOf(annotation: Annotation): ZoneRef {
return { annotationId: annotation.id, viewId: annotation.view_id }
}
export function sidesPresent(obs: Observation, ref: ZoneRef): LateralSide[] {
return obs.zones
.filter((z) => sameZone(z, ref) && z.side)
.map((z) => z.side as LateralSide)
}
/**
* Legacy click chain: detail trigger opens its view and is never added; no
* active observation → the click only activates one; spine zones always open
* the picker; bilateral zones go through the side picker, or clear both sides
* when both are set; anything else toggles.
*/
export function decideZoneClick(
annotation: Annotation | undefined,
active: Observation | undefined,
): ZoneClickDecision {
if (!annotation) return { kind: 'ignore' }
if (annotation.kind === 'detail_trigger') {
return { kind: 'open_view', viewId: annotation.opens_view_id }
}
if (!active) return { kind: 'activate_fallback' }
if (annotation.vertebral_region_code !== null) {
return { kind: 'open_vertebra_picker' }
}
if (annotation.laterality === 'bilateral') {
const sides = sidesPresent(active, refOf(annotation))
return sides.includes('left') && sides.includes('right')
? { kind: 'remove_both_sides' }
: { kind: 'open_laterality_picker' }
}
return { kind: 'toggle' }
}
function newZone(annotation: Annotation, side?: LateralSide): ReportZone {
const zone: ReportZone = refOf(annotation)
if (isObservable(annotation)) {
zone.labelFrSnapshot = annotation.name.fr
zone.labelEnSnapshot = annotation.name.en
}
if (side) zone.side = side
return zone
}
function withZones(obs: Observation, zones: ReportZone[]): Observation {
return { ...obs, zones }
}
/** Plain zone: added when absent, removed when present (no side). */
export function toggleZone(
obs: Observation,
annotation: Annotation,
): Observation {
const index = obs.zones.findIndex((z) => sameZone(z, refOf(annotation)))
if (index >= 0)
return withZones(
obs,
obs.zones.filter((_, i) => i !== index),
)
return withZones(obs, [...obs.zones, newZone(annotation)])
}
/** The zone exists after the call; returns its index. */
export function ensureZone(
obs: Observation,
annotation: Annotation,
): { observation: Observation; index: number } {
const index = obs.zones.findIndex((z) => sameZone(z, refOf(annotation)))
if (index >= 0) return { observation: obs, index }
const zones = [...obs.zones, newZone(annotation)]
return { observation: withZones(obs, zones), index: zones.length - 1 }
}
/** Appends the sides not present yet; never removes one (legacy semantics). */
export function addSides(
obs: Observation,
annotation: Annotation,
sides: readonly LateralSide[],
): Observation {
const present = sidesPresent(obs, refOf(annotation))
const added = sides
.filter((side) => !present.includes(side))
.map((side) => newZone(annotation, side))
return added.length === 0 ? obs : withZones(obs, [...obs.zones, ...added])
}
export function removeAllSides(obs: Observation, ref: ZoneRef): Observation {
return withZones(
obs,
obs.zones.filter((z) => !sameZone(z, ref)),
)
}
export function removeZoneAt(obs: Observation, index: number): Observation {
return withZones(
obs,
obs.zones.filter((_, i) => i !== index),
)
}
function isSpineZone(zone: ReportZone, index: SheetIndex): boolean {
return index.isSpine(zone.annotationId)
}
/**
* Vertebrae of every spine zone of the observation, the zone at `priority`
* first (the one the picker was opened from), without duplicates.
*/
export function collectVertebrae(
obs: Observation,
index: SheetIndex,
priority: number,
): Vertebra[] {
const ordered = [
...obs.zones.filter((_, i) => i === priority),
...obs.zones.filter((_, i) => i !== priority),
]
const seen = new Set<string>()
const out: Vertebra[] = []
for (const zone of ordered) {
if (!isSpineZone(zone, index)) continue
for (const v of zone.vertebrae ?? []) {
const key = `${v.region}${v.index}`
if (seen.has(key)) continue
seen.add(key)
out.push({ ...v })
}
}
return out
}
function regionOf(zone: ReportZone, index: SheetIndex): string | null {
const a = index.annotation(zone.annotationId)
return isObservable(a) ? a.vertebral_region_code : null
}
/**
* BDR-019: the picker edits every region at once. Per region the selection
* REPLACES the zone's vertebrae; a spine zone left without vertebrae is
* pruned; a region picked without a zone gets one on the view the picker
* was opened from (or the main view).
*/
export function syncVertebrae(
obs: Observation,
selection: readonly Vertebra[],
index: SheetIndex,
viewId: string,
): Observation {
const byRegion = new Map<string, Vertebra[]>()
for (const v of selection) {
const list = byRegion.get(v.region) ?? []
list.push({ ...v })
byRegion.set(v.region, list)
}
const kept: ReportZone[] = []
for (const zone of obs.zones) {
const region = isSpineZone(zone, index) ? regionOf(zone, index) : null
if (region === null) {
kept.push(zone)
continue
}
const picked = byRegion.get(region)
byRegion.delete(region)
if (!picked || picked.length === 0) continue
kept.push({ ...zone, vertebrae: picked })
}
for (const [region, picked] of byRegion) {
if (picked.length === 0) continue
const annotation =
index.spineAnnotation(region, viewId) ??
index.spineAnnotation(region, index.mainView.id)
if (!annotation) continue
kept.push({ ...newZone(annotation), vertebrae: picked })
}
return withZones(obs, kept)
}
+83
View File
@@ -0,0 +1,83 @@
import {
AnatomicalSheetDocumentSchema,
ReportMigrationMapSchema,
type AnatomicalSheetDocument,
type ReportMigrationMap,
type SheetRef,
} from '@faunosteo/domain'
/**
* Where the application gets the anatomical sheet it works on. Step 5 ships
* one implementation, the sheet bundled at build time (virtual module, see
* vite/sheet-bundle.ts); the Supabase implementation of Step 13 sits behind
* the same interface. A loaded sheet is immutable for the session.
*/
export type SheetStatus = 'draft' | 'published'
/** Raw payload of the virtual module, validated here before use. */
export interface BundledSheetData {
status: SheetStatus
ref: {
sheet_id: string
version_id: string | null
document_sha256: string
schema_version: number
species_id: string
}
document: unknown
migrationMap: unknown
assets: Record<string, string>
}
export interface LoadedSheet {
status: SheetStatus
ref: SheetRef
speciesId: string
document: AnatomicalSheetDocument
/** SVG text by `svg_asset_id`. */
assets: Readonly<Record<string, string>>
migrationMap: ReportMigrationMap
}
export interface SheetProvider {
/** The reference sheet of a species, or null when none is available. */
getReferenceSheet(speciesId: string): Promise<LoadedSheet | null>
}
export function parseBundledSheet(data: BundledSheetData): LoadedSheet {
const document = AnatomicalSheetDocumentSchema.parse(data.document)
const migrationMap = ReportMigrationMapSchema.parse(data.migrationMap)
return {
status: data.status,
ref: {
sheetId: data.ref.sheet_id,
versionId: data.ref.version_id,
documentSha256: data.ref.document_sha256,
},
speciesId: data.ref.species_id,
document,
assets: data.assets,
migrationMap,
}
}
let cached: Promise<LoadedSheet | null> | null = null
async function loadBundled(): Promise<LoadedSheet | null> {
const mod = await import('virtual:faunosteo-sheet')
return mod.bundledSheet ? parseBundledSheet(mod.bundledSheet) : null
}
export const bundledSheetProvider: SheetProvider = {
async getReferenceSheet(speciesId) {
cached ??= loadBundled()
const sheet = await cached
return sheet && sheet.speciesId === speciesId ? sheet : null
},
}
/** Test seam: forget the memoised bundle. */
export function resetBundledSheetCache(): void {
cached = null
}
+54
View File
@@ -0,0 +1,54 @@
import { useEffect, useState } from 'react'
import { buildSheetIndex, type SheetIndex } from '@/services/sheetIndex'
import { bundledSheetProvider, type SheetProvider } from './provider'
/**
* The reference sheet of a species for the current session, loaded once
* through the provider and indexed. `none` means the build carries no sheet
* (production bundle without SHEET_BUNDLE=draft) or no sheet for the species.
*/
export type SheetState =
| { status: 'loading' }
| { status: 'none' }
| { status: 'ready'; index: SheetIndex }
let provider: SheetProvider = bundledSheetProvider
const cache = new Map<string, Promise<SheetIndex | null>>()
/** Test seam: swap the provider and forget loaded sheets. */
export function setSheetProvider(next: SheetProvider): void {
provider = next
cache.clear()
}
export function loadSheetIndex(speciesId: string): Promise<SheetIndex | null> {
let pending = cache.get(speciesId)
if (!pending) {
pending = provider
.getReferenceSheet(speciesId)
.then((sheet) => (sheet ? buildSheetIndex(sheet) : null))
cache.set(speciesId, pending)
}
return pending
}
export function useSheet(speciesId: string | undefined): SheetState {
const [state, setState] = useState<SheetState>({ status: 'loading' })
useEffect(() => {
let cancelled = false
if (!speciesId) {
setState({ status: 'none' })
return
}
setState({ status: 'loading' })
loadSheetIndex(speciesId).then((index) => {
if (cancelled) return
setState(index ? { status: 'ready', index } : { status: 'none' })
})
return () => {
cancelled = true
}
}, [speciesId])
return state
}
+3
View File
@@ -0,0 +1,3 @@
declare module 'virtual:faunosteo-sheet' {
export const bundledSheet: import('./provider').BundledSheetData | null
}
+41
View File
@@ -0,0 +1,41 @@
import {
readReportDocument,
type Report,
type ReportMigrationMap,
} from '@faunosteo/domain'
/**
* Where the report document lives between renders. One implementation today
* (the per-tab sessionStorage draft, migrated from v2 on read); the Supabase
* and outbox adapters of later steps implement the same interface.
*/
export interface ReportPersistence {
load(map: ReportMigrationMap): Report | null
save(report: Report | null): void
}
export const DRAFT_KEY = 'osteo:draft'
function storage(): Storage | null {
return typeof sessionStorage === 'undefined' ? null : sessionStorage
}
export const sessionStoragePersistence: ReportPersistence = {
load(map) {
const raw = storage()?.getItem(DRAFT_KEY)
if (!raw) return null
try {
return readReportDocument(JSON.parse(raw), map).report
} catch (err) {
if (import.meta.env.DEV) console.warn('osteo:draft ignored', err)
return null
}
},
save(report) {
const store = storage()
if (!store) return
if (report) store.setItem(DRAFT_KEY, JSON.stringify(report))
else store.removeItem(DRAFT_KEY)
},
}
+1 -4
View File
@@ -1,7 +1,4 @@
import { import { PractitionerSchema, type Practitioner } from '@faunosteo/domain'
PractitionerSchema,
type Practitioner,
} from '@/domain/schema/practitioner'
const STORAGE_KEY = 'osteo:lastPractitioner' const STORAGE_KEY = 'osteo:lastPractitioner'
+105 -85
View File
@@ -1,16 +1,42 @@
import { create } from 'zustand' import { create } from 'zustand'
import { ReportSchema, type Report } from '@/domain/schema/report' import {
import type { Observation } from '@/domain/schema/observation' REPORT_VERSION,
import type { Practitioner } from '@/domain/schema/practitioner' type Animal,
import type { Animal, Owner } from '@/domain/schema/animal' type NextAppointment,
type Observation,
type Owner,
type Practitioner,
type Report,
type ReportMigrationMap,
type SheetRef,
} from '@faunosteo/domain'
import { generateId } from '@/lib/id' import { generateId } from '@/lib/id'
import { nowIso } from '@/lib/dates' import { nowIso } from '@/lib/dates'
import {
sessionStoragePersistence,
type ReportPersistence,
} from './persistence'
/**
* In-memory report document (v3) and its editing actions. Observation-level
* zone rules live in services/zoneInteraction; the store only replaces
* documents. The per-tab draft is mirrored through the persistence adapter
* and restored once the sheet (and its migration map) is known.
*/
/** What a new report needs before the store stamps version, id and dates. */
export type NewReportDraft = Omit<
Report,
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
>
export interface ReportStore { export interface ReportStore {
report: Report | null report: Report | null
activeObservationIndex: number activeObservationIndex: number
initReport: (draft: Omit<Report, 'id' | 'createdAt' | 'version'>) => void initReport: (draft: NewReportDraft, sheet: SheetRef) => void
hydrateReport: (report: Report) => void hydrateReport: (report: Report) => void
/** Restores the per-tab draft; a no-op when a report is already open. */
restoreDraft: (map: ReportMigrationMap) => void
addObservation: () => void addObservation: () => void
removeObservation: (index: number) => void removeObservation: (index: number) => void
moveObservationUp: (index: number) => void moveObservationUp: (index: number) => void
@@ -22,11 +48,11 @@ export interface ReportStore {
setOwner: (next: Owner) => void setOwner: (next: Owner) => void
setConclusion: (text: string) => void setConclusion: (text: string) => void
setRecommendations: (text: string) => void setRecommendations: (text: string) => void
setNextAppointment: (next: Report['nextAppointment']) => void setNextAppointment: (next: NextAppointment | undefined) => void
reset: () => void reset: () => void
} }
function emptyObservation(): Observation { export function emptyObservation(): Observation {
return { return {
id: generateId(), id: generateId(),
zones: [], zones: [],
@@ -36,131 +62,125 @@ function emptyObservation(): Observation {
} }
} }
const DRAFT_KEY = 'osteo:draft' function swapped(list: Observation[], i: number, j: number): Observation[] {
const next = [...list]
/** Reads the auto-saved draft back from sessionStorage (null if absent/invalid). */ ;[next[i], next[j]] = [next[j]!, next[i]!]
export function readPersistedDraft(): Report | null { return next
if (typeof sessionStorage === 'undefined') return null
const raw = sessionStorage.getItem(DRAFT_KEY)
if (!raw) return null
try {
const parsed = ReportSchema.safeParse(JSON.parse(raw))
return parsed.success ? parsed.data : null
} catch {
return null
}
} }
export const useReportStore = create<ReportStore>((set) => ({ type Patch = Partial<Pick<ReportStore, 'report' | 'activeObservationIndex'>>
// Restore the per-tab draft so a page refresh never loses the session. type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
report: readPersistedDraft(),
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s))
}
export function createReportStore(persistence: ReportPersistence) {
const store = create<ReportStore>((set) => ({
report: null,
activeObservationIndex: 0, activeObservationIndex: 0,
initReport: (draft) => initReport: (draft, sheet) =>
set({ set({
report: { report: {
...draft, ...draft,
version: 2, version: REPORT_VERSION,
id: generateId(), id: generateId(),
createdAt: nowIso(), createdAt: nowIso(),
sheet,
observations: observations:
draft.observations.length === 0 draft.observations.length === 0
? [emptyObservation()] ? [emptyObservation()]
: draft.observations, : draft.observations,
localAnnotations: [],
}, },
activeObservationIndex: 0, activeObservationIndex: 0,
}), }),
hydrateReport: (report) => set({ report, activeObservationIndex: 0 }), hydrateReport: (report) => set({ report, activeObservationIndex: 0 }),
addObservation: () => restoreDraft: (map) =>
set((s) => { set((s) => {
if (!s.report) return s if (s.report) return s
const obs = emptyObservation() const report = persistence.load(map)
const observations = [...s.report.observations, obs] return report ? { report, activeObservationIndex: 0 } : s
}),
addObservation: () =>
onReport(set, (r) => {
const observations = [...r.observations, emptyObservation()]
return { return {
report: { ...s.report, observations }, report: { ...r, observations },
activeObservationIndex: observations.length - 1, activeObservationIndex: observations.length - 1,
} }
}), }),
removeObservation: (index) => removeObservation: (index) =>
set((s) => { onReport(set, (r, s) => {
if (!s.report) return s const observations = r.observations.filter((_, i) => i !== index)
const observations = s.report.observations.filter((_, i) => i !== index)
const active = Math.min( const active = Math.min(
s.activeObservationIndex, s.activeObservationIndex,
Math.max(0, observations.length - 1), Math.max(0, observations.length - 1),
) )
return { return {
report: { ...s.report, observations }, report: { ...r, observations },
activeObservationIndex: active, activeObservationIndex: active,
} }
}), }),
moveObservationUp: (index) => moveObservationUp: (index) =>
set((s) => { onReport(set, (r) =>
if (!s.report || index <= 0) return s index <= 0
const observations = [...s.report.observations] ? {}
;[observations[index - 1], observations[index]] = [ : {
observations[index], report: {
observations[index - 1], ...r,
] observations: swapped(r.observations, index - 1, index),
return { report: { ...s.report, observations } } },
}), },
),
moveObservationDown: (index) => moveObservationDown: (index) =>
set((s) => { onReport(set, (r) =>
if (!s.report || index >= s.report.observations.length - 1) return s index >= r.observations.length - 1
const observations = [...s.report.observations] ? {}
;[observations[index], observations[index + 1]] = [ : {
observations[index + 1], report: {
observations[index], ...r,
] observations: swapped(r.observations, index, index + 1),
return { report: { ...s.report, observations } } },
}), },
),
updateObservation: (index, obs) => updateObservation: (index, obs) =>
set((s) => { onReport(set, (r) => ({
if (!s.report) return s report: {
const observations = s.report.observations.map((o, i) => ...r,
i === index ? obs : o, observations: r.observations.map((o, i) => (i === index ? obs : o)),
) },
return { report: { ...s.report, observations } } })),
}),
setActiveObservation: (index) => set({ activeObservationIndex: index }), setActiveObservation: (index) => set({ activeObservationIndex: index }),
setPractitioner: (next) => setPractitioner: (next) =>
set((s) => (s.report ? { report: { ...s.report, practitioner: next } } : s)), onReport(set, (r) => ({ report: { ...r, practitioner: next } })),
setAnimal: (next) => setAnimal: (next) =>
set((s) => (s.report ? { report: { ...s.report, animal: next } } : s)), onReport(set, (r) => ({ report: { ...r, animal: next } })),
setOwner: (next) => setOwner: (next) =>
set((s) => (s.report ? { report: { ...s.report, owner: next } } : s)), onReport(set, (r) => ({ report: { ...r, owner: next } })),
setConclusion: (text) => setConclusion: (text) =>
set((s) => (s.report ? { report: { ...s.report, conclusion: text } } : s)), onReport(set, (r) => ({ report: { ...r, conclusion: text } })),
setRecommendations: (text) => setRecommendations: (text) =>
set((s) => onReport(set, (r) => ({ report: { ...r, recommendations: text } })),
s.report ? { report: { ...s.report, recommendations: text } } : s,
),
setNextAppointment: (next) => setNextAppointment: (next) =>
set((s) => onReport(set, (r) => {
s.report ? { report: { ...s.report, nextAppointment: next } } : s, const rest = { ...r }
), delete rest.nextAppointment
return { report: next ? { ...rest, nextAppointment: next } : rest }
}),
reset: () => set({ report: null, activeObservationIndex: 0 }), reset: () => set({ report: null, activeObservationIndex: 0 }),
})) }))
store.subscribe((state) => persistence.save(state.report))
return store
}
useReportStore.subscribe((state) => { export const useReportStore = createReportStore(sessionStoragePersistence)
if (typeof sessionStorage === 'undefined') return
if (state.report) {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(state.report))
} else {
sessionStorage.removeItem(DRAFT_KEY)
}
})
-528
View File
@@ -1,528 +0,0 @@
.svg-editor-root {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
font-family: var(--font-sans);
color: var(--color-ink);
background: var(--color-bg);
}
@media (min-width: 768px) {
.svg-editor-root {
flex-direction: row;
}
}
.svg-editor-root * { box-sizing: border-box; margin: 0; padding: 0; }
.svg-editor-canvas {
flex: 1;
position: relative;
background: var(--color-surface);
overflow: hidden;
padding: 10px;
min-height: 40vh;
}
@media (min-width: 768px) {
.svg-editor-canvas {
min-height: 0;
}
}
.svg-editor-canvas-inner {
width: 100%;
height: 100%;
overflow: auto;
position: relative;
}
.svg-editor-canvas-inner svg {
display: block;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
.svg-editor-canvas.mode-point svg,
.svg-editor-canvas.mode-polygon svg { cursor: crosshair; }
.svg-editor-canvas.mode-select svg { cursor: default; }
.svg-editor-root [data-anno-id] { transition: filter 0.1s; }
.svg-editor-root [data-anno-id]:hover {
filter: brightness(1.3) drop-shadow(0 0 4px rgba(184, 90, 63, 0.7));
}
.svg-editor-root [data-anno-id].selected {
filter: drop-shadow(0 0 12px var(--color-accent)) drop-shadow(0 0 6px var(--color-accent)) brightness(1.15);
stroke: var(--color-accent) !important;
stroke-width: 4 !important;
stroke-opacity: 1 !important;
}
.svg-editor-root .polygon-handle {
cursor: move;
fill: #ffd54f;
stroke: var(--color-accent);
stroke-width: 2;
transition: r 0.1s;
}
.svg-editor-root .polygon-handle:hover {
fill: #ffe082;
stroke-width: 3;
}
.svg-editor-root .polygon-midhandle {
cursor: copy;
fill: var(--color-surface);
stroke: var(--color-accent);
stroke-width: 1.5;
fill-opacity: 0.7;
}
.svg-editor-root .polygon-midhandle:hover {
fill: #ffd54f;
fill-opacity: 1;
}
@keyframes svg-editor-flash-pulse {
0%, 100% {
stroke-width: 4;
stroke: var(--color-accent);
filter: drop-shadow(0 0 12px var(--color-accent)) brightness(1.15);
}
50% {
stroke-width: 10;
stroke: #ffd54f;
filter: drop-shadow(0 0 24px #ffd54f) drop-shadow(0 0 12px var(--color-accent)) brightness(1.4);
}
}
.svg-editor-root [data-anno-id].flashing {
animation: svg-editor-flash-pulse 0.6s ease-in-out 2;
}
.svg-editor-root .polygon-preview {
fill: rgba(184, 90, 63, 0.2);
stroke: var(--color-accent);
stroke-width: 2;
stroke-dasharray: 5,3;
}
.svg-editor-root .polygon-preview-pt { fill: var(--color-accent); }
.svg-editor-sidebar {
width: 100%;
background: var(--color-surface);
border-top: 1px solid var(--color-border);
display: flex;
flex-direction: column;
overflow: hidden;
max-height: 50vh;
}
@media (min-width: 768px) {
.svg-editor-sidebar {
width: 380px;
max-height: none;
border-top: none;
border-left: 1px solid var(--color-border);
}
}
.svg-editor-sidebar header {
padding: 14px 16px;
background: var(--color-accent);
color: white;
}
.svg-editor-sidebar header h1 { font-size: 16px; font-weight: 600; }
.svg-editor-sidebar header .sub { font-size: 11px; opacity: 0.8; margin-top: 4px; }
.svg-editor-sidebar-content {
flex: 1;
overflow-y: auto;
padding: 14px 16px;
}
.svg-editor-root .section { margin-bottom: 20px; }
.svg-editor-root .section h3 {
font-size: 11px;
text-transform: uppercase;
color: var(--color-ink-muted);
margin-bottom: 8px;
letter-spacing: 0.5px;
}
.svg-editor-root button,
.svg-editor-root .btn {
display: block;
width: 100%;
padding: 9px 12px;
margin-bottom: 6px;
background: var(--color-surface-strong);
border: 1px solid var(--color-border);
border-radius: 6px;
cursor: pointer;
font-size: 13px;
text-align: left;
transition: all 0.1s;
font-family: inherit;
color: var(--color-ink);
}
.svg-editor-root button:hover { background: var(--color-border); }
.svg-editor-root button.active {
background: var(--color-accent);
color: white;
border-color: var(--color-accent);
}
.svg-editor-root button.danger {
background: #fef2f2;
border-color: #fecaca;
color: var(--color-danger);
}
.svg-editor-root button.danger:hover { background: #fee2e2; }
.svg-editor-root button.primary {
background: var(--color-accent);
color: white;
border-color: var(--color-accent);
}
.svg-editor-root button.primary:hover { background: var(--color-accent-strong); }
.svg-editor-root input,
.svg-editor-root select {
display: block;
width: 100%;
padding: 8px 10px;
margin-bottom: 6px;
border: 1px solid var(--color-border);
border-radius: 6px;
font-size: 13px;
background: var(--color-surface);
font-family: inherit;
color: var(--color-ink);
}
.svg-editor-root input[type="color"] { padding: 2px; height: 32px; cursor: pointer; }
.svg-editor-root input[type="file"] { background: var(--color-surface-strong); cursor: pointer; }
.svg-editor-root label {
font-size: 11px;
color: var(--color-ink-muted);
margin-bottom: 2px;
display: block;
margin-top: 8px;
}
.svg-editor-root .element-list {
max-height: 280px;
overflow-y: auto;
border: 1px solid var(--color-border);
border-radius: 6px;
background: var(--color-bg);
}
.svg-editor-root .element-item {
padding: 6px 10px;
border-bottom: 1px solid var(--color-border);
cursor: pointer;
font-size: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.svg-editor-root .element-item:last-child { border-bottom: none; }
.svg-editor-root .element-item:hover { background: var(--color-surface-strong); }
.svg-editor-root .element-item.selected {
background: color-mix(in srgb, var(--color-accent) 12%, transparent);
color: var(--color-accent-strong);
font-weight: 600;
}
.svg-editor-root .element-item .swatch {
width: 12px;
height: 12px;
border-radius: 3px;
border: 1px solid rgba(0,0,0,0.15);
flex-shrink: 0;
}
.svg-editor-root .element-item .name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.svg-editor-root .element-item .cat {
font-size: 10px;
color: var(--color-ink-muted);
margin-left: auto;
padding: 1px 6px;
background: var(--color-surface-strong);
border-radius: 8px;
flex-shrink: 0;
}
.svg-editor-root .coords {
font-family: monospace;
font-size: 11px;
color: var(--color-ink-muted);
padding: 4px 8px;
background: var(--color-bg);
border-radius: 4px;
margin-bottom: 8px;
}
.svg-editor-zoom-controls {
position: absolute;
bottom: 20px;
left: 20px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: 6px;
padding: 4px;
display: flex;
gap: 4px;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.svg-editor-zoom-controls button {
width: 40px;
height: 40px;
padding: 0;
margin: 0;
font-size: 18px;
display: flex;
align-items: center;
justify-content: center;
}
@media (min-width: 768px) {
.svg-editor-zoom-controls button {
width: 32px;
height: 32px;
font-size: 16px;
}
}
.svg-editor-root input[type="checkbox"] { width: auto; display: inline; margin: 0 6px 0 0; }
.svg-editor-root .cat-row {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 4px;
background: var(--color-bg);
border-radius: 6px;
margin-bottom: 4px;
border: 1px solid var(--color-border);
}
.svg-editor-root .cat-row input[type="color"] { width: 32px; height: 28px; padding: 0; margin: 0; flex-shrink: 0; }
.svg-editor-root .cat-row input[type="checkbox"] { margin: 0 4px 0 4px; flex-shrink: 0; }
.svg-editor-root .cat-row .name {
flex: 1;
font-size: 13px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.svg-editor-root .cat-row .count {
font-size: 10px;
color: var(--color-ink-muted);
padding: 1px 5px;
background: var(--color-surface-strong);
border-radius: 8px;
}
.svg-editor-root .cat-row .delete {
width: 28px;
height: 28px;
padding: 0;
margin: 0;
font-size: 13px;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
border: none;
cursor: pointer;
}
.svg-editor-root .cat-row .delete:hover { background: #fef2f2; color: var(--color-danger); }
.svg-editor-root .cat-row .special-btn {
width: 28px;
height: 28px;
padding: 0;
margin: 0;
font-size: 13px;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
border: none;
cursor: pointer;
color: var(--color-ink-muted);
}
.svg-editor-root .cat-row .special-btn:hover { background: #fff8e1; color: #d97706; }
.svg-editor-root .cat-row .special-btn.has-value { color: #d97706; }
.svg-editor-root .cat-row .special-badge {
font-size: 10px;
padding: 1px 6px;
background: #fff8e1;
color: #92400e;
border: 1px solid #ffd54f;
border-radius: 8px;
flex-shrink: 0;
}
.svg-editor-root .add-cat { display: flex; gap: 6px; margin-top: 8px; }
.svg-editor-root .add-cat input { margin: 0; }
.svg-editor-root .add-cat input[type="color"] { width: 36px; flex-shrink: 0; }
.svg-editor-root .add-cat input[type="text"] { flex: 1; }
.svg-editor-root .add-cat button { width: auto; padding: 6px 12px; margin: 0; flex-shrink: 0; }
.svg-editor-root .slider-row {
display: flex;
gap: 8px;
align-items: center;
margin-bottom: 6px;
}
.svg-editor-root .slider-row input[type="range"] {
flex: 1;
margin: 0;
padding: 0;
height: 28px;
cursor: pointer;
accent-color: var(--color-accent);
}
.svg-editor-root .slider-row input[type="number"] {
width: 60px;
margin: 0;
padding: 6px 4px;
text-align: center;
font-variant-numeric: tabular-nums;
}
.svg-editor-root .detail-toggle {
margin-top: 4px;
padding: 8px 10px;
background: #fff8e1;
border: 1px solid #ffd54f;
border-radius: 6px;
font-size: 13px;
}
.svg-editor-root .detail-toggle label { margin: 0; color: #92400e; font-size: 13px; }
.svg-editor-root .detail-toggle input[type="text"] { margin-top: 4px; margin-bottom: 0; }
.svg-editor-root .element-item .detail-badge {
background: #ffd54f;
color: #6b4500;
font-size: 10px;
padding: 1px 6px;
border-radius: 8px;
font-weight: 600;
margin-left: 4px;
flex-shrink: 0;
}
.svg-editor-root [data-anno-opens-detail] { stroke-dasharray: 8,4; }
.svg-editor-root .detail-zone { cursor: pointer; }
.svg-editor-root .welcome {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100%;
text-align: center;
color: var(--color-ink-muted);
padding: 60px 20px;
}
.svg-editor-root .welcome-icon { font-size: 80px; margin-bottom: 20px; opacity: 0.7; }
.svg-editor-root .welcome h2 {
color: var(--color-accent);
margin-bottom: 16px;
font-size: 24px;
font-family: var(--font-serif);
}
.svg-editor-root .welcome p {
max-width: 480px;
margin-bottom: 30px;
line-height: 1.5;
font-size: 14px;
}
.svg-editor-root .welcome p code {
background: var(--color-surface-strong);
padding: 2px 6px;
border-radius: 3px;
font-size: 90%;
font-family: monospace;
}
.svg-editor-root .welcome-btn {
width: auto !important;
padding: 14px 28px !important;
font-size: 15px !important;
margin: 0 !important;
}
.svg-editor-root .welcome-hint {
margin-top: 16px;
color: var(--color-ink-muted);
font-size: 13px;
}
.svg-editor-root .welcome-tabs {
display: flex;
gap: 0;
margin-bottom: 20px;
border-radius: 6px;
overflow: hidden;
border: 1px solid var(--color-border);
}
.svg-editor-root .welcome-tab {
padding: 8px 20px;
font-size: 13px;
background: var(--color-surface);
color: var(--color-ink-muted);
border: none;
cursor: pointer;
transition: background 0.15s, color 0.15s;
}
.svg-editor-root .welcome-tab:not(:last-child) {
border-right: 1px solid var(--color-border);
}
.svg-editor-root .welcome-tab.active {
background: var(--color-accent);
color: #fff;
}
.svg-editor-root .welcome-tab-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
min-width: 260px;
}
.svg-editor-root .welcome-tab-content label {
font-size: 12px;
color: var(--color-ink-muted);
align-self: flex-start;
}
.svg-editor-root .welcome-tab-content select {
width: 100%;
padding: 8px 10px;
border-radius: 5px;
border: 1px solid var(--color-border);
background: var(--color-surface);
color: var(--color-ink);
font-size: 13px;
}
.svg-editor-canvas.dragging-over { background: color-mix(in srgb, var(--color-accent) 8%, var(--color-surface)); }
.svg-editor-canvas.dragging-over .welcome { color: var(--color-accent); }
.svg-editor-canvas.dragging-over::after {
content: attr(data-drop-label);
position: absolute;
inset: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 32px;
color: var(--color-accent);
background: color-mix(in srgb, var(--color-accent) 8%, transparent 15%);
border: 4px dashed var(--color-accent);
border-radius: 8px;
pointer-events: none;
z-index: 10;
}
.svg-editor-root .hide-articulation [data-anno-category="articulation"],
.svg-editor-root .hide-charniere [data-anno-category="charniere"],
.svg-editor-root .hide-cadran-crane [data-anno-category="cadran-crane"],
.svg-editor-root .hide-os-overlay [data-anno-category="os-overlay"],
.svg-editor-root .hide-spine-zone [data-anno-category="spine-zone"],
.svg-editor-root .hide-custom [data-anno-category="custom"] { display: none; }
+2 -1
View File
@@ -5,8 +5,9 @@ the Report v2 document as the current application produces it.
| File | Content | | File | Content |
|---|---| |---|---|
| `report-v2.full.json` | One report exercising every zone kind the editor can produce: plain hinge point, bilateral joint with both sides, spine zone with vertebrae, detail-popup zone, catalog findings (with and without vet referral and side), free text, severity, comment, conclusion, recommendations, dated next appointment. `boneId` values are the real `data-anno-id` of `public/species/equine/*.svg`; `zoneId`/`path` values exist in `pathologies.json`. | | `report-v2.full.json` | One report exercising every zone kind the editor can produce: plain hinge point, bilateral joint with both sides, spine zone with vertebrae, detail-popup zone, catalog findings (with and without vet referral and side), free text, severity, comment, conclusion, recommendations, dated next appointment. `boneId` values are the real `data-anno-id` of the legacy `Horse.svg` / `Horse_head.svg` now kept under `supabase/seed/anatomical-sheets/equine/legacy-sources/`; `zoneId`/`path` values exist in `pathologies.json`. |
| `report-v2.minimal.json` | Smallest valid v2 report (no observations). | | `report-v2.minimal.json` | Smallest valid v2 report (no observations). |
| `report-v2.full.pdf`, `report-v2.minimal.pdf` | The two reports exported by the v2 pipeline (commit 199e328, Step 5.0, rasteriser stubbed to a 1×1 PNG, no logos): the archive-like PDFs the v3 importer must read and migrate. Synthetic data only. |
Do not edit these files to make a test pass: they are the behavioural oracle for Do not edit these files to make a test pass: they are the behavioural oracle for
the Report v2 → v3 adapter and for PDF regression. Add a new fixture instead. the Report v2 → v3 adapter and for PDF regression. Add a new fixture instead.
Binary file not shown.
Binary file not shown.
+94
View File
@@ -0,0 +1,94 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { resolve } from 'node:path'
import {
AnatomicalSheetDocumentSchema,
ReportV2Schema,
type AnatomicalSheetDocument,
type FindingCategory,
type FindingNode,
type ObservationV2,
type ReportV2,
} from '@faunosteo/domain'
/**
* The legacy catalog as the application's archive knew it: every leaf of the
* generated baseline (`legacy-import/document.json`) becomes a Report v2
* finding, grouped in one observation per zone. Mirrors the anatomy package
* helper of the same name; both read the committed seed, never a copy.
*/
const BASELINE = resolve(
fileURLToPath(import.meta.url),
'../../../../../supabase/seed/anatomical-sheets/equine/legacy-import/document.json',
)
export interface LegacyLeaf {
zoneId: string
path: string[]
name: { fr: string; en: string }
vet: boolean
}
export function loadLegacyBaseline(): AnatomicalSheetDocument {
return AnatomicalSheetDocumentSchema.parse(
JSON.parse(readFileSync(BASELINE, 'utf8')),
)
}
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
const out: LegacyLeaf[] = []
const walk = (
zoneId: string,
nodes: readonly (FindingCategory | FindingNode)[],
prefix: string[],
) => {
for (const node of nodes) {
const path = [...prefix, node.id]
if (node.children.length > 0) walk(zoneId, node.children, path)
else {
const vet =
'requires_vet_referral' in node && node.requires_vet_referral
out.push({ zoneId, path, name: node.name, vet })
}
}
}
for (const zone of doc.finding_zones) walk(zone.id, zone.categories, [])
return out
}
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
const byZone = new Map<string, ObservationV2>()
for (const leaf of leaves) {
let obs = byZone.get(leaf.zoneId)
if (!obs) {
obs = {
id: `obs-${leaf.zoneId}`,
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
}
byZone.set(leaf.zoneId, obs)
}
obs.findings.push({
zoneId: leaf.zoneId,
path: leaf.path,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en || leaf.name.fr,
...(leaf.vet ? { requiresVetReferral: true } : {}),
})
}
return ReportV2Schema.parse({
version: 2,
id: 'all-leaves',
createdAt: '2026-10-10T00:00:00Z',
date: '2026-10-10',
practitioner: { name: 'Synthetic' },
animal: { speciesId: 'equine', name: 'Synthetic' },
owner: { name: 'Synthetic' },
observations: [...byZone.values()],
conclusion: '',
recommendations: '',
})
}
+39
View File
@@ -0,0 +1,39 @@
import {
REPORT_VERSION,
type Observation,
type Report,
} from '@faunosteo/domain'
import { loadSheetIndex } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
/** The bundled reference draft (vitest runs the sheet-bundle plugin in draft mode). */
export async function loadTestSheet(): Promise<SheetIndex> {
const index = await loadSheetIndex('equine')
if (!index) throw new Error('bundled sheet missing: run pnpm import:equine')
return index
}
export function emptyObservation(id = 'obs-1'): Observation {
return { id, zones: [], findings: [], freeTextFindings: [], comment: '' }
}
export function minimalReport(
sheet: SheetIndex,
patch: Partial<Report> = {},
): Report {
return {
version: REPORT_VERSION,
id: 'r1',
createdAt: '2026-10-10T10:00:00Z',
date: '2026-10-10',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
sheet: sheet.sheet.ref,
observations: [],
conclusion: '',
recommendations: '',
localAnnotations: [],
...patch,
}
}
-72
View File
@@ -1,72 +0,0 @@
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { parseSvgBones } from '@/anatomy/svgConvention'
const HERE = dirname(fileURLToPath(import.meta.url))
const HORSE_PATH = resolve(HERE, '../../public/species/equine/Horse.svg')
const HEAD_PATH = resolve(HERE, '../../public/species/equine/Horse_head.svg')
function loadSvg(path: string): SVGSVGElement {
const raw = readFileSync(path, 'utf8')
const doc = new DOMParser().parseFromString(raw, 'image/svg+xml')
return doc.documentElement as unknown as SVGSVGElement
}
describe('real Horse.svg', () => {
const map = parseSvgBones(loadSvg(HORSE_PATH))
it('parses 18 unique annotations', () => {
expect(map.size).toBe(18)
})
it('contains 5 zone-colonne annotations (cervical / thoracic / lumbar / sacral / caudal)', () => {
const spine = [...map.values()].filter(
(b) => b.category === 'zone-colonne',
)
expect(spine.length).toBe(5)
})
it('contains exactly one opens-detail trigger pointing at the head SVG', () => {
const triggers = [...map.values()].filter((b) => b.opensDetail === 'head')
expect(triggers.length).toBe(1)
})
it('contains 9 articulations', () => {
const arts = [...map.values()].filter(
(b) => b.category === 'articulations',
)
expect(arts.length).toBe(9)
})
it('contains 3 vertebral hinges', () => {
const ch = [...map.values()].filter(
(b) => b.category === 'charni-res-vert-brales',
)
expect(ch.length).toBe(3)
})
})
describe('real Horse_head.svg', () => {
const map = parseSvgBones(loadSvg(HEAD_PATH))
it('parses 9 unique annotations', () => {
expect(map.size).toBe(9)
})
it('contains 5 cadrans-du-cr-ne annotations', () => {
const cadrans = [...map.values()].filter(
(b) => b.category === 'cadrans-du-cr-ne',
)
expect(cadrans.length).toBe(5)
})
it('contains 2 articulations (ATM + SSB equivalents)', () => {
const arts = [...map.values()].filter(
(b) => b.category === 'articulations',
)
expect(arts.length).toBe(2)
})
})
@@ -1,99 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
parseSvgBones,
getBoneIdFromEvent,
} from '@/anatomy/svgConvention'
import { SvgConventionError } from '@/anatomy/types'
function svgFromString(s: string): SVGSVGElement {
const doc = new DOMParser().parseFromString(s, 'image/svg+xml')
return doc.documentElement as unknown as SVGSVGElement
}
const FIXTURE = `
<svg xmlns="http://www.w3.org/2000/svg">
<circle data-anno-id="point-shoulder" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
data-anno-category="articulations" />
<circle data-anno-id="point-shoulder" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
data-anno-category="articulations" />
<polygon data-anno-id="zone-cervical" data-anno-name-fr="Vertèbres cervicales"
data-anno-name-en="Cervical Vertebrae" data-anno-category="zone-colonne"
data-anno-special="vertebral-precision" />
<polygon data-anno-id="zone-head" data-anno-category="os" data-anno-opens-detail="head" />
<polygon data-anno-id="zone-future" data-anno-name-fr="Catégorie inédite"
data-anno-category="something-new-the-parser-has-never-seen" />
<circle data-anno-id="point-knee" data-anno-name-fr="Genou" data-anno-name-en="Knee"
data-anno-category="articulations" data-anno-lateral="bilateral" />
</svg>`
describe('parseSvgBones', () => {
it('groups multiple elements sharing the same data-anno-id', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
const shoulder = map.get('point-shoulder')
expect(shoulder).toBeDefined()
expect(shoulder?.fr).toBe('Épaule')
expect(shoulder?.en).toBe('Shoulder')
expect(shoulder?.category).toBe('articulations')
expect(shoulder?.els.length).toBe(2)
})
it('captures opensDetail when present', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('zone-head')?.opensDetail).toBe('head')
})
it('captures data-anno-special when present', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('zone-cervical')?.special).toBe('vertebral-precision')
expect(map.get('point-shoulder')?.special).toBeUndefined()
})
it('allows annotations without data-anno-name-fr/en (trigger-only zones)', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
const trigger = map.get('zone-head')
expect(trigger?.fr).toBe('')
expect(trigger?.en).toBe('')
})
it('accepts any string as data-anno-category (no hardcoded enum)', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('zone-future')?.category).toBe(
'something-new-the-parser-has-never-seen',
)
})
it('captures data-anno-lateral when present', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('point-knee')?.lateral).toBe('bilateral')
})
it('leaves lateral undefined when attribute absent', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('point-shoulder')?.lateral).toBeUndefined()
})
})
describe('parseSvgBones validation', () => {
it('throws on missing data-anno-category', () => {
const bad = `<svg xmlns="http://www.w3.org/2000/svg">
<circle data-anno-id="x" />
</svg>`
expect(() => parseSvgBones(svgFromString(bad))).toThrow(SvgConventionError)
})
it('throws on empty data-anno-id', () => {
const bad = `<svg xmlns="http://www.w3.org/2000/svg">
<circle data-anno-id="" data-anno-category="anything" />
</svg>`
expect(() => parseSvgBones(svgFromString(bad))).toThrow(SvgConventionError)
})
})
describe('getBoneIdFromEvent', () => {
it('returns null when no anno in ancestry', () => {
const div = document.createElement('div')
const evt = new Event('click')
Object.defineProperty(evt, 'target', { value: div })
expect(getBoneIdFromEvent(evt)).toBeNull()
})
})
@@ -1,23 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { loadSvg } from '@/anatomy/svgLoader'
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"><g data-anno-id="x"/></svg>'
describe('loadSvg', () => {
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,
text: async () => SVG,
})) as unknown as typeof fetch)
})
it('returns an SVGSVGElement', async () => {
const root = await loadSvg('/whatever.svg')
expect(root.tagName.toLowerCase()).toBe('svg')
})
it('throws on non-ok response', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404, text: async () => '' })) as unknown as typeof fetch)
await expect(loadSvg('/missing.svg')).rejects.toThrow()
})
})
-169
View File
@@ -1,169 +0,0 @@
/**
* Characterisation (Step 1): the equine findings catalog as it exists today.
* Pins the facts of docs/faunosteo-audit/05-findings-editor.md §2.4 so that
* the future legacy importer (plan Step 4) can be checked against them, and
* so that any deliberate business correction shows up as a test change.
*
* Reads the files directly (no Zod) to count what is really on disk.
*/
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { createHash } from 'node:crypto'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { SpeciesFindingsSchema } from '@/domain/schema/findings'
const HERE = dirname(fileURLToPath(import.meta.url))
const SRC_PATH = resolve(HERE, '../../src/domain/species/equine/pathologies.json')
const PUBLIC_PATH = resolve(HERE, '../../public/species/equine/pathologies.json')
interface RawNode {
id: string
name_fr?: string
name_en?: string
description_fr?: string
description_en?: string
requires_vet_referral?: boolean
sources?: unknown[]
children?: RawNode[]
}
interface RawZone { id: string; name_fr: string; name_en: string; categories: RawNode[] }
interface RawCatalog {
schema_version: string
scope_disclaimer: string
species: { id: string; name_fr: string; name_en: string }
zones: Record<string, RawZone>
}
const srcText = readFileSync(SRC_PATH, 'utf8')
const catalog = JSON.parse(srcText) as RawCatalog
const zoneKeys = Object.keys(catalog.zones)
function walk(nodes: RawNode[], depth: number, visit: (n: RawNode, depth: number) => void) {
for (const n of nodes) {
visit(n, depth)
if (n.children) walk(n.children, depth + 1, visit)
}
}
function allNodes(): Array<{ node: RawNode; depth: number; zone: string }> {
const out: Array<{ node: RawNode; depth: number; zone: string }> = []
for (const key of zoneKeys) {
walk(catalog.zones[key].categories, 1, (node, depth) => out.push({ node, depth, zone: key }))
}
return out
}
const isLeaf = (n: RawNode) => !n.children || n.children.length === 0
describe('catalog copies (src vs public)', () => {
it('the two pathologies.json copies are byte-identical (manual sync, no script)', () => {
const publicText = readFileSync(PUBLIC_PATH, 'utf8')
const md5 = (s: string) => createHash('md5').update(s).digest('hex')
expect(md5(publicText)).toBe(md5(srcText))
})
it('the bundled copy passes the Zod schema (boot-time contract)', () => {
expect(() => SpeciesFindingsSchema.parse(catalog)).not.toThrow()
})
})
describe('catalog shape (audit 05 §2.4)', () => {
it('declares schema_version "2.0" and species equine / Cheval / Horse', () => {
expect(catalog.schema_version).toBe('2.0')
expect(catalog.species).toEqual({ id: 'equine', name_fr: 'Cheval', name_en: 'Horse' })
expect(catalog.scope_disclaimer.length).toBeGreaterThan(50)
})
it('has exactly 26 zones in cranio-caudal insertion order', () => {
expect(zoneKeys).toEqual([
'parietal', 'frontal', 'sphenoid', 'temporal', 'occipital', 'ssb', 'atm', 'hyoid',
'c0-c1', 'cervical', 'c7-t1', 'shoulder', 'elbow', 'fore-fetlock', 'fore-sesamoids',
'thoracic', 't18-l1', 'lumbar', 'l6-s1', 'sacral', 'sacroiliac', 'hip', 'stifle',
'hock', 'hind-fetlock', 'caudal',
])
})
it('every zone.id equals its record key (convention, not enforced by Zod)', () => {
for (const key of zoneKeys) expect(catalog.zones[key].id).toBe(key)
})
it('every zone has exactly 3 root categories, the third always "anamnesis"', () => {
for (const key of zoneKeys) {
const cats = catalog.zones[key].categories
expect(cats, key).toHaveLength(3)
expect(cats[2].id, key).toBe('anamnesis')
}
})
it('root category ids follow <zone>-dysfunctions / <zone>-observations, except the known sphenoid anomaly', () => {
const anomalies: string[] = []
for (const key of zoneKeys) {
const [dys, obs] = catalog.zones[key].categories
if (dys.id !== `${key}-dysfunctions`) anomalies.push(`${key}:${dys.id}`)
if (obs.id !== `${key}-observations`) anomalies.push(`${key}:${obs.id}`)
}
// KNOWN: sphenoid reuses the ssb category id (audit 05 §2.4). The business
// correction is deferred to the editor before the first official version
// (OPEN_QUESTIONS Q9); the importer must NOT silently fix it.
expect(anomalies).toEqual(['sphenoid:ssb-dysfunctions'])
})
it('counts 792 nodes, 612 leaves, max depth 3, 228 leaves at depth 2 and 384 at depth 3', () => {
const nodes = allNodes()
expect(nodes).toHaveLength(792)
const leaves = nodes.filter((n) => isLeaf(n.node))
expect(leaves).toHaveLength(612)
expect(Math.max(...nodes.map((n) => n.depth))).toBe(3)
expect(leaves.filter((n) => n.depth === 2)).toHaveLength(228)
expect(leaves.filter((n) => n.depth === 3)).toHaveLength(384)
})
it('flags 41 vet-referral nodes, all of them leaves', () => {
const flagged = allNodes().filter((n) => n.node.requires_vet_referral === true)
expect(flagged).toHaveLength(41)
expect(flagged.every((n) => isLeaf(n.node))).toBe(true)
})
it('carries 62 description_fr, 0 description_en, 0 sources (CLAUDE.md "≥1 source" rule not met)', () => {
const nodes = allNodes()
expect(nodes.filter((n) => typeof n.node.description_fr === 'string')).toHaveLength(62)
expect(nodes.filter((n) => typeof n.node.description_en === 'string')).toHaveLength(0)
expect(nodes.filter((n) => Array.isArray(n.node.sources))).toHaveLength(0)
})
it('every node has non-empty name_fr and name_en', () => {
for (const { node, zone } of allNodes()) {
expect(node.name_fr, `${zone}/${node.id}`).toBeTruthy()
expect(node.name_en, `${zone}/${node.id}`).toBeTruthy()
}
})
it('node ids are unique among siblings only (same id reused across zones)', () => {
const idCount = new Map<string, number>()
for (const { node } of allNodes()) idCount.set(node.id, (idCount.get(node.id) ?? 0) + 1)
expect(idCount.get('anamnesis')).toBe(26)
expect(idCount.get('trauma-direct')).toBe(26)
expect(idCount.get('no-identified-cause')).toBe(26)
expect(idCount.get('amplitude-asymmetry')).toBe(11)
// sibling uniqueness holds everywhere
const checkSiblings = (nodes: RawNode[], where: string) => {
const ids = nodes.map((n) => n.id)
expect(new Set(ids).size, where).toBe(ids.length)
for (const n of nodes) if (n.children) checkSiblings(n.children, `${where}/${n.id}`)
}
for (const key of zoneKeys) checkSiblings(catalog.zones[key].categories, key)
})
it('anamnesis exists in exactly three content variants (vertebral / appendicular / head)', () => {
const variants = new Map<string, string[]>()
for (const key of zoneKeys) {
const anam = catalog.zones[key].categories[2]
const sig = (anam.children ?? []).map((c) => c.id).join(',')
variants.set(sig, [...(variants.get(sig) ?? []), key])
}
expect(variants.size).toBe(3)
const groups = [...variants.values()].map((g) => g.length).sort((a, b) => a - b)
expect(groups).toEqual([8, 9, 9])
})
})
@@ -1,293 +0,0 @@
/**
* Characterisation (Step 1): the zone-click chain of EditorRoute
* (onZoneClick → detail / fallback / spine / bilateral / toggle), the
* disclaimer-once-per-session rule, the zone removal and the pickers'
* integration with the store. Exercised through the rendered route on the
* real Horse.svg / Horse_head.svg, with loadSvg mocked to read the files.
*
* Limitation: the chain lives inside the route component (audit 13 §4, no
* unit seam). These tests go through the DOM; plan Step 5 extracts the
* chain into a service and will replace them with unit tests one-to-one.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor, within, cleanup } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import EditorRoute from '@/app/routes/EditorRoute'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import minimal from '../fixtures/report-v2.minimal.json'
import type { Report } from '@/domain/schema/report'
const HERE = dirname(fileURLToPath(import.meta.url))
const FILES: Record<string, string> = {
'/species/equine/Horse.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8'),
'/species/equine/Horse_head.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8'),
}
vi.mock('@/anatomy/svgLoader', () => ({
loadSvg: vi.fn(async (path: string) => {
const text = FILES[path]
if (!text) throw new Error(`unexpected path ${path}`)
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
return doc.documentElement as unknown as SVGSVGElement
}),
}))
const HINGE = 'point-mpbwyyc9' // Charnière C7-T1, plain point
const HIP = 'point-mpbwtst0' // bilateral
const CERVICAL = 'zone-mpbx5hx2' // vertebral-precision
const TRIGGER = 'zone-mpby55kd' // opens-detail=head
const ATM = 'point-mpbyo7zq' // in Horse_head.svg
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
function seedReport(observations: Report['observations'] = []) {
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.getState().initReport({
...(minimal as Report),
observations,
} as Omit<Report, 'id' | 'createdAt' | 'version'>)
}
const zonesOf = (i = 0) => useReportStore.getState().report!.observations[i].zones
const activeIndex = () => useReportStore.getState().activeObservationIndex
async function mount() {
const utils = render(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
// Main SVG rendered and parsed (bones map ready once the trigger exists).
await waitFor(() => expect(document.querySelector(`[data-anno-id="${TRIGGER}"]`)).not.toBeNull())
// Give the bones state effect a tick so onZoneClick resolves ids.
await waitFor(() => expect(screen.queryByRole('dialog', { name: fr['editor.disclaimer_title'] })).toBeNull())
return utils
}
function clickZone(id: string, scope: ParentNode = document) {
const els = scope.querySelectorAll(`[data-anno-id="${id}"]`)
expect(els.length, id).toBeGreaterThan(0)
els[0].dispatchEvent(new Event('click', { bubbles: true }))
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
sessionStorage.setItem(DISCLAIMER_FLAG, '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
seedReport()
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
describe('disclaimer', () => {
it('shows the catalog scope_disclaimer once per session and records the flag', async () => {
sessionStorage.removeItem(DISCLAIMER_FLAG)
render(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
const dialog = await screen.findByRole('dialog', { name: fr['editor.disclaimer_title'] })
expect(dialog.textContent).toContain('Aucun diagnostic médical')
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.understood'] }))
expect(sessionStorage.getItem(DISCLAIMER_FLAG)).toBe('1')
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
})
})
describe('plain zone (toggle)', () => {
it('adds the zone on first click and removes it on second click', async () => {
await mount()
clickZone(HINGE)
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HINGE }]))
clickZone(HINGE)
await waitFor(() => expect(zonesOf()).toEqual([]))
})
it('highlights the zone of the active observation with data-state="current"', async () => {
await mount()
clickZone(HINGE)
await waitFor(() =>
expect(document.querySelector(`[data-anno-id="${HINGE}"]`)?.getAttribute('data-state')).toBe('current'),
)
})
})
describe('no active observation (fallback)', () => {
it('re-activates the last observation and drops the click (user must click again)', async () => {
await mount()
// Collapse the only card through the UI (sets activeObservationIndex to -1).
await userEvent.click(screen.getByRole('button', { name: `${fr['observation.collapse_aria']} 1` }))
await waitFor(() => expect(activeIndex()).toBe(-1))
clickZone(HINGE)
await waitFor(() => expect(activeIndex()).toBe(0))
expect(zonesOf()).toEqual([])
clickZone(HINGE)
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HINGE }]))
})
})
describe('detail trigger', () => {
it('opens the detail modal, never adds the trigger as a zone, and zones clicked inside carry detailSourceId', async () => {
await mount()
clickZone(TRIGGER)
const dialog = await screen.findByRole('dialog', { name: `${fr['editor.detail_title_prefix']}head` })
expect(zonesOf()).toEqual([])
await waitFor(() => expect(dialog.querySelector(`[data-anno-id="${ATM}"]`)).not.toBeNull())
clickZone(ATM, dialog)
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: ATM, detailSourceId: 'head' }]))
// Toggle off from inside the modal uses the same (boneId, detailSourceId) identity.
clickZone(ATM, dialog)
await waitFor(() => expect(zonesOf()).toEqual([]))
})
})
describe('spine zone (vertebral-precision)', () => {
it('adds the zone, opens the picker on the matching region, and never toggles off on re-click', async () => {
await mount()
clickZone(CERVICAL)
const dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
expect(zonesOf()).toEqual([{ boneId: CERVICAL }])
expect(within(dialog).getByRole('tab', { name: fr['vertebra.region.C'] })).toHaveAttribute('aria-selected', 'true')
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' }))
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: CERVICAL, vertebrae: [{ region: 'C', index: 3 }] }]))
clickZone(CERVICAL)
await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
expect(zonesOf()).toHaveLength(1)
})
it('cancelling the picker leaves a spine zone without vertebrae', async () => {
await mount()
clickZone(CERVICAL)
const dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.cancel'] }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(zonesOf()).toEqual([{ boneId: CERVICAL }])
})
it('picking another region in the picker spawns that region zone and pruning to zero removes a zone', async () => {
await mount()
clickZone(CERVICAL)
let dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' }))
await userEvent.click(within(dialog).getByRole('tab', { name: fr['vertebra.region.L'] }))
await userEvent.click(within(dialog).getByRole('button', { name: 'L2' }))
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
await waitFor(() =>
expect(zonesOf()).toEqual([
{ boneId: CERVICAL, vertebrae: [{ region: 'C', index: 3 }] },
{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] },
]),
)
clickZone(CERVICAL)
dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' })) // uncheck
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] }]))
})
})
describe('bilateral zone', () => {
it('asks for a side, adds one zone per side, and clears both when both are present', async () => {
await mount()
clickZone(HIP)
let dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.left'] }))
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HIP, side: 'left' }]))
clickZone(HIP)
dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
expect(within(dialog).getByRole('button', { name: fr['lateral.left'] })).toBeDisabled()
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.right'] }))
await waitFor(() =>
expect(zonesOf()).toEqual([
{ boneId: HIP, side: 'left' },
{ boneId: HIP, side: 'right' },
]),
)
clickZone(HIP)
await waitFor(() => expect(zonesOf()).toEqual([]))
expect(screen.queryByRole('dialog')).toBeNull()
})
it('"both" adds the missing sides only', async () => {
await mount()
clickZone(HIP)
const dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.both'] }))
await waitFor(() =>
expect(zonesOf()).toEqual([
{ boneId: HIP, side: 'left' },
{ boneId: HIP, side: 'right' },
]),
)
})
})
describe('zone removal and orphan findings', () => {
it('KNOWN: removing a zone via ✕ keeps the findings attached to its catalog zone', async () => {
seedReport([
{
id: 'obs-a',
zones: [{ boneId: HINGE }],
findings: [
{
zoneId: 'c7-t1',
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
labelFrSnapshot: 'Fixation de la charnière',
labelEnSnapshot: 'Junction fixation',
},
],
freeTextFindings: [],
comment: '',
},
])
await mount()
const remove = await screen.findByRole('button', {
name: `${fr['observation.remove_zone']} Charnière C7-T1 (cervico-thoracique)`,
})
await userEvent.click(remove)
await waitFor(() => expect(zonesOf()).toEqual([]))
expect(useReportStore.getState().report!.observations[0].findings).toHaveLength(1)
})
it('shows one findings picker per (catalog zone, side) resolved by label match', async () => {
seedReport([
{
id: 'obs-b',
zones: [
{ boneId: HIP, side: 'left' },
{ boneId: HIP, side: 'right' },
{ boneId: HINGE },
{ boneId: TRIGGER },
],
findings: [],
freeTextFindings: [],
comment: '',
},
])
await mount()
await screen.findByRole('button', { name: /Hanche \(coxo-fémorale\) \(Gauche\)/ })
screen.getByRole('button', { name: /Hanche \(coxo-fémorale\) \(Droite\)/ })
screen.getByRole('button', { name: /^Charnière C7-T1 \(cervico-thoracique\)$/ })
// The trigger has no label and no catalog zone: exactly 3 pickers, and its
// badge falls back to the raw boneId.
expect(document.querySelectorAll('[aria-controls^="findings-zone-"]')).toHaveLength(3)
expect(
screen.getByRole('button', { name: `${fr['observation.remove_zone']} ${TRIGGER}` }),
).toBeInTheDocument()
})
})
@@ -1,127 +0,0 @@
/**
* Characterisation (Step 1): dictionary keys the runtime builds dynamically
* (severity.<fr value>, vertebra.region.<code>, import error kinds, PDF
* section labels), label fallbacks, the species registry and the
* scaffold script quirks (audit 12 §1).
*/
import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
import { boneLabel } from '@/anatomy/labels'
import { SeveritySchema, VertebralRegionSchema } from '@/domain/schema/observation'
import { getAllSpecies, getSpecies, speciesLabel } from '@/domain/species/registry'
import { EQUINE_VERTEBRAL_FORMULA } from '@/domain/species/equine/vertebrae'
import NewReportRoute from '@/app/routes/NewReportRoute'
import { useLocaleStore } from '@/state/localeStore'
const HERE = dirname(fileURLToPath(import.meta.url))
describe('dynamic dictionary keys', () => {
it('has a severity.* key for every stored severity value, in both dicts', () => {
for (const s of SeveritySchema.options) {
expect(fr[`severity.${s}`]).toBeTruthy()
expect(en[`severity.${s}`]).toBeTruthy()
}
})
it('has a vertebra.region.* key for every region code', () => {
for (const r of VertebralRegionSchema.options) {
expect(fr[`vertebra.region.${r}`]).toBeTruthy()
expect(en[`vertebra.region.${r}`]).toBeTruthy()
}
})
it('has one message per ImportError kind plus a generic one, with a {version} placeholder', () => {
for (const k of ['invalid_pdf', 'no_attachment', 'incompatible_version', 'generic']) {
expect(fr[`home.import.error_${k}`]).toBeTruthy()
expect(en[`home.import.error_${k}`]).toBeTruthy()
}
expect(fr['home.import.error_incompatible_version']).toContain('{version}')
expect(en['home.import.error_incompatible_version']).toContain('{version}')
})
it('exposes the PDF section and view labels used by the renderer', () => {
for (const k of [
'pdf.section.zones', 'pdf.section.findings_prefix', 'pdf.section.free_findings',
'pdf.section.severity', 'pdf.section.comment', 'pdf.section.conclusion',
'pdf.section.recommendations', 'pdf.section.next_appointment', 'pdf.view.general',
'pdf.view.detail_prefix', 'pdf.empty', 'pdf.title.suffix.bilan', 'pdf.subject',
]) {
expect(fr[k], k).toBeTruthy()
expect(en[k], k).toBeTruthy()
}
expect(fr['pdf.section.findings_prefix']).toBe('CONSTATS — ')
})
it('carries 71 svg_editor.* keys that die with the SVG editor', () => {
expect(Object.keys(fr).filter((k) => k.startsWith('svg_editor.'))).toHaveLength(71)
})
})
describe('label fallbacks', () => {
it('pickLocaleLabel falls back to the other language, then to the fallback', () => {
expect(pickLocaleLabel('FR', 'EN', 'fr')).toBe('FR')
expect(pickLocaleLabel('', 'EN', 'fr')).toBe('EN')
expect(pickLocaleLabel('FR', '', 'en')).toBe('FR')
expect(pickLocaleLabel('', '', 'en', 'id')).toBe('id')
expect(pickLocaleLabel(undefined, undefined, 'fr')).toBe('')
})
it('boneLabel returns the raw fallback for an unknown bone', () => {
expect(boneLabel(undefined, 'fr', 'point-x')).toBe('point-x')
})
})
describe('species registry', () => {
it('registers exactly one species, equine, with the committed manifest values', () => {
expect(getAllSpecies().map((s) => s.id)).toEqual(['equine'])
const eq = getSpecies('equine')!
expect(speciesLabel(eq, 'fr')).toBe('Cheval')
expect(speciesLabel(eq, 'en')).toBe('Horse')
expect(eq.vertebralFormula).toEqual({ C: 7, T: 18, L: 6, S: 5, Cd: 18 })
expect(EQUINE_VERTEBRAL_FORMULA).toEqual(eq.vertebralFormula)
})
it('the catalog loader resolves the same species id as the manifest', async () => {
const m = await getSpecies('equine')!.findings()
expect(m.default.species.id).toBe('equine')
})
it('NewReportRoute defaults the species select to equine', () => {
useLocaleStore.setState({ locale: 'fr' })
render(
<MemoryRouter>
<NewReportRoute />
</MemoryRouter>,
)
const select = screen.getByRole('combobox') as HTMLSelectElement
expect(select.value).toBe('equine')
expect(select.options).toHaveLength(1)
})
})
describe('scaffold script quirks (audit 12 §1, kept as-is, script slated for removal)', () => {
const src = readFileSync(resolve(HERE, '../../scripts/scaffold-species.mjs'), 'utf8')
it("writes schema_version '1.1' while the horse catalog is at '2.0'", () => {
expect(src).toContain("schema_version: '1.1'")
})
it('defaults the vertebral formula to C7 T13 L6 S5 Cd18 (mixed canine/equine)', () => {
expect(src).toMatch(/askPositiveInt\('\s*cervical \(C\)', 7\)/)
expect(src).toMatch(/askPositiveInt\('\s*thoracic \(T\)', 13\)/)
expect(src).toMatch(/askPositiveInt\('\s*lumbar \(L\)', 6\)/)
expect(src).toMatch(/askPositiveInt\('\s*sacral \(S\)', 5\)/)
expect(src).toMatch(/askPositiveInt\('\s*caudal \(Cd\)', 18\)/)
})
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
})
@@ -1,146 +0,0 @@
/**
* Characterisation (Step 1): public/pathology-editor.html, the standalone
* findings editor. Its JavaScript is extracted by text and evaluated so that
* the inline matcher, id generator, translations and species config are
* pinned without touching the file (BDR-020/021, LRN-026).
*
* Limitation: the DOM-editing behaviour (tree add/edit/delete, dirty flag,
* download) is not executed here; it is described in
* docs/faunosteo-audit/05-findings-editor.md §3.5 and will be re-specified
* as tests of the merged editor (plan Step 17).
*/
import { describe, it, expect } from 'vitest'
import { existsSync, readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { parseSvgBones } from '@/anatomy/svgConvention'
import { matchZoneFindings, normalizeLabel, scorePair } from '@/lib/zoneMatch'
import FINDINGS from '@/domain/species/equine/pathologies'
import { fr } from '@/i18n/fr'
const HERE = dirname(fileURLToPath(import.meta.url))
const ROOT = resolve(HERE, '../..')
const HTML = readFileSync(resolve(ROOT, 'public/pathology-editor.html'), 'utf8')
function slice(from: string, to: string): string {
const a = HTML.indexOf(from)
const b = HTML.indexOf(to, a)
if (a < 0 || b < 0) throw new Error(`markers not found: ${from} … ${to}`)
return HTML.slice(a, b)
}
type Zone = { id: string; name_fr: string; name_en: string }
interface InlineApi {
normalizeLabel: (s: string) => string
scorePair: (a: string, b: string) => number
matchZone: (fr: string, en: string, zones: Zone[]) => Zone | null
generateId: (en: string, fr: string, existing: string[]) => string
}
const matcherSrc = slice('function normalizeLabel(s)', '// ── Node stats ──')
const inline = new Function(
`${matcherSrc}; return { normalizeLabel, scorePair, matchZone, generateId };`,
)() as InlineApi
const translationsSrc = slice('var TRANSLATIONS = ', '\n };') + '\n };'
const TRANSLATIONS = new Function(`${translationsSrc} return TRANSLATIONS;`)() as {
fr: Record<string, string>
en: Record<string, string>
}
const configSrc = slice('var SPECIES_CONFIG = ', '\n ];') + '\n ];'
const SPECIES_CONFIG = new Function(`${configSrc} return SPECIES_CONFIG;`)() as Array<{
id: string
labelKey: string
jsonPath: string
views: Array<{ labelKey: string; svgPath: string }>
}>
function bones(file: string) {
const text = readFileSync(resolve(ROOT, 'public/species/equine', file), 'utf8')
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
return parseSvgBones(doc.documentElement as unknown as SVGSVGElement)
}
const zones = Object.values(FINDINGS.zones)
describe('inline matcher parity with src/lib/zoneMatch.ts', () => {
const labels: Array<{ fr: string; en: string }> = [
...[...bones('Horse.svg').values(), ...bones('Horse_head.svg').values()].map((b) => ({ fr: b.fr, en: b.en })),
{ fr: 'Hanche', en: 'Hip' },
{ fr: 'ATM', en: 'TMJ' },
{ fr: 'Sphenoide', en: 'Sphenoidd' },
{ fr: 'Vertèbres sacrales', en: '' },
{ fr: '', en: '' },
{ fr: 'Boulet ant. (métacarpo-phalangien)', en: 'Fore fetlok' },
]
it('returns the same zone for every real annotation and edge label', () => {
for (const l of labels) {
const app = matchZoneFindings(l, zones)?.id
const editor = inline.matchZone(l.fr, l.en, zones)?.id
expect(editor ?? undefined, `${l.fr} / ${l.en}`).toBe(app)
}
})
it('normalizes and scores identically', () => {
for (const s of ['Sphénoïde', 'Charnière C0-C1 (occipito-atloïdienne)', 'Temporomandibular Joint (TMJ)', '']) {
expect(inline.normalizeLabel(s)).toBe(normalizeLabel(s))
}
expect(inline.scorePair('Hip', 'Hip joint')).toBe(scorePair('Hip', 'Hip joint'))
expect(inline.scorePair('Sphenoidd', 'Sphenoid')).toBe(scorePair('Sphenoidd', 'Sphenoid'))
expect(inline.scorePair('', 'x')).toBe(scorePair('', 'x'))
})
})
describe('inline id generator', () => {
it('slugs name_en first, then name_fr, strips accents, suffixes -2 on sibling collision', () => {
expect(inline.generateId('Flexion restriction', 'Restriction en flexion', [])).toBe('flexion-restriction')
expect(inline.generateId('', 'Tension du splénius', [])).toBe('tension-du-splenius')
expect(inline.generateId('Hip', '', ['hip'])).toBe('hip-2')
expect(inline.generateId('Hip', '', ['hip', 'hip-2'])).toBe('hip-3')
expect(inline.generateId('', '', [])).toBe('node')
expect(inline.generateId(' -- ', '', [])).toBe('node')
})
})
describe('inline translations and config', () => {
it('fr and en share the same key set (76 keys), independent from the app dictionary', () => {
const frKeys = Object.keys(TRANSLATIONS.fr).sort()
const enKeys = Object.keys(TRANSLATIONS.en).sort()
expect(frKeys).toEqual(enKeys)
expect(frKeys).toHaveLength(76)
// No shared key space with src/i18n (different naming scheme)
expect(frKeys.filter((k) => k in fr)).toEqual([])
})
it('shares only the locale storage key with the app', () => {
expect(HTML).toContain("localStorage.getItem('osteo:locale')")
expect(HTML).toContain("localStorage.setItem('osteo:locale'")
})
it('hard-codes a single species (equine) with two views and the public JSON copy', () => {
expect(SPECIES_CONFIG).toHaveLength(1)
const [equine] = SPECIES_CONFIG
expect(equine.id).toBe('equine')
expect(equine.jsonPath).toBe('/species/equine/pathologies.json')
expect(equine.views.map((v) => v.svgPath)).toEqual([
'/species/equine/Horse.svg',
'/species/equine/Horse_head.svg',
])
for (const p of [equine.jsonPath, ...equine.views.map((v) => v.svgPath)]) {
expect(existsSync(resolve(ROOT, 'public', p.slice(1))), p).toBe(true)
}
})
it('imports nothing from src/ and declares noindex', () => {
expect(HTML).not.toMatch(/from\s+['"]\.\.?\/src/)
expect(HTML).not.toMatch(/<script[^>]+src=/)
expect(HTML).toMatch(/name="robots"\s+content="noindex,\s*nofollow"/)
})
it('validates only three top-level keys of the loaded JSON (no Zod)', () => {
expect(HTML).toMatch(/schema_version/)
expect(HTML).not.toMatch(/zod/i)
})
})
-250
View File
@@ -1,250 +0,0 @@
/**
* Characterisation (Step 1): the full PDF pipeline on the golden fixture
* (every zone kind, findings with vet flag and side, free text, severity,
* comment, conclusion, next appointment): page count, drawn text, attachment
* roundtrip, import error kinds, and the attachment fallback path.
*
* Text is captured by spying on PDFPage.drawText (pdf-lib has no text
* extraction). Rasterization is replaced by a 1×1 PNG: happy-dom has no
* canvas. SVG fetches are served from the committed files; logo fetches 404
* on purpose to pin the "PDF without logos" degradation.
*/
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest'
import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import full from '../fixtures/report-v2.full.json'
import type { Report } from '@/domain/schema/report'
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: vi.fn(async () => ONE_PX_PNG) }))
const HERE = dirname(fileURLToPath(import.meta.url))
const FILES: Record<string, string> = {
'/species/equine/Horse.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8'),
'/species/equine/Horse_head.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8'),
}
const fetched: string[] = []
const realFetch = globalThis.fetch
beforeAll(() => {
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = String(input)
fetched.push(url)
const text = FILES[url]
if (text) return new Response(text, { status: 200, headers: { 'content-type': 'image/svg+xml' } })
return new Response('not found', { status: 404 })
}) as typeof fetch
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => {
globalThis.fetch = realFetch
})
const report = full as Report
let drawn: string[] = []
beforeEach(() => {
drawn = []
fetched.length = 0
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (this: PDFPage, text: string) {
drawn.push(text)
} as never)
})
/** Rebuilds wrapped values: lines are drawn one by one, joined by a space. */
const joined = () => drawn.join(' ').replace(/\s+/g, ' ')
describe('export on the full fixture (FR)', () => {
it('produces one page per observation plus a conclusion page', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
expect(doc.getPageCount()).toBe(report.observations.length + 1)
expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
expect(doc.getAuthor()).toBe('Dr. Claire Dupont')
})
it('re-fetches the SVGs from public/ and the logos at export time (external dependencies)', async () => {
await exportReportToPdf(report, { locale: 'fr' })
const svgFetches = fetched.filter((u) => u.endsWith('.svg') && u.includes('/species/'))
// buildZoneLabels (2) + one colorized view per rendered image (general ×2, head ×1)
expect(svgFetches.filter((u) => u.endsWith('Horse.svg')).length).toBeGreaterThanOrEqual(3)
expect(svgFetches.filter((u) => u.endsWith('Horse_head.svg')).length).toBeGreaterThanOrEqual(2)
expect(fetched.some((u) => u.includes('/assets/') && u.endsWith('.png'))).toBe(true)
})
it('draws the ZONES section as bullet rows with vertebrae and side suffixes', async () => {
await exportReportToPdf(report, { locale: 'fr' })
expect(drawn).toContain(fr['pdf.section.zones'])
const zonesIdx = drawn.indexOf(fr['pdf.section.zones'])
// The ' · ' joined value is split back into one row per zone with a bullet glyph.
expect(drawn.slice(zonesIdx + 1, zonesIdx + 6)).toEqual([
'Charnière C7-T1 (cervico-thoracique)',
'•',
'Hanche (coxo-fémorale) (Gauche)',
'•',
'Hanche (coxo-fémorale) (Droite)',
])
expect(drawn).toContain('Vertèbres cervicales (C3, C4)')
expect(drawn).toContain('Articulation Temporo-Mandibulaire (ATM)')
})
it('draws one CONSTATS section per (catalog zone, side) with snapshot labels and the (!) vet marker', async () => {
await exportReportToPdf(report, { locale: 'fr' })
const prefix = fr['pdf.section.findings_prefix']
expect(drawn).toContain(`${prefix}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`)
expect(drawn).toContain(`${prefix}HANCHE (COXO-FÉMORALE) (GAUCHE)`)
expect(drawn).toContain(`${prefix}VERTÈBRES CERVICALES`)
expect(drawn).toContain(`${prefix}ARTICULATION TEMPORO-MANDIBULAIRE (ATM)`)
expect(drawn).toContain('Fixation de la charnière')
expect(drawn).toContain('Restriction en flexion')
expect(drawn.some((l) => l.startsWith('(!) Trébuchements'))).toBe(true)
expect(drawn).toContain('(!) Headshaking (secouement de tête)')
})
it('draws free findings, severity, comment, and the view captions', async () => {
await exportReportToPdf(report, { locale: 'fr' })
expect(drawn).toContain(fr['pdf.section.free_findings'])
expect(drawn).toContain('Sensibilité au garrot')
expect(drawn).toContain(fr['pdf.section.severity'])
expect(drawn).toContain(fr['severity.modérée'])
expect(drawn).toContain(fr['severity.sévère'])
expect(drawn).toContain(fr['pdf.section.comment'])
expect(drawn).toContain('Réagit à la palpation du garrot.')
expect(drawn.filter((l) => l === fr['pdf.view.general'])).toHaveLength(2)
expect(drawn).toContain(`${fr['pdf.view.detail_prefix']}HEAD`)
})
it('draws the conclusion page and the header identity on every page', async () => {
await exportReportToPdf(report, { locale: 'fr' })
expect(drawn).toContain(fr['pdf.section.conclusion'])
expect(drawn).toContain(fr['pdf.section.recommendations'])
expect(drawn).toContain(fr['pdf.section.next_appointment'])
expect(joined()).toContain('Dysfonction cervico-thoracique avec compensation du bassin.')
expect(drawn.filter((l) => l === 'Dr. Claire Dupont').length).toBe(4)
expect(drawn.filter((l) => l.includes('12345678901234')).length).toBe(4)
})
it('uses the EN snapshots and dictionary when locale=en, same attachment bytes', async () => {
const frBytes = await exportReportToPdf(report, { locale: 'fr' })
const frDrawn = [...drawn]
drawn = []
const enBytes = await exportReportToPdf(report, { locale: 'en' })
expect(drawn).toContain(en['pdf.section.zones'])
expect(drawn).toContain(`${en['pdf.section.findings_prefix']}HIP JOINT (LEFT)`)
expect(drawn).toContain('Junction fixation')
expect(drawn).toContain('(!) Headshaking')
expect(frDrawn).not.toContain('Junction fixation')
const a = await importReportFromPdf(frBytes)
const b = await importReportFromPdf(enBytes)
expect(a).toEqual(b)
})
})
describe('roundtrip and import', () => {
it('re-imports the full fixture unchanged (deep equality)', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const imported = await importReportFromPdf(bytes)
expect(imported).toEqual(report)
})
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, description "Faunosteo state v2"', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) => String(o))
const filespec = objects.find((s) => s.includes('/Type /Filespec'))!
expect(filespec).toContain('/F (osteo-report.json)')
expect(filespec).toContain('/AFRelationship /Data')
// /Desc is a UTF-16BE hex string: "Faunosteo state v2"
expect(filespec).toContain('/Desc <FEFF004600610075006E006F007300740065006F002000730074006100740065002000760032>')
const embedded = objects.find((s) => s.includes('/Type /EmbeddedFile'))!
expect(embedded).toContain('/Subtype /application#2Fjson')
expect(embedded).toContain('/Filter /FlateDecode')
expect(objects.some((s) => s.includes('/EmbeddedFiles'))).toBe(true)
})
it('pdf-lib 1.17.1 has no getAttachments: the object-traversal fallback IS the import path', async () => {
expect(typeof (PDFDocument.prototype as unknown as { getAttachments?: unknown }).getAttachments).toBe('undefined')
})
it('reports incompatible_version with the found version for a v3 attachment', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(new TextEncoder().encode(JSON.stringify({ ...report, version: 3 })), 'osteo-report.json', {
mimeType: 'application/json',
afRelationship: AFRelationship.Data,
})
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
expect(err).toBeInstanceOf(ImportError)
expect((err as ImportError).kind).toBe('incompatible_version')
expect((err as ImportError).foundVersion).toBe(3)
})
it('KNOWN: a foreign JSON attachment is picked up by the traversal and fails as no_attachment', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(new TextEncoder().encode('{"hello":1}'), 'other.json', {
mimeType: 'application/json',
afRelationship: AFRelationship.Data,
})
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
expect(err).toBeInstanceOf(ImportError)
expect((err as ImportError).kind).toBe('no_attachment')
})
it('KNOWN: a Zod-invalid report attachment is also reported as no_attachment (cause lost)', async () => {
const doc = await PDFDocument.create()
doc.addPage()
const broken = { ...report, practitioner: { name: '' } }
await doc.attach(new TextEncoder().encode(JSON.stringify(broken)), 'osteo-report.json', {
mimeType: 'application/json',
afRelationship: AFRelationship.Data,
})
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
expect((err as ImportError).kind).toBe('no_attachment')
})
it('an orphan finding (zone removed) is still printed under its catalog zone', async () => {
const orphaned: Report = {
...report,
observations: [{ ...report.observations[0], zones: [] }],
}
await exportReportToPdf(orphaned, { locale: 'fr' })
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`)
expect(drawn).toContain(fr['pdf.empty'])
})
it('an unknown boneId is printed raw and an unknown zoneId is printed raw', async () => {
const stale: Report = {
...report,
observations: [
{
...report.observations[0],
zones: [{ boneId: 'point-gone' }],
findings: [
{
zoneId: 'zone-gone',
path: ['x'],
labelFrSnapshot: 'Snapshot FR',
labelEnSnapshot: 'Snapshot EN',
},
],
},
],
}
await exportReportToPdf(stale, { locale: 'fr' })
expect(drawn).toContain('point-gone')
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`)
expect(drawn).toContain('Snapshot FR')
})
})
@@ -1,115 +0,0 @@
/**
* Characterisation (Step 1): what the Report v2 schema accepts or rejects,
* what the browser persistence keeps, and the storage keys the SaaS
* migration must read (plan Step 14 one-time draft import).
*/
import { describe, it, expect, beforeEach } from 'vitest'
import { ReportSchema } from '@/domain/schema/report'
import { ObservationSchema, VertebraSchema, SeveritySchema } from '@/domain/schema/observation'
import { readPersistedDraft, useReportStore } from '@/state/reportStore'
import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache'
import { useLocaleStore } from '@/state/localeStore'
import full from '../fixtures/report-v2.full.json'
import minimal from '../fixtures/report-v2.minimal.json'
import type { Report } from '@/domain/schema/report'
describe('Report v2 schema on the golden fixtures', () => {
it('accepts both fixtures unchanged', () => {
expect(ReportSchema.parse(full)).toEqual(full)
expect(ReportSchema.parse(minimal)).toEqual(minimal)
})
it('strips unknown keys silently (forward-compat fields are lost on reimport)', () => {
const parsed = ReportSchema.parse({ ...minimal, futureField: 1, animal: { ...minimal.animal, chip: 'x' } })
expect(parsed).toEqual(minimal)
})
it('rejects version 1 and 3, accepts only the literal 2', () => {
expect(ReportSchema.safeParse({ ...minimal, version: 1 }).success).toBe(false)
expect(ReportSchema.safeParse({ ...minimal, version: 3 }).success).toBe(false)
})
it('does not bound vertebra indexes by the species formula (C99 accepted)', () => {
expect(VertebraSchema.safeParse({ region: 'C', index: 99 }).success).toBe(true)
expect(VertebraSchema.safeParse({ region: 'X', index: 1 }).success).toBe(false)
expect(VertebraSchema.safeParse({ region: 'C', index: 0 }).success).toBe(false)
})
it('stores severities as French enum values', () => {
expect(SeveritySchema.options).toEqual(['légère', 'modérée', 'sévère'])
})
it('accepts findings whose zoneId matches no zone of the observation (orphans)', () => {
const obs = { ...full.observations[0], zones: [] }
expect(ObservationSchema.safeParse(obs).success).toBe(true)
})
it('accepts a speciesId that no manifest registers (checked only at render time)', () => {
expect(ReportSchema.safeParse({ ...minimal, animal: { speciesId: 'dragon', name: 'X' } }).success).toBe(true)
})
it('accepts two zones with the same boneId and different sides, and the same boneId from main and detail', () => {
const obs = {
...minimal,
observations: [
{
id: 'o',
zones: [
{ boneId: 'a', side: 'left' },
{ boneId: 'a', side: 'right' },
{ boneId: 'a', detailSourceId: 'head' },
],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}
expect(ReportSchema.safeParse(obs).success).toBe(true)
})
})
describe('browser persistence', () => {
beforeEach(() => {
sessionStorage.clear()
localStorage.clear()
useReportStore.setState({ report: null, activeObservationIndex: 0 })
})
it('mirrors the full fixture to sessionStorage["osteo:draft"] and restores it unchanged', () => {
useReportStore.getState().hydrateReport(full as Report)
const raw = sessionStorage.getItem('osteo:draft')
expect(raw).not.toBeNull()
expect(JSON.parse(raw!)).toEqual(full)
expect(readPersistedDraft()).toEqual(full)
})
it('hydrateReport does not revalidate (an invalid report can enter the store, the draft is then unreadable)', () => {
const broken = { ...(minimal as Report), version: 7 } as unknown as Report
useReportStore.getState().hydrateReport(broken)
expect(useReportStore.getState().report?.version).toBe(7)
expect(readPersistedDraft()).toBeNull()
})
it('initReport creates one empty observation, a uuid id and version 2', () => {
const { observations, ...draft } = minimal as Report
void observations
useReportStore.getState().initReport({ ...draft, observations: [] } as never)
const r = useReportStore.getState().report!
expect(r.version).toBe(2)
expect(r.id).toMatch(/^[0-9a-f-]{36}$/)
expect(r.observations).toHaveLength(1)
expect(r.observations[0]).toMatchObject({ zones: [], findings: [], freeTextFindings: [], comment: '' })
})
it('caches the practitioner block under localStorage["osteo:lastPractitioner"]', () => {
writeCachedPractitioner(full.practitioner)
expect(JSON.parse(localStorage.getItem('osteo:lastPractitioner')!)).toEqual(full.practitioner)
expect(readCachedPractitioner()).toEqual(full.practitioner)
})
it('persists the locale under localStorage["osteo:locale"] (shared with pathology-editor.html)', () => {
useLocaleStore.getState().setLocale('en')
expect(localStorage.getItem('osteo:locale')).toBe('en')
})
})
@@ -1,222 +0,0 @@
/**
* Characterisation (Step 1): the real SVG assets, their attributes, the
* SVG ↔ catalog link computed by zoneMatch, the opens-detail ↔ manifest
* contract and the spine helpers on the real Horse.svg.
* Oracle: docs/faunosteo-audit/06-svg-findings-link.md §4 (full table).
*/
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { parseSvgBones } from '@/anatomy/svgConvention'
import { matchZoneFindings, scorePair, levenshtein, normalizeLabel } from '@/lib/zoneMatch'
import {
regionFromLabel,
findSpineZoneId,
collectSpineVertebrae,
syncSpineZones,
} from '@/lib/spineZones'
import { getSpecies } from '@/domain/species/registry'
import FINDINGS from '@/domain/species/equine/pathologies'
import type { Bone } from '@/anatomy/types'
const HERE = dirname(fileURLToPath(import.meta.url))
const HORSE_TEXT = readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8')
const HEAD_TEXT = readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8')
function parse(text: string): Map<string, Bone> {
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
return parseSvgBones(doc.documentElement as unknown as SVGSVGElement)
}
const horse = parse(HORSE_TEXT)
const head = parse(HEAD_TEXT)
const zones = Object.values(FINDINGS.zones)
/** Expected mapping, audit 06 §4. Trigger zone-mpby55kd is intentionally absent. */
const EXPECTED: Record<string, string> = {
'point-mpbwrkp0': 'hind-fetlock',
'point-mpbwsi9q': 'hock',
'point-mpbwt4fa': 'stifle',
'point-mpbwtst0': 'hip',
'point-mpbwugty': 'sacroiliac',
'point-mpbwv4xy': 'shoulder',
'point-mpbwvpvt': 'elbow',
'point-mpbwwaru': 'fore-fetlock',
'point-mpbwwxvn': 'fore-sesamoids',
'point-mpbwxnb4': 'l6-s1',
'point-mpbwyd9i': 't18-l1',
'point-mpbwyyc9': 'c7-t1',
'zone-mpbx00jq': 'caudal',
'zone-mpbx0xnp': 'sacral',
'zone-mpbx1rm9': 'lumbar',
'zone-mpbx2rpe': 'thoracic',
'zone-mpbx5hx2': 'cervical',
'point-mpbykomv': 'parietal',
'point-mpbylh35': 'frontal',
'point-mpbymcln': 'sphenoid',
'point-mpbyn2k3': 'temporal',
'point-mpbynls5': 'occipital',
'point-mpbyo7zq': 'atm',
'point-mpbyphay': 'ssb',
'point-mpbyq841': 'hyoid',
'point-mpbyqxbg': 'c0-c1',
}
describe('SVG attribute census (raw text, audit 03 §10.H)', () => {
const count = (attr: string) =>
(HORSE_TEXT.match(new RegExp(`${attr}="`, 'g')) ?? []).length +
(HEAD_TEXT.match(new RegExp(`${attr}="`, 'g')) ?? []).length
it('counts data-anno-* attributes across both files', () => {
expect(count('data-anno-id')).toBe(48)
expect(count('data-anno-category')).toBe(48)
expect(count('data-anno-category-name')).toBe(18)
expect(count('data-anno-name-fr')).toBe(47)
expect(count('data-anno-name-en')).toBe(47)
expect(count('data-anno-lateral')).toBe(18)
expect(count('data-anno-special')).toBe(5)
expect(count('data-anno-opens-detail')).toBe(1)
})
it('uses only five category slugs, two of them with degraded accents', () => {
const cats = new Set([...horse.values(), ...head.values()].map((b) => b.category))
expect([...cats].sort()).toEqual([
'articulations', 'cadrans-du-cr-ne', 'charni-res-vert-brales', 'os', 'zone-colonne',
])
})
it('lateral is always "bilateral", special always "vertebral-precision"', () => {
const all = [...horse.values(), ...head.values()]
expect(all.filter((b) => b.lateral).every((b) => b.lateral === 'bilateral')).toBe(true)
expect(all.filter((b) => b.lateral)).toHaveLength(9)
expect(all.filter((b) => b.special).every((b) => b.special === 'vertebral-precision')).toBe(true)
expect(all.filter((b) => b.special)).toHaveLength(5)
})
it('main and detail id spaces do not overlap (27 distinct ids)', () => {
const ids = new Set([...horse.keys(), ...head.keys()])
expect(ids.size).toBe(horse.size + head.size)
expect(ids.size).toBe(27)
})
it('Horse_head.svg is the same drawing as Horse.svg with a different viewBox', () => {
expect(HORSE_TEXT).toMatch(/viewBox="0 0 2073\.4 1629\.4"/)
expect(HEAD_TEXT).toMatch(/viewBox="60 100 500 380"/)
const body = (t: string) => t.split('\n').slice(2, 703).join('\n')
expect(body(HEAD_TEXT)).toBe(body(HORSE_TEXT))
})
})
describe('SVG ↔ catalog link (audit 06 §4)', () => {
it('maps the 26 named annotations to their catalog zone, exact EN and FR match', () => {
const all = new Map([...horse, ...head])
for (const [id, zoneId] of Object.entries(EXPECTED)) {
const bone = all.get(id)
expect(bone, id).toBeDefined()
const tree = matchZoneFindings({ fr: bone!.fr, en: bone!.en }, zones)
expect(tree?.id, id).toBe(zoneId)
expect(scorePair(bone!.en, tree!.name_en), `${id} EN`).toBe(0)
expect(scorePair(bone!.fr, tree!.name_fr), `${id} FR`).toBe(0)
}
})
it('leaves the detail trigger unmatched (no FR/EN name)', () => {
const trigger = horse.get('zone-mpby55kd')!
expect(trigger.fr).toBe('')
expect(trigger.en).toBe('')
expect(trigger.opensDetail).toBe('head')
expect(trigger.category).toBe('articulations')
expect(matchZoneFindings({ fr: trigger.fr, en: trigger.en }, zones)).toBeUndefined()
})
it('leaves no catalog zone orphaned', () => {
const matched = new Set(Object.values(EXPECTED))
expect(matched.size).toBe(26)
expect(zones.map((z) => z.id).filter((id) => !matched.has(id))).toEqual([])
})
it('no normalized EN or FR zone name is a substring of another (substring rule unreachable today)', () => {
for (const lang of ['name_en', 'name_fr'] as const) {
const norms = zones.map((z) => normalizeLabel(z[lang]))
for (let i = 0; i < norms.length; i += 1)
for (let j = 0; j < norms.length; j += 1)
if (i !== j) expect(norms[i].includes(norms[j]), `${lang} ${zones[i].id} ⊃ ${zones[j].id}`).toBe(false)
}
})
it('KNOWN: two FR pairs are within the fuzzy tolerance and would collide if EN ever diverged', () => {
const d = (a: string, b: string) => levenshtein(normalizeLabel(a), normalizeLabel(b))
const fetlock = d('Boulet ant. (métacarpo-phalangien)', 'Boulet post. (métatarso-phalangien)')
const spine = d('Vertèbres sacrales', 'Vertèbres caudales')
expect(fetlock).toBe(5)
expect(spine).toBe(3)
expect(scorePair('Boulet ant. (métacarpo-phalangien)', 'Boulet post. (métatarso-phalangien)')).toBe(2 + 5)
expect(scorePair('Vertèbres sacrales', 'Vertèbres caudales')).toBe(2 + 3)
})
})
describe('opens-detail ↔ species manifest', () => {
const species = getSpecies('equine')!
it('every opens-detail value is a key of species.details, and every key has one trigger', () => {
const triggers = [...horse.values()].filter((b) => b.opensDetail).map((b) => b.opensDetail!)
expect(triggers).toEqual(['head'])
for (const key of triggers) expect(species.details[key]).toBeDefined()
expect(Object.keys(species.details)).toEqual(['head'])
})
it('the detail SVG carries no trigger of its own (one level of detail)', () => {
expect([...head.values()].some((b) => b.opensDetail)).toBe(false)
})
it('manifest paths point at the two committed files', () => {
expect(species.mainSvg).toBe('/species/equine/Horse.svg')
expect(species.details.head).toBe('/species/equine/Horse_head.svg')
})
})
describe('spine helpers on the real Horse.svg', () => {
it('resolves each region to its zone-colonne polygon by label', () => {
expect(findSpineZoneId('C', horse)).toBe('zone-mpbx5hx2')
expect(findSpineZoneId('T', horse)).toBe('zone-mpbx2rpe')
expect(findSpineZoneId('L', horse)).toBe('zone-mpbx1rm9')
expect(findSpineZoneId('S', horse)).toBe('zone-mpbx0xnp')
expect(findSpineZoneId('Cd', horse)).toBe('zone-mpbx00jq')
})
it('KNOWN: hinge labels also resolve to a region, but hinges have no special so it is never used', () => {
expect(regionFromLabel(horse.get('point-mpbwyyc9')!.fr)).toBe('C')
expect(horse.get('point-mpbwyyc9')!.special).toBeUndefined()
})
it('spawns a lumbar zone from scratch and keeps a joint zone untouched', () => {
const next = syncSpineZones([{ boneId: 'point-mpbwtst0', side: 'left' }], [{ region: 'L', index: 2 }], horse)
expect(next).toEqual([
{ boneId: 'point-mpbwtst0', side: 'left' },
{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] },
])
})
it('collects vertebrae across spine zones with the clicked zone first', () => {
const zonesSel = [
{ boneId: 'zone-mpbx5hx2', vertebrae: [{ region: 'C' as const, index: 3 }] },
{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L' as const, index: 1 }] },
]
expect(collectSpineVertebrae(zonesSel, horse, 'zone-mpbx1rm9')).toEqual([
{ region: 'L', index: 1 },
{ region: 'C', index: 3 },
])
})
it('detail-sourced zones never count as spine zones', () => {
const next = syncSpineZones(
[{ boneId: 'zone-mpbx5hx2', detailSourceId: 'head' }],
[{ region: 'C', index: 1 }],
horse,
)
// passes through untouched, then a fresh cervical zone is spawned
expect(next[0]).toEqual({ boneId: 'zone-mpbx5hx2', detailSourceId: 'head' })
expect(next[1]).toEqual({ boneId: 'zone-mpbx5hx2', vertebrae: [{ region: 'C', index: 1 }] })
})
})
@@ -1,39 +1,110 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react' import { cleanup, render, waitFor } from '@testing-library/react'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import { buildViewSvg, parseDrawing, sanitizeSvg } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
vi.mock('@/anatomy/svgLoader', () => ({ let sheet: SheetIndex
loadSvg: vi.fn(async () => { beforeAll(async () => {
const doc = new DOMParser().parseFromString( sheet = await loadTestSheet()
`<svg xmlns="http://www.w3.org/2000/svg"> })
<circle data-anno-id="epaule" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder" afterEach(cleanup)
data-anno-category="articulation" class="bone osteo articulation hitbox bone-epaule" />
<circle data-anno-id="epaule" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
data-anno-category="articulation" class="bone osteo articulation visible bone-epaule" />
</svg>`,
'image/svg+xml',
)
return doc.documentElement as unknown as SVGSVGElement
}),
}))
beforeEach(() => vi.clearAllMocks()) describe('buildViewSvg', () => {
it('frames the main view on the asset box and the head view on its crop of the same drawing', () => {
describe('AnatomyCanvas', () => { const main = buildViewSvg(sheet, 'main', new Map())
it('renders the loaded SVG inline', async () => { const head = buildViewSvg(sheet, 'head', new Map())
render(<AnatomyCanvas src="/x.svg" boneStates={new Map()} onZoneClick={() => {}} />) expect(main.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
await waitFor(() => expect(head.getAttribute('viewBox')).toBe('60 100 500 380')
expect(document.querySelector('[data-anno-id="epaule"]')).not.toBeNull(), expect(main.querySelectorAll('path').length).toBe(
head.querySelectorAll('path').length,
) )
expect(main.querySelectorAll('[data-layer="annotations"]')).toHaveLength(1)
expect(main.querySelectorAll('[data-anno-id="hip"]')).toHaveLength(2)
expect(head.querySelectorAll('[data-anno-id="hip"]')).toHaveLength(0)
expect(head.querySelectorAll('[data-anno-id="atm"]')).toHaveLength(2)
expect(main.hasAttribute('width')).toBe(false)
}) })
it('calls onZoneClick with the clicked bone id', async () => { it('applies states as data-state on the generated markers', () => {
const onZoneClick = vi.fn() const svg = buildViewSvg(sheet, 'main', new Map([['stifle', 'current']]))
render(<AnatomyCanvas src="/x.svg" boneStates={new Map()} onZoneClick={onZoneClick} />) const marked = Array.from(
await waitFor(() => screen.getByTestId('anatomy-canvas')) svg.querySelectorAll('[data-state="current"]'),
;(document.querySelector('[data-anno-id="epaule"]') as Element).dispatchEvent( ).map((el) => el.getAttribute('data-anno-id'))
new Event('click', { bubbles: true }), expect(marked).toEqual(['stifle', 'stifle'])
})
it('sanitises scripts, embedded documents and handlers out of an asset', () => {
const root = parseDrawing(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><script>alert(1)</script><g onclick="x()"><a href="javascript:void(0)"><path d="M0 0"/></a></g><foreignObject/></svg>',
) )
await waitFor(() => expect(onZoneClick).toHaveBeenCalledWith('epaule')) sanitizeSvg(root)
expect(root.querySelector('script')).toBeNull()
expect(root.querySelector('foreignObject')).toBeNull()
expect(root.querySelector('g')!.hasAttribute('onclick')).toBe(false)
expect(root.querySelector('a')!.hasAttribute('href')).toBe(false)
expect(root.querySelector('path')).not.toBeNull()
expect(() => parseDrawing('<not svg')).toThrow()
})
})
describe('AnatomyCanvas', () => {
it('renders the view and delegates clicks on the generated markers to onZoneClick with the view id', async () => {
const onZoneClick = vi.fn()
const { container } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={onZoneClick}
/>,
)
await waitFor(() =>
expect(
container.querySelector('[data-anno-id="head-trigger"]'),
).not.toBeNull(),
)
const hip = container.querySelector('circle[data-anno-id="hip"]')!
hip.dispatchEvent(new Event('click', { bubbles: true }))
expect(onZoneClick).toHaveBeenCalledWith('hip', 'main')
container
.querySelector('path')!
.dispatchEvent(new Event('click', { bubbles: true }))
expect(onZoneClick).toHaveBeenCalledTimes(1)
})
it('restyles in place when the states change', async () => {
const { container, rerender } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={() => undefined}
/>,
)
await waitFor(() =>
expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull(),
)
rerender(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map([['hip', 'current']])}
onZoneClick={() => undefined}
/>,
)
expect(
container.querySelectorAll('[data-anno-id="hip"][data-state="current"]'),
).toHaveLength(2)
rerender(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={() => undefined}
/>,
)
expect(container.querySelectorAll('[data-state="current"]')).toHaveLength(0)
}) })
}) })
@@ -1,298 +1,237 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import {
import { render, screen } from '@testing-library/react' beforeAll,
describe,
expect,
it,
vi,
afterEach,
beforeEach,
} from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import type { Finding } from '@faunosteo/domain'
import FindingsTreePicker from '@/components/observation/FindingsTreePicker' import FindingsTreePicker from '@/components/observation/FindingsTreePicker'
import type { ZoneFindings } from '@/domain/schema/findings'
import type { Finding } from '@/domain/schema/observation'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
beforeEach(() => { let sheet: SheetIndex
// Navigator-detected default may land on EN in happy-dom; force FR so the beforeAll(async () => {
// FR-label assertions in this file remain stable regardless of the runner's sheet = await loadTestSheet()
// navigator.language.
useLocaleStore.setState({ locale: 'fr' })
}) })
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
const TREE: ZoneFindings = { describe('FindingsTreePicker on a sheet finding zone', () => {
id: 'sphenoid', it('drills down the hip zone and selects a leaf as a v3 finding with snapshots and side', async () => {
name_fr: 'Sphénoïde', const user = userEvent.setup()
name_en: 'Sphenoid', const onChange = vi.fn()
categories: [
{
id: 'dysfunctions',
name_fr: 'Dysfonctions',
name_en: 'Dysfunctions',
children: [
{
id: 'flexion',
name_fr: 'Flexion',
name_en: 'Flexion',
description_fr: 'Description test',
},
{
id: 'extension',
name_fr: 'Extension',
name_en: 'Extension',
requires_vet_referral: true,
},
],
},
],
}
describe('FindingsTreePicker', () => {
it('renders the zone name in the initial breadcrumb', () => {
render( render(
<FindingsTreePicker <FindingsTreePicker
zoneId="sphenoid" zone={sheet.findingZone('hip')!}
tree={TREE} side="left"
selected={[]}
onChange={() => {}}
/>,
)
expect(screen.getByText('Sphénoïde')).toBeInTheDocument()
})
it('drills into a category and shows leaves', async () => {
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={[]}
onChange={() => {}}
/>,
)
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions'))
expect(screen.getByLabelText('Flexion')).toBeInTheDocument()
expect(screen.getByLabelText('Extension')).toBeInTheDocument()
})
it('emits a Finding with snapshot labels on leaf select', async () => {
const onChange = vi.fn<(next: Finding[]) => void>()
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={[]} selected={[]}
onChange={onChange} onChange={onChange}
/>, />,
) )
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions')) expect(screen.getByText('Hanche (coxo-fémorale)')).toBeInTheDocument()
await userEvent.click(screen.getByLabelText('Flexion')) await user.click(
expect(onChange).toHaveBeenCalledTimes(1) screen.getByRole('button', {
expect(onChange.mock.calls[0][0]).toEqual([ name: 'Ouvrir Dysfonctions ostéopathiques',
}),
)
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Restrictions de mobilité articulaire',
}),
)
await user.click(
screen.getByRole('checkbox', { name: 'Restriction en flexion' }),
)
expect(onChange).toHaveBeenCalledWith([
{ {
zoneId: 'sphenoid', findingZoneId: 'hip',
path: ['dysfunctions', 'flexion'], path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
labelFrSnapshot: 'Flexion', labelFrSnapshot: 'Restriction en flexion',
labelEnSnapshot: 'Flexion', labelEnSnapshot: 'Flexion restriction',
side: 'left',
}, },
]) ])
}) })
it('flags vet-referral leaves with requiresVetReferral on selection', async () => { it('shows descriptions in the active locale, the vet marker, counts, and unselects', async () => {
const onChange = vi.fn<(next: Finding[]) => void>() const user = userEvent.setup()
render( useLocaleStore.setState({ locale: 'en' })
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={[]}
onChange={onChange}
/>,
)
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions'))
await userEvent.click(screen.getByLabelText('Extension'))
expect(onChange.mock.calls[0][0][0].requiresVetReferral).toBe(true)
})
it('deselects a previously selected leaf', async () => {
const onChange = vi.fn<(next: Finding[]) => void>()
const selected: Finding[] = [ const selected: Finding[] = [
{ {
zoneId: 'sphenoid', findingZoneId: 'hip',
path: ['dysfunctions', 'flexion'], path: ['hip-dysfunctions', 'articular', 'hypermobility'],
labelFrSnapshot: 'Flexion', labelFrSnapshot: 'x',
labelEnSnapshot: 'Flexion', labelEnSnapshot: 'x',
requiresVetReferral: true,
}, },
] ]
const onChange = vi.fn()
render( render(
<FindingsTreePicker <FindingsTreePicker
zoneId="sphenoid" zone={sheet.findingZone('hip')!}
tree={TREE}
selected={selected} selected={selected}
onChange={onChange} onChange={onChange}
/>, />,
) )
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions')) expect(screen.getByLabelText('1 finding selected')).toBeInTheDocument()
await userEvent.click(screen.getByLabelText('Flexion')) await user.click(
screen.getByRole('button', { name: 'Open Osteopathic dysfunctions' }),
)
await user.click(
screen.getByRole('button', {
name: 'Open Articular mobility restrictions',
}),
)
expect(
screen.getByText(/Perceived laxity may indicate a ligament injury/),
).toBeInTheDocument()
expect(
screen.getAllByLabelText('Refer to a veterinarian').length,
).toBeGreaterThan(0)
const box = screen.getByRole('checkbox', {
name: 'Hypermobility / perceived laxity',
})
expect(box).toBeChecked()
await user.click(box)
expect(onChange).toHaveBeenCalledWith([]) expect(onChange).toHaveBeenCalledWith([])
await user.click(
screen.getByRole('button', { name: 'Back to previous level' }),
)
expect(
screen.getByRole('button', {
name: 'Open Articular mobility restrictions',
}),
).toBeInTheDocument()
}) })
it('navigates back to parent via the Retour button', async () => { it('flags a vet-referral leaf and omits the key on other leaves', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render( render(
<FindingsTreePicker <FindingsTreePicker
zoneId="sphenoid" zone={sheet.findingZone('hip')!}
tree={TREE} selected={[]}
onChange={onChange}
/>,
)
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Dysfonctions ostéopathiques',
}),
)
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Restrictions de mobilité articulaire',
}),
)
await user.click(
screen.getByRole('checkbox', { name: 'Hypermobilité / laxité perçue' }),
)
expect(onChange.mock.calls[0]![0][0].requiresVetReferral).toBe(true)
onChange.mockClear()
await user.click(
screen.getByRole('checkbox', { name: 'Hypomobilité globale' }),
)
expect(onChange.mock.calls[0]![0][0]).not.toHaveProperty(
'requiresVetReferral',
)
})
describe('count badges and scoping', () => {
const finding = (
path: string[],
extra: Partial<Finding> = {},
): Finding => ({
findingZoneId: 'hip',
path,
labelFrSnapshot: 'x',
labelEnSnapshot: 'x',
side: 'left',
...extra,
})
const base = [
finding(['hip-dysfunctions', 'articular', 'hypomobility']),
finding(['hip-dysfunctions', 'articular', 'hypermobility']),
finding(['hip-dysfunctions', 'muscular', 'trigger-points']),
]
function renderPicker(selected: Finding[]) {
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
side="left"
selected={selected}
onChange={vi.fn()}
/>,
)
}
it('counts selected findings per level, none on a clean sibling', async () => {
const user = userEvent.setup()
renderPicker(base)
expect(
screen.getByLabelText('3 constats sélectionnés'),
).toBeInTheDocument()
expect(screen.getAllByLabelText(/constats? sélectionnés?$/)).toHaveLength(
1,
)
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Dysfonctions ostéopathiques',
}),
)
expect(
screen.getByLabelText('2 constats sélectionnés'),
).toBeInTheDocument()
expect(screen.getByLabelText('1 constat sélectionné')).toBeInTheDocument()
expect(screen.getAllByLabelText(/constats? sélectionnés?$/)).toHaveLength(
2,
)
})
it('ignores findings of another zone or another side', async () => {
const user = userEvent.setup()
renderPicker([
finding(['hip-dysfunctions', 'articular', 'hypomobility'], {
findingZoneId: 'stifle',
}),
finding(['hip-dysfunctions', 'articular', 'hypomobility'], {
side: 'right',
}),
])
expect(screen.queryByLabelText(/sélectionnés?$/)).toBeNull()
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Dysfonctions ostéopathiques',
}),
)
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Restrictions de mobilité articulaire',
}),
)
expect(
screen.getByRole('checkbox', { name: 'Hypomobilité globale' }),
).not.toBeChecked()
})
})
it('the findings list carries no permanent compositing hint (text stays crisp)', () => {
render(
<FindingsTreePicker
zone={sheet.findingZone('hip')!}
selected={[]} selected={[]}
onChange={() => {}} onChange={() => {}}
/>, />,
) )
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions')) const ul = document.querySelector('ul') as HTMLElement
expect(screen.getByLabelText('Flexion')).toBeInTheDocument() expect(ul.getAttribute('style') ?? '').not.toContain('will-change')
await userEvent.click(screen.getByLabelText('Retour au niveau précédent')) expect(ul.style.willChange).toBe('')
expect(screen.getByLabelText('Ouvrir Dysfonctions')).toBeInTheDocument()
})
})
const DEEP_TREE: ZoneFindings = {
id: 'atm',
name_fr: 'ATM',
name_en: 'TMJ',
categories: [
{
id: 'dysf',
name_fr: 'Dysfonctions ostéopathiques de l\'ATM',
name_en: 'Osteopathic dysfunctions of the TMJ',
children: [
{
id: 'tensions',
name_fr: 'Tensions des muscles masticateurs',
name_en: 'Masticatory muscle tensions',
children: [
{
id: 'temporal',
name_fr: 'Tension du temporal',
name_en: 'Temporal tension',
},
{
id: 'pterygo',
name_fr: 'Tension des ptérygoïdiens',
name_en: 'Pterygoid tension',
},
{
id: 'masseter',
name_fr: 'Tension des masséters',
name_en: 'Masseter tension',
},
],
},
{
id: 'capsule',
name_fr: 'Dysfonction capsulaire',
name_en: 'Capsular dysfunction',
children: [
{ id: 'cap-ant', name_fr: 'Antérieure', name_en: 'Anterior' },
{ id: 'cap-post', name_fr: 'Postérieure', name_en: 'Posterior' },
],
},
],
},
],
}
describe('FindingsTreePicker selection counts on intermediate nodes', () => {
const selected: Finding[] = [
{
zoneId: 'atm',
path: ['dysf', 'tensions', 'temporal'],
labelFrSnapshot: 'Tension du temporal',
labelEnSnapshot: 'Temporal tension',
},
{
zoneId: 'atm',
path: ['dysf', 'tensions', 'pterygo'],
labelFrSnapshot: 'Tension des ptérygoïdiens',
labelEnSnapshot: 'Pterygoid tension',
},
]
it('shows a count badge of 2 on the top-level category when two descendant leaves are selected', () => {
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={selected}
onChange={() => {}}
/>,
)
// Root view: only the top-level "Dysfonctions..." category is visible.
expect(
screen.getByLabelText('2 constats sélectionnés'),
).toBeInTheDocument()
})
it('shows a count badge of 2 on the sub-category one level deeper', async () => {
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={selected}
onChange={() => {}}
/>,
)
await userEvent.click(
screen.getByLabelText('Ouvrir Dysfonctions ostéopathiques de l\'ATM'),
)
// Now we see "Tensions des muscles masticateurs" (2 leaves selected)
// and "Dysfonction capsulaire" (0 leaves selected — no badge).
expect(
screen.getByLabelText('2 constats sélectionnés'),
).toBeInTheDocument()
})
it('does not show a badge for siblings without selected descendants', async () => {
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={selected}
onChange={() => {}}
/>,
)
await userEvent.click(
screen.getByLabelText('Ouvrir Dysfonctions ostéopathiques de l\'ATM'),
)
// Capsular dysfunction has no selections — the button should not carry a badge label.
const capsular = screen.getByLabelText('Ouvrir Dysfonction capsulaire')
expect(capsular.textContent ?? '').not.toMatch(/\d/)
})
it('shows a singular badge label for exactly one selection', () => {
const oneSelected: Finding[] = [selected[0]]
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={oneSelected}
onChange={() => {}}
/>,
)
expect(
screen.getByLabelText('1 constat sélectionné'),
).toBeInTheDocument()
})
it('ignores selections from other zones when counting', () => {
const cross: Finding[] = [
{
zoneId: 'sphenoid',
path: ['dysf', 'tensions', 'temporal'],
labelFrSnapshot: 'Tension du temporal',
labelEnSnapshot: 'Temporal tension',
},
]
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={cross}
onChange={() => {}}
/>,
)
// No badge should appear on the ATM tree — the lone selected finding
// belongs to a different zone.
expect(
screen.queryByLabelText(/constat sélectionné/),
).not.toBeInTheDocument()
}) })
}) })
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more