diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 28f10b9a..53a23fd2 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -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. 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-.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. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 3e9e6eb1..8e80a667 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -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. Anomalies: ImageMagick MSVG drops `fill="none"` shapes and shapes with `` 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. + +--- + +## 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. + diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 6e63f40f..e10c4477 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -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). - 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 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. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 21b78bc8..04fc8d47 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -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. 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. + diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 5f83e6e6..75eae18f 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -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. - [ ] 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. -- [ ] 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) - - [ ] 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) - - [ ] 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) - - [ ] 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) - - [ ] 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] 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) + - [x] 5.0 freeze: golden v2 PDFs + expected v3 docs; CHARACTERIZATION_REPORT refreshed + - [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) + - [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 + - [x] 5.3 app foundation: bundledSheetProvider (Vite alias @sheets), sheetIndex, sanitiser, renderAnnotationLayer (legacy look), AnatomyCanvas/DetailModal on views (head = crop) + - [x] 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.5 PDF shim + attachment v3 + v2 import (gate D3) + - [x] 5.6 delete legacy (registry, species/*, zoneMatch, spineZones, svgConvention, D4 tools), SVG convention doc replaced, CLAUDE.md map, CHANGELOG, plan note, memory + - [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 --- diff --git a/.claude/tasks/contracts/2026-10-10-findings-picker-blur-2212.md b/.claude/tasks/contracts/2026-10-10-findings-picker-blur-2212.md new file mode 100644 index 00000000..fc43f6a0 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-10-findings-picker-blur-2212.md @@ -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) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6499fafd..d23809e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. - **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 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). diff --git a/CLAUDE.md b/CLAUDE.md index c381b6e4..d21c1166 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 (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`, -tables `species`, `anatomical_sheets` / `_versions` / `_assets`). The UI does not use -the client yet (local-only flows unchanged). +tables `species`, `anatomical_sheets` / `_versions` / `_assets`). Step 5 moved the +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. --- @@ -81,6 +83,12 @@ pnpm db:reset # replay from zero pnpm db:test # pgTAP on the real stack pnpm db:types # regenerate packages/supabase/src/database.types.ts 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 @@ -89,6 +97,9 @@ pnpm db:types:check # CI diff # Build image 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) 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 -`apps/app/tests/fixtures/`. Setup: `apps/app/tests/setup.ts` imports -@testing-library/jest-dom. Characterisation suite: files prefixed `char.`. +`apps/app/tests/fixtures/`. The 612 legacy catalog leaves run through the v2 → v3 migration +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` 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/ ├─ apps/app/ ← @faunosteo/app (everything below until packages/) -├─ public/ -│ ├─ species/equine/{Horse,Horse_head}.svg ← real anatomy SVGs -│ └─ pathology-editor.html ← standalone JSON editor (served as static file) +├─ public/ ← logos only (no anatomy asset: the sheet is bundled) +├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none) +├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts) ├─ src/ │ ├─ app/ │ │ ├─ 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 │ ├─ config/env.ts ← runtime config resolution -│ ├─ domain/ -│ │ ├─ schema/ ← Zod schemas (source of truth) -│ │ │ ├─ report.ts -│ │ │ ├─ observation.ts -│ │ │ ├─ practitioner.ts -│ │ │ ├─ animal.ts -│ │ │ └─ findings.ts -│ │ └─ species/ -│ │ ├─ types.ts ← SpeciesManifest interface -│ │ ├─ registry.ts ← getSpecies(), getAllSpecies() -│ │ └─ equine/{index,vertebrae,pathologies}.{ts,json} +│ ├─ sheets/{provider,useSheet}.ts ← SheetProvider interface, bundled implementation, per-species hook +│ ├─ services/ +│ │ ├─ sheetIndex.ts ← read-only lookups over the loaded sheet (ids, never labels) +│ │ └─ zoneInteraction.ts ← pure click decision + observation reducers (zones, sides, vertebrae) │ ├─ i18n/ │ │ ├─ types.ts ← Locale type + Dict type │ │ ├─ fr.ts + en.ts ← translation dicts (flat key → string) │ │ ├─ index.ts ← getDict(locale) │ │ └─ useT.ts ← useT() hook (reads localeStore) │ ├─ 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) │ │ └─ practitionerCache.ts ← localStorage prefill -│ ├─ anatomy/ -│ │ ├─ types.ts ← Bone, BoneCategory, BoneState -│ │ ├─ svgConvention.ts ← parseSvgBones() -│ │ ├─ svgLoader.ts ← loadSvg() -│ │ └─ labels.ts ← boneLabel(bone, locale, fallback) +│ ├─ anatomy/drawing.ts ← sanitised asset + generated annotation layer → inline <svg> per view │ ├─ components/ │ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip}.tsx │ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx -│ │ ├─ observation/{ObservationList,ObservationCard,FindingsTreePicker, +│ │ ├─ observation/{ObservationList,ObservationCard,ObservationPickers,FindingsTreePicker, │ │ │ VertebraPicker,SeveritySelector,LateralityPicker, │ │ │ FreeTextFindingInput}.tsx -│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm, +│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog, │ │ │ ConclusionPanel,NextAppointmentPicker}.tsx │ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx │ ├─ pdf/ │ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts │ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng,text,logo,linkAnnotation}.ts -│ ├─ lib/{dates,id,assert,zoneMatch,spineZones,supabase}.ts ← supabase.ts: getSupabaseClient() | null -│ ├─ styles/{index,tokens,svg-editor}.css ← Tailwind v4 CSS-first + SVG editor styles +│ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null +│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first │ └─ main.tsx ├─ tests/ │ ├─ setup.ts @@ -192,8 +193,7 @@ faunosteo/ │ ├─ entrypoint.sh ← injects env.js at container start │ └─ nginx.conf ← SPA fallback + PORT envsubst ├─ docs/ -│ ├─ ANATOMY-SVG-CONVENTION.md ← SVG data-* contract -│ ├─ ADDING-A-SPECIES.md +│ ├─ ANNOTATION-RENDERING.md ← annotation layer contract (attributes, styles, colours) │ ├─ PDF-FORMAT.md │ ├─ faunosteo-audit/ ← audit of the current system (frozen at 83e40af) │ ├─ development/ ← SaaS implementation plan, WORKSPACE.md @@ -204,7 +204,7 @@ faunosteo/ ├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only) │ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules │ └─ 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/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 @@ -215,9 +215,10 @@ faunosteo/ │ ├─ 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 │ ├─ 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) │ │ ├─ 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 ├─ packages/README.md ← shared packages index ├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker @@ -238,16 +239,19 @@ User interaction → Zustand store (reportStore) → 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 - → AnatomyCanvas fetches SVG text via loadSvg() - → parseSvgBones() walks DOM → Bone map - → delegated click listener → getBoneIdFromEvent() - → if spine-zone → VertebraPicker modal - → if data-anno-opens-detail → DetailModal (loads detail SVG) - → else → updateObservation() in store + → AnatomyCanvas builds the view: sanitised asset + renderAnnotationLayer() (markers from the document) + → delegated click on [data-anno-id] → decideZoneClick() (services/zoneInteraction, pure) + → open_view → DetailModal (same drawing, view_box crop, or the view's own asset) + → open_vertebra_picker / open_laterality_picker → pickers → reducers (ensureZone, addSides, syncVertebrae) + → toggle / remove_both_sides → updateObservation() in store PDF export - → exportReportToPdf(report, { locale }) + → exportReportToPdf(report, sheet, { locale }) → pdf-lib PDFDocument → embedFonts (Helvetica body + TimesRoman heading — WinAnsi StandardFonts; TTF Inter/Fraunces planned) → for each observation: addObservationPage (rasterize SVG → PNG) @@ -256,9 +260,9 @@ PDF export → Uint8Array → browser download PDF import - → importReportFromPdf(bytes) - → extractReportJson → Zod validate - → hydrateReport() → navigate /editor + → importReportFromPdf(bytes, migrationMap) + → extractReportJson → readReportDocument (v3 as is, v2 migrated, else incompatible_version) + → hydrateReport() → navigate /editor (unresolved zones/findings kept and flagged) Runtime 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 - 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 -- 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` ### Identity strings @@ -298,34 +302,40 @@ Database (Supabase) - Always read from ConfigProvider via useConfig() - src/config/env.ts is the only place with defaults -### SVG convention -- docs/ANATOMY-SVG-CONVENTION.md is the source of truth -- Every clickable element must have: data-anno-id, data-anno-name-fr, data-anno-name-en, data-anno-category -- SvgConventionError thrown on any missing required attribute -- Never rely on element id or className for click targeting — always data-anno-id +### Annotation rendering +- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the app draws + the markers from the document (`@faunosteo/anatomy/render`), with the attributes listed there +- Never rely on element id, className or a label for click targeting or behaviour — 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 -- 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 -- 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 - No direct store mutation outside Zustand 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) ### PDF - A4 portrait: 595.28 × 841.89 pt - 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 `⚠`). -### Pathology DB -- All entries must pass PathologySchema.parse() -- Each entry needs ≥1 source with citation -- boneIds: [] = all zones; speciesIds: [] = all species -- Source types: manual | journal | database | web +### Anatomical sheet content +- The findings catalog, the vertebral regions and the markers are the canonical sheet document; every content + change goes through `supabase/seed/anatomical-sheets/equine/curation/changes.json` (see the sheet model section) +- The curated draft is the reference content in development (`SHEET_BUNDLE=draft`); it is not medically + validated and a production build carries no sheet unless that flag is set on purpose ### Database (Supabase) - Platform roles (`platform_role`: owner/admin/moderator/support) are NOT professional @@ -403,12 +413,12 @@ Database (Supabase) ## Workflow expectations - Run `pnpm typecheck && pnpm test:run` before every commit. -- Domain schema changes (domain/schema/*.ts) require updating all callers + bumping version if breaking. -- SVG convention changes require updating docs/ANATOMY-SVG-CONVENTION.md first. -- Never modify anatomy SVGs in public/species/ — they are source assets from the user. -- Pathology DB entries must be source-cited before commit; client review required for MVP batch. -- Ask before any change to importReportFromPdf or extractReportJson — these handle user data. -- After PDF roundtrip tests fail: check attachment bytes, then Zod validation, then DecompressionStream inflation. +- Domain schema changes (`packages/domain/src/report/*.ts`) require updating all callers + bumping version if breaking. +- Annotation rendering changes require updating docs/ANNOTATION-RENDERING.md first. +- Never modify the legacy sources under `supabase/seed/anatomical-sheets/equine/legacy-sources/` — they are the + importer's input (the user's historical files). +- Ask before any change to importReportFromPdf, extractReportJson or readAttachedDocument — these handle user data. +- 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. - 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`). diff --git a/DEPLOY.md b/DEPLOY.md index 1669b53e..c971bb34 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -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 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 Expected change in `.env.example` (file not editable by the assistant): diff --git a/Dockerfile b/Dockerfile index 27e293d4..e5ae5525 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,12 @@ COPY packages/supabase/package.json packages/supabase/ 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 . . RUN pnpm --filter @faunosteo/app build diff --git a/README.md b/README.md index 9a196ae2..c075f883 100644 --- a/README.md +++ b/README.md @@ -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 restores the state for a follow-up. -Multi-species by design. MVP data set covers the **horse** (équin). Additional -species — dog, cat, goat, cow, pig, rabbit, donkey, sheep — drop in by adding -their SVG schematic + manifest + pathology file under `src/domain/species/`. -See [`docs/ADDING-A-SPECIES.md`](docs/ADDING-A-SPECIES.md) for the recipe. +Multi-species by design. The MVP ships the **horse** sheet: a canonical anatomical +sheet document (drawing + annotations + findings catalog, `packages/domain`) +generated and curated under `supabase/seed/anatomical-sheets/equine/`. Another +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, no central server in v1 — the PDF is the long-term record. Phase 2 will add @@ -19,20 +20,17 @@ contract. ## 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 - **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 -- **Detail popups** — click a zone (e.g. head) to open a secondary SVG with finer-grained zones -- **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 +- **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 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 - **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 - **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 -- **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 --- @@ -80,8 +78,9 @@ docker compose up --build ```bash pnpm typecheck # TypeScript strict, no emit 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 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 - [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/ADDING-A-SPECIES.md](docs/ADDING-A-SPECIES.md) — guide for adding a second species post-MVP -- [docs/PATHOLOGIES-FORMAT.md](docs/PATHOLOGIES-FORMAT.md) — findings catalog format + authoring guide +- [docs/ANNOTATION-RENDERING.md](docs/ANNOTATION-RENDERING.md) — annotation layer contract (markers drawn from the sheet document) +- [docs/development/ANATOMICAL_SHEET_MODEL.md](docs/development/ANATOMICAL_SHEET_MODEL.md) — canonical anatomical sheet document, curation pipeline, report migration map +- [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/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) @@ -117,25 +116,26 @@ For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy, ``` faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md) ├─ 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/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/state/ Zustand store + locale store + localStorage cache -├─ src/anatomy/ SVG parser + loader +├─ src/state/ Zustand store (Report v3) + persistence adapter + locale store +├─ src/anatomy/ drawing: sanitised asset + annotation layer → inline SVG per view ├─ src/components/ UI primitives, canvas, observation, report ├─ src/pdf/ export/import/attachment/fonts + renderers ├─ src/lib/ id, dates, assert utilities ├─ src/styles/ Tailwind v4 CSS + design tokens -├─ tests/unit/ vitest tests (apps/app/tests, incl. characterisation suite) -├─ packages/domain/ @faunosteo/domain: canonical anatomical sheet document (Zod) + integrity rules +├─ tests/unit/ vitest tests on the bundled sheet (+ frozen v2 fixtures) +├─ 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 -├─ 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 -├─ docs/ conventions + species guide + PDF spec -├─ index.html SPA entry point -└─ public/pathology-editor.html standalone pathology JSON editor (served as static file) +├─ docs/ conventions, sheet model, PDF spec, development plan +└─ index.html SPA entry point ``` --- @@ -146,16 +146,16 @@ v0.1.0 MVP — implementation complete. - `pnpm typecheck` ✅ - `pnpm lint` ✅ -- `pnpm test:run` ✅ — 271 tests across 39 files +- `pnpm test:run` ✅ — 367 tests across the workspace (domain, anatomy, supabase, app) - `pnpm build` ✅ -The first species data set ships with the real `Horse.svg` + `Horse_head.svg` -anatomy sources at `public/species/equine/` and a full v2.0 findings catalog -(26 zones, 792 nodes, 612 leaves, 41 vet-referral leaves) authored by the -domain expert. Adding **dog, cat, goat, cow, pig, rabbit, donkey, sheep** is -the same procedure: convention-compliant SVG + manifest + findings JSON. See -[docs/ADDING-A-SPECIES.md](docs/ADDING-A-SPECIES.md) and -[docs/PATHOLOGIES-FORMAT.md](docs/PATHOLOGIES-FORMAT.md). +The first species ships as the equine anatomical sheet: the historical +`Horse.svg`, `Horse_head.svg` and findings catalog (26 zones, 792 nodes) +imported, then audited and curated (`supabase/seed/anatomical-sheets/equine/`, +45 traced changes, 48 references). The application bundles that curated +draft in development (`SHEET_BUNDLE=draft`); it is not medically validated and +a production build carries no sheet unless asked. Another species is another +sheet document produced the same way. Manual QA checklist: `.claude/audits/MVP-QA.md` — walk it through `pnpm dev` before delivery. diff --git a/apps/app/package.json b/apps/app/package.json index 4e352035..b90f8665 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -12,9 +12,11 @@ "test": "vitest", "test:run": "vitest run", "lint": "eslint . --max-warnings 0", - "scaffold:species": "node scripts/scaffold-species.mjs" + "report:compare": "tsx scripts/compare-reports.ts" }, "dependencies": { + "@faunosteo/anatomy": "workspace:*", + "@faunosteo/domain": "workspace:*", "@faunosteo/supabase": "workspace:*", "motion": "^11.11.17", "pdf-lib": "^1.17.1", @@ -38,6 +40,7 @@ "eslint-plugin-react-hooks": "^5.1.0", "globals": "^15.14.0", "happy-dom": "^20.10.6", + "tsx": "^4.23.15", "typescript": "^5.7.2", "typescript-eslint": "^8.19.0", "vite": "^7.3.6", diff --git a/apps/app/public/pathology-editor.html b/apps/app/public/pathology-editor.html deleted file mode 100644 index adb79e21..00000000 --- a/apps/app/public/pathology-editor.html +++ /dev/null @@ -1,1700 +0,0 @@ -<!DOCTYPE html> -<html lang="fr" id="pe-html"> -<head> - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta name="robots" content="noindex,nofollow"> - <title>Faunosteo — Éditeur de pathologies - - - -
-
- Faunosteo - -
-
- - -
-
- -
-
-
-
-
- -
-
-

-
-
- -
- - -
-
- - - - diff --git a/apps/app/scripts/compare-reports.ts b/apps/app/scripts/compare-reports.ts new file mode 100644 index 00000000..87ca0b24 --- /dev/null +++ b/apps/app/scripts/compare-reports.ts @@ -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 ... [--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 { + 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 { + 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 ... [--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) + }, +) diff --git a/apps/app/scripts/compare/report.ts b/apps/app/scripts/compare/report.ts new file mode 100644 index 00000000..4917841c --- /dev/null +++ b/apps/app/scripts/compare/report.ts @@ -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 +} diff --git a/apps/app/scripts/scaffold-species.mjs b/apps/app/scripts/scaffold-species.mjs deleted file mode 100755 index c6f03e51..00000000 --- a/apps/app/scripts/scaffold-species.mjs +++ /dev/null @@ -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//` 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() - }) diff --git a/apps/app/src/anatomy/drawing.ts b/apps/app/src/anatomy/drawing.ts new file mode 100644 index 00000000..cbee6683 --- /dev/null +++ b/apps/app/src/anatomy/drawing.ts @@ -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 + +/** 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 ') + sanitizeSvg(root) + return root as unknown as SVGSVGElement +} + +const parsed = new Map() + +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 +} diff --git a/apps/app/src/anatomy/labels.ts b/apps/app/src/anatomy/labels.ts deleted file mode 100644 index fe2f0fed..00000000 --- a/apps/app/src/anatomy/labels.ts +++ /dev/null @@ -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) -} diff --git a/apps/app/src/anatomy/svgConvention.ts b/apps/app/src/anatomy/svgConvention.ts deleted file mode 100644 index 67c0c3cc..00000000 --- a/apps/app/src/anatomy/svgConvention.ts +++ /dev/null @@ -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 { - const map = new Map() - const all = svgRoot.querySelectorAll('[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 -} diff --git a/apps/app/src/anatomy/svgLoader.ts b/apps/app/src/anatomy/svgLoader.ts deleted file mode 100644 index 2084f78b..00000000 --- a/apps/app/src/anatomy/svgLoader.ts +++ /dev/null @@ -1,17 +0,0 @@ -export async function loadSvg(publicPath: string): Promise { - 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 `) - } - return root as unknown as SVGSVGElement -} diff --git a/apps/app/src/anatomy/types.ts b/apps/app/src/anatomy/types.ts deleted file mode 100644 index f0c3c03c..00000000 --- a/apps/app/src/anatomy/types.ts +++ /dev/null @@ -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' - } -} diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx index 706094d9..349d4e24 100644 --- a/apps/app/src/app/App.tsx +++ b/apps/app/src/app/App.tsx @@ -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 Footer from '@/components/brand/Footer' import HomeRoute from './routes/HomeRoute' import NewReportRoute from './routes/NewReportRoute' import EditorRoute from './routes/EditorRoute' -import SvgEditorRoute from './routes/SvgEditorRoute' -import EditorsRoute from './routes/EditorsRoute' import NotFoundRoute from './routes/NotFoundRoute' function AppShell() { - const hideFooter = useLocation().pathname === '/svg-editor' return (
@@ -17,12 +14,10 @@ function AppShell() { } /> } /> } /> - } /> - } /> } />
- {!hideFooter &&
} +
) } diff --git a/apps/app/src/app/routes/EditorRoute.tsx b/apps/app/src/app/routes/EditorRoute.tsx index d1d6d4c1..4e39cdbe 100644 --- a/apps/app/src/app/routes/EditorRoute.tsx +++ b/apps/app/src/app/routes/EditorRoute.tsx @@ -1,329 +1,151 @@ -import { useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useState } from 'react' import { useNavigate } from 'react-router-dom' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import DetailModal from '@/components/canvas/DetailModal' import ObservationList from '@/components/observation/ObservationList' -import VertebraPicker from '@/components/observation/VertebraPicker' -import { regionFromLabel } from '@/lib/spineZones' -import LateralityPicker from '@/components/observation/LateralityPicker' -import type { LateralSide } from '@/domain/schema/observation' +import ObservationPickers from '@/components/observation/ObservationPickers' import ConclusionPanel from '@/components/report/ConclusionPanel' import ReportHeader from '@/components/report/ReportHeader' -import PractitionerForm from '@/components/report/PractitionerForm' -import AnimalForm from '@/components/report/AnimalForm' +import EditInfosDialog, { + isIdentityComplete, + type Identity, +} from '@/components/report/EditInfosDialog' +import DisclaimerDialog from '@/components/report/DisclaimerDialog' import Button from '@/components/ui/Button' -import Dialog from '@/components/ui/Dialog' import { useReportStore } from '@/state/reportStore' import { writeCachedPractitioner } from '@/state/practitionerCache' -import { getSpecies } from '@/domain/species/registry' -import { loadSvg } from '@/anatomy/svgLoader' -import { parseSvgBones } from '@/anatomy/svgConvention' -import { collectSpineVertebrae, syncSpineZones } from '@/lib/spineZones' -import type { Bone, BoneState } from '@/anatomy/types' -import type { Observation, ObservationZone } from '@/domain/schema/observation' -import type { Report } from '@/domain/schema/report' -import type { SpeciesFindings } from '@/domain/schema/findings' -import type { Practitioner } from '@/domain/schema/practitioner' -import type { Animal, Owner } from '@/domain/schema/animal' +import { useLocaleStore } from '@/state/localeStore' +import { useSheet } from '@/sheets/useSheet' +import { pickLabel, type SheetIndex } from '@/services/sheetIndex' +import { + decideZoneClick, + ensureZone, + refOf, + removeAllSides, + removeZoneAt, + toggleZone, + type ZoneRef, +} from '@/services/zoneInteraction' +import type { ViewStates } from '@/anatomy/drawing' import { exportReportToPdf } from '@/pdf/export' import { useT } from '@/i18n/useT' -import { useLocaleStore } from '@/state/localeStore' -import { boneLabel } from '@/anatomy/labels' +import { DEFAULT_SPECIES_ID } from './NewReportRoute' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' -/** Merges newly parsed bones into the accumulated map without overwriting. */ -function mergeBones(prev: Map, parsed: Map) { - const merged = new Map(prev) - parsed.forEach((b, id) => { - if (!merged.has(id)) merged.set(id, b) - }) - return merged -} - +/** Editor on the reference sheet: wires the canvas, the pickers and the store. */ export default function EditorRoute() { const navigate = useNavigate() const t = useT() const locale = useLocaleStore((s) => s.locale) - const report = useReportStore((s) => s.report) - const activeIndex = useReportStore((s) => s.activeObservationIndex) - const addObservation = useReportStore((s) => s.addObservation) - const updateObservation = useReportStore((s) => s.updateObservation) - 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 store = useReportStore() + const { report, activeObservationIndex: activeIndex } = store + // Without a report yet (draft restore), the default species' sheet carries the migration map. + const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID) - const [bones, setBones] = useState>(new Map()) - const [detailBones, setDetailBones] = useState>(new Map()) - const [findings, setFindings] = useState(null) - const [disclaimer, setDisclaimer] = useState(null) - const [detail, setDetail] = useState<{ - id: string - src: string - title: string - } | null>(null) + const [detailViewId, setDetailViewId] = useState(null) const [vertebraTarget, setVertebraTarget] = useState(null) - const [lateralTarget, setLateralTarget] = useState<{ - boneId: string - detailSourceId?: string - } | null>(null) + const [lateralTarget, setLateralTarget] = useState(null) + const [disclaimer, setDisclaimer] = useState(null) const [exporting, setExporting] = useState(false) - const [editOpen, setEditOpen] = useState(false) - 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]) + const [editDraft, setEditDraft] = useState(null) useEffect(() => { window.scrollTo({ top: 0, left: 0, behavior: 'auto' }) }, []) - const species = useMemo( - () => (report ? getSpecies(report.animal.speciesId) : undefined), - [report], - ) + // No report in memory: restore the per-tab draft once the sheet is known. + useEffect(() => { + 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(() => { - if (!species) return - loadSvg(species.mainSvg).then((root) => setBones(parseSvgBones(root))) - 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 (sheet.status !== 'ready' || typeof sessionStorage === 'undefined') + return if (sessionStorage.getItem(DISCLAIMER_FLAG)) return - setDisclaimer(findings.scope_disclaimer) - }, [findings]) - - useEffect(() => { - if (!detail) return - 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 text = sheet.index.sheet.document.scope_disclaimer + setDisclaimer( + pickLabel({ fr: text.fr ?? '', en: text.en ?? '' }, locale) || null, + ) + }, [sheet, locale]) const activeObs = activeIndex >= 0 ? report?.observations[activeIndex] : undefined - const boneStates = useMemo>(() => { - const map = new Map() - if (!report || activeIndex < 0) return map - const active = report.observations[activeIndex] - if (!active) return map - active.zones.forEach((z) => { - map.set(z.boneId, 'current') - }) + const states = useMemo(() => { + const map = new Map() + activeObs?.zones.forEach((z) => map.set(z.annotationId, 'current')) return map - }, [report, activeIndex]) + }, [activeObs]) - function onToggleCard(index: number) { - setActiveObservation(activeIndex === index ? -1 : index) - } - - /** Opens the detail-popup modal for a bone that carries data-anno-opens-detail. */ - function handleDetailOpen(bone: Bone, detailId: string, detailSrc: string) { - setDetail({ - id: detailId, - src: detailSrc, - title: boneLabel(bone, locale, detailId), - }) - } - - /** - * No expanded observation — auto-expand the most recent one (or the - * first if no rows yet) so the click lands somewhere. Defers the actual - * zone add to the next render where activeObs is set. - */ - function activateFallbackObservation(report: Report) { - const fallbackIndex = - report.observations.length > 0 ? report.observations.length - 1 : -1 - if (fallbackIndex < 0) return - setActiveObservation(fallbackIndex) - } - - /** - * 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 onZoneClick = useCallback( + (annotationId: string) => { + // Fresh state: two clicks may land before React re-renders the handler. + const { report, activeObservationIndex: activeIndex } = + useReportStore.getState() + if (sheet.status !== 'ready' || !report) return + const activeObs = + activeIndex >= 0 ? report.observations[activeIndex] : undefined + const index = sheet.index + const annotation = index.annotation(annotationId) + const decision = decideZoneClick(annotation, activeObs) + if (!annotation) return + switch (decision.kind) { + case 'ignore': + return + case 'open_view': + return setDetailViewId(decision.viewId) + case 'activate_fallback': + return store.setActiveObservation(report.observations.length - 1) + case 'open_vertebra_picker': { + const { observation, index: zoneIndex } = ensureZone( + activeObs!, + annotation, + ) + store.updateObservation(activeIndex, observation) + return setVertebraTarget(zoneIndex) + } + case 'open_laterality_picker': + return setLateralTarget(refOf(annotation)) + case 'remove_both_sides': + return store.updateObservation( + activeIndex, + removeAllSides(activeObs!, refOf(annotation)), + ) + case 'toggle': + return store.updateObservation( + activeIndex, + toggleZone(activeObs!, annotation), + ) } - const nextZones = [...activeObs.zones, newZone] - targetIndex = nextZones.length - 1 - updateObservation(activeIndex, { ...activeObs, zones: nextZones }) - } - setVertebraTarget(targetIndex) + }, + [sheet, store], + ) + + function acknowledgeDisclaimer() { + sessionStorage?.setItem(DISCLAIMER_FLAG, '1') + setDisclaimer(null) } - /** 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) - .filter(Boolean) as LateralSide[] - - if (sidesPresent.includes('left') && sidesPresent.includes('right')) { - const nextZones = activeObs.zones.filter( - (z) => !(z.boneId === boneId && z.detailSourceId === detailSourceId), - ) - updateObservation(activeIndex, { ...activeObs, zones: nextZones }) - return - } - - setLateralTarget({ - boneId, - ...(detailSourceId ? { detailSourceId } : {}), - }) + function saveEditInfos() { + if (!editDraft) return + 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. */ - 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() { + async function onExport(index: SheetIndex) { if (!report) return setExporting(true) 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 url = URL.createObjectURL(blob) 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 ( +

+ {t('sheet.loading')} +

+ ) + } + if (sheet.status === 'none') return null + const index = sheet.index + const detailView = detailViewId ? index.view(detailViewId) : undefined return (
- + + setEditDraft({ + practitioner: report.practitioner, + animal: report.animal, + owner: report.owner, + }) + } + />
-
+
onZoneClick(id)} + index={index} + viewId={index.mainView.id} + states={states} + onZoneClick={onZoneClick} + className="flex-1" /> +

+ {t( + index.sheet.status === 'draft' + ? 'sheet.status.draft' + : 'sheet.status.published', + )} +

updateObservation(i, next)} + onToggle={(i) => + store.setActiveObservation(activeIndex === i ? -1 : i) + } + onAdd={store.addObservation} + onDelete={store.removeObservation} + onMoveUp={store.moveObservationUp} + onMoveDown={store.moveObservationDown} + sheet={index} + onChange={store.updateObservation} onOpenVertebraPicker={(_i, zoneIndex) => setVertebraTarget(zoneIndex) } onRemoveZone={(i, zoneIndex) => { const obs = report.observations[i] - if (!obs) return - const zones = obs.zones.filter((_, k) => k !== zoneIndex) - updateObservation(i, { ...obs, zones }) + if (obs) store.updateObservation(i, removeZoneAt(obs, zoneIndex)) }} />
-
- {detail && ( + {detailView && ( setDetail(null)} - detailSrc={detail.src} - detailId={detail.id} - title={`${t('editor.detail_title_prefix')}${detail.title}`} - boneStates={boneStates} - onZoneClick={(id, did) => onZoneClick(id, did)} + onClose={() => setDetailViewId(null)} + index={index} + viewId={detailView.id} + title={pickLabel(detailView.name, locale)} + states={states} + onZoneClick={onZoneClick} /> )} {editDraft && ( - -
- - setEditDraft((d) => (d ? { ...d, practitioner: next } : d)) - } - /> - - setEditDraft((d) => (d ? { ...d, animal: next } : d)) - } - onChangeOwner={(next) => - setEditDraft((d) => (d ? { ...d, owner: next } : d)) - } - /> -
- - -
-
-
+ setEditDraft(null)} + onSave={saveEditInfos} + /> )} {disclaimer && ( - -
-

{disclaimer}

-
- -
-
-
- )} - - {vertebraTarget !== null && - activeObs && - activeObs.zones[vertebraTarget] && ( - 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 && ( - setLateralTarget(null)} - title={boneLabel( - allBones.get(lateralTarget.boneId), - locale, - lateralTarget.boneId, - )} - 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) - }} + )} + + setVertebraTarget(null)} + onCloseLateral={() => setLateralTarget(null)} + />
) } diff --git a/apps/app/src/app/routes/EditorsRoute.tsx b/apps/app/src/app/routes/EditorsRoute.tsx deleted file mode 100644 index b795ddd2..00000000 --- a/apps/app/src/app/routes/EditorsRoute.tsx +++ /dev/null @@ -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 ( -
- -
-
- -

{t('editors.svg.title')}

-

- {t('editors.svg.description')} -

- - {t('editors.svg.cta')} - -
- -

{t('editors.pathology.title')}

-

- {t('editors.pathology.description')} -

- - {t('editors.pathology.cta')} - -
-
-
-
- ) -} diff --git a/apps/app/src/app/routes/HomeRoute.tsx b/apps/app/src/app/routes/HomeRoute.tsx index fa7ace68..0d0e61c6 100644 --- a/apps/app/src/app/routes/HomeRoute.tsx +++ b/apps/app/src/app/routes/HomeRoute.tsx @@ -5,25 +5,42 @@ import Button from '@/components/ui/Button' import Card from '@/components/ui/Card' import { importReportFromPdf, ImportError } from '@/pdf/import' import { useReportStore } from '@/state/reportStore' +import { useSheet } from '@/sheets/useSheet' +import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { useT } from '@/i18n/useT' export default function HomeRoute() { const navigate = useNavigate() const fileRef = useRef(null) const hydrate = useReportStore((s) => s.hydrateReport) + const sheet = useSheet(DEFAULT_SPECIES_ID) const [error, setError] = useState(null) const [busy, setBusy] = useState(false) const t = useT() async function onPickFile(e: React.ChangeEvent) { const file = e.target.files?.[0] - if (!file) return + if (!file || sheet.status !== 'ready') return setBusy(true) setError(null) try { const bytes = new Uint8Array(await file.arrayBuffer()) - const report = await importReportFromPdf(bytes) - hydrate(report) + const outcome = await importReportFromPdf( + 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') } catch (err) { if (err instanceof ImportError) { @@ -48,21 +65,58 @@ export default function HomeRoute() { } } + const noSheet = sheet.status === 'none' + return (
+ {noSheet && ( + +

+ {t('home.no_sheet.title')} +

+

+ {t('home.no_sheet.description')} +

+
+ )} -

{t('home.new_report.title')}

-

{t('home.new_report.description')}

- +

+ {t('home.new_report.title')} +

+

+ {t('home.new_report.description')} +

+
-

{t('home.import.title')}

-

{t('home.import.description')}

- - {error &&

{error}

} diff --git a/apps/app/src/app/routes/NewReportRoute.tsx b/apps/app/src/app/routes/NewReportRoute.tsx index 4bd0c003..e4dbdad1 100644 --- a/apps/app/src/app/routes/NewReportRoute.tsx +++ b/apps/app/src/app/routes/NewReportRoute.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' +import type { Animal, Owner, Practitioner } from '@faunosteo/domain' import PractitionerForm from '@/components/report/PractitionerForm' import AnimalForm from '@/components/report/AnimalForm' import AppHeader from '@/components/brand/AppHeader' @@ -7,18 +8,29 @@ import Button from '@/components/ui/Button' import Input from '@/components/ui/Input' import Label from '@/components/ui/Label' import { todayIso } from '@/lib/dates' -import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache' +import { + readCachedPractitioner, + writeCachedPractitioner, +} from '@/state/practitionerCache' import { useReportStore } from '@/state/reportStore' +import { useSheet } from '@/sheets/useSheet' import { useT } from '@/i18n/useT' +/** The one species this build ships a sheet for. */ +export const DEFAULT_SPECIES_ID = 'equine' + export default function NewReportRoute() { const navigate = useNavigate() const initReport = useReportStore((s) => s.initReport) const t = useT() + const sheet = useSheet(DEFAULT_SPECIES_ID) - const [practitioner, setPractitioner] = useState({ name: '' }) - const [animal, setAnimal] = useState({ speciesId: 'equine', name: '' }) - const [owner, setOwner] = useState({ name: '' }) + const [practitioner, setPractitioner] = useState({ name: '' }) + const [animal, setAnimal] = useState({ + speciesId: DEFAULT_SPECIES_ID, + name: '', + }) + const [owner, setOwner] = useState({ name: '' }) const [date, setDate] = useState(todayIso()) useEffect(() => { @@ -26,20 +38,27 @@ export default function NewReportRoute() { 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() { - if (!canSubmit) return + if (!canSubmit || sheet.status !== 'ready') return writeCachedPractitioner(practitioner) - initReport({ - date, - practitioner, - animal, - owner, - observations: [], - conclusion: '', - recommendations: '', - }) + initReport( + { + date, + practitioner, + animal, + owner, + observations: [], + conclusion: '', + recommendations: '', + }, + sheet.index.sheet.ref, + ) navigate('/editor') } @@ -47,16 +66,52 @@ export default function NewReportRoute() {
-

{t('new_report.title')}

+

+ {t('new_report.title')} +

+ {sheet.status === 'none' && ( +

+ {t('home.no_sheet.description')} +

+ )}
- setDate(e.target.value)} /> + setDate(e.target.value)} + />
- +
- - + +
diff --git a/apps/app/src/app/routes/NotFoundRoute.tsx b/apps/app/src/app/routes/NotFoundRoute.tsx index 7367e553..30e48ada 100644 --- a/apps/app/src/app/routes/NotFoundRoute.tsx +++ b/apps/app/src/app/routes/NotFoundRoute.tsx @@ -9,8 +9,12 @@ export default function NotFoundRoute() {

{t('not_found.title')}

-

{t('not_found.description')}

- +

+ {t('not_found.description')} +

+
) diff --git a/apps/app/src/app/routes/SvgEditorRoute.tsx b/apps/app/src/app/routes/SvgEditorRoute.tsx deleted file mode 100644 index e234961e..00000000 --- a/apps/app/src/app/routes/SvgEditorRoute.tsx +++ /dev/null @@ -1,1858 +0,0 @@ -import { useEffect, useRef } from 'react' -import { Link } from 'react-router-dom' -import AppHeader from '@/components/brand/AppHeader' -import { useT } from '@/i18n/useT' -import { useLocaleStore } from '@/state/localeStore' -import { getDict } from '@/i18n/index' -import type { Locale } from '@/i18n/types' -import { getAllSpecies, speciesLabel } from '@/domain/species/registry' -import '@/styles/svg-editor.css' - -type TFn = (key: string) => string - -export default function SvgEditorRoute() { - const canvasRef = useRef(null) - const canvasInnerRef = useRef(null) - const sidebarRef = useRef(null) - const cleanupRef = useRef<(() => void) | null>(null) - const t = useT() - const locale = useLocaleStore((s) => s.locale) - - useEffect(() => { - const meta = document.createElement('meta') - meta.name = 'robots' - meta.content = 'noindex,nofollow' - document.head.appendChild(meta) - return () => { - document.head.removeChild(meta) - } - }, []) - - useEffect(() => { - const canvas = canvasRef.current - const canvasInner = canvasInnerRef.current - const sidebar = sidebarRef.current - if (!canvas || !canvasInner || !sidebar) return - - const dict = getDict(locale) - const tFn: TFn = (key: string) => dict[key] ?? key - const cleanup = initSvgEditor(canvas, canvasInner, sidebar, tFn, locale) - cleanupRef.current = cleanup - - return () => { - cleanup() - cleanupRef.current = null - } - // Re-init when locale changes so all vanilla JS strings update - }, [locale]) - - return ( -
- - -
-
-
-
-
- -
-
-
- - ← - -
-

{t('svg_editor.title')}

-
{t('svg_editor.subtitle')}
-
-
-
- -
-
-

{t('svg_editor.file')}

- - - -
- -
-

{t('svg_editor.mode')}

- - - -
- - -
- - - - -
-
- -
-

{t('svg_editor.selected_element')}

-
- — -
- -
- -
- - -
-
- -
- - - - - - - - - - -
- - -
-
-
- -
- - -
-
-
-
- {t('svg_editor.polygon_editing')} -
- {t('svg_editor.polygon_drag')} -
- {t('svg_editor.polygon_insert')} -
- {t('svg_editor.polygon_delete')} -
- -
-
- -
-
- -
-

- {t('svg_editor.elements')} (0) -

- -
-
-
-
-
-
- ) -} - -function initSvgEditor( - canvas: HTMLDivElement, - canvasInner: HTMLDivElement, - _sidebar: HTMLDivElement, - t: TFn, - locale: Locale, -): () => void { - const ac = new AbortController() - const sig = { signal: ac.signal } - - let mode = 'select' - let selected: SVGElement | null = null - let polygonPoints: number[][] = [] - let dragging: SVGElement | null = null - let draggingHandle: { - vIdx: number - points: number[][] - originalPoint: number[] - polygon: SVGElement - } | null = null - let dragStart: { - x: number - y: number - snap?: ReturnType - siblingSnaps?: { el: SVGElement; snap: ReturnType }[] - } | null = null - let zoom = 1 - let svgRoot: SVGSVGElement | null = null - - const CATEGORY_TEMPLATES: Record = { - articulation: { color: '#fb5607', name: 'Articulations' }, - charniere: { color: '#d00000', name: 'Charnieres vertebrales' }, - 'cadran-crane': { color: '#06a77d', name: 'Cadrans du crane' }, - 'os-overlay': { color: '#f72585', name: 'Os overlay' }, - 'spine-zone': { color: '#7209b7', name: 'Zones colonne' }, - } - let CATEGORIES: Record< - string, - { color: string; name: string; visible: boolean; special?: string } - > = {} - - const DETAIL_ZONE_STYLE = { - fill: '#808080', - fillOpacity: '0.20', - stroke: '#606060', - strokeWidth: '2', - strokeDasharray: '8,4', - } - - const SPECIAL_BEHAVIORS = [ - { id: 'vertebral-precision', desc: 'Specify which vertebrae are involved' }, - { id: 'joint-detail', desc: 'Detail a joint (mobility, pain, etc.)' }, - ] - - const zoomContainer = document.getElementById('svg-editor-zoom-controls') - if (zoomContainer) { - zoomContainer.textContent = '' - const btnIn = document.createElement('button') - btnIn.textContent = '+' - btnIn.addEventListener('click', () => { - zoom *= 1.2 - applyZoom() - }, sig) - const btnOut = document.createElement('button') - btnOut.textContent = '−' - btnOut.addEventListener('click', () => { - zoom /= 1.2 - applyZoom() - }, sig) - const btnReset = document.createElement('button') - btnReset.textContent = '⌂' - btnReset.addEventListener('click', () => { - zoom = 1 - applyZoom() - }, sig) - zoomContainer.append(btnIn, btnOut, btnReset) - } - - let loadedFileName = 'horse_anatomy_edited.svg' - - const speciesList = getAllSpecies() - - setupGlobalListeners() - setupGlobalDragDrop() - showWelcomeScreen() - - function showWelcomeScreen() { - canvasInner.textContent = '' - const welcome = document.createElement('div') - welcome.className = 'welcome' - welcome.id = 'svg-editor-welcome' - - const icon = document.createElement('div') - icon.className = 'welcome-icon' - icon.textContent = '📐' - - const h2 = document.createElement('h2') - h2.textContent = t('svg_editor.welcome_title') - - const p = document.createElement('p') - p.textContent = t('svg_editor.welcome_text') - const code1 = document.createElement('code') - code1.textContent = 'data-anno-id' - const code2 = document.createElement('code') - code2.textContent = 'data-anno-category' - p.appendChild(code1) - p.appendChild(document.createTextNode(' & ')) - p.appendChild(code2) - p.appendChild(document.createTextNode(t('svg_editor.welcome_text_suffix'))) - - const tabBar = document.createElement('div') - tabBar.className = 'welcome-tabs' - const tabProject = document.createElement('button') - tabProject.className = 'welcome-tab active' - tabProject.textContent = t('svg_editor.source_project') - const tabUpload = document.createElement('button') - tabUpload.className = 'welcome-tab' - tabUpload.textContent = t('svg_editor.source_upload') - tabBar.append(tabProject, tabUpload) - - const tabContent = document.createElement('div') - tabContent.className = 'welcome-tab-content' - - function showProjectTab() { - tabProject.classList.add('active') - tabUpload.classList.remove('active') - tabContent.textContent = '' - buildProjectPicker(tabContent) - } - - function showUploadTab() { - tabUpload.classList.add('active') - tabProject.classList.remove('active') - tabContent.textContent = '' - buildUploadPicker(tabContent) - } - - tabProject.addEventListener('click', showProjectTab) - tabUpload.addEventListener('click', showUploadTab) - - welcome.append(icon, h2, p, tabBar, tabContent) - canvasInner.appendChild(welcome) - - showProjectTab() - - svgRoot = null - CATEGORIES = {} - selected = null - dragging = null - draggingHandle = null - refreshCategoryList() - refreshCategorySelects() - getEl('svg-editor-count').textContent = '0' - getEl('svg-editor-element-list').textContent = '' - getEl('svg-editor-edit-section').style.display = 'none' - getEl('svg-editor-file-btn').textContent = t('svg_editor.choose_file') - } - - function buildProjectPicker(container: HTMLElement) { - const speciesLabelEl = document.createElement('label') - speciesLabelEl.textContent = t('svg_editor.species') - const speciesSel = document.createElement('select') - speciesList.forEach((sp) => { - const opt = document.createElement('option') - opt.value = sp.id - opt.textContent = speciesLabel(sp, locale) - speciesSel.appendChild(opt) - }) - - const viewLabel = document.createElement('label') - viewLabel.textContent = t('svg_editor.view') - const viewSel = document.createElement('select') - - function populateViews() { - viewSel.textContent = '' - const sp = speciesList.find((s) => s.id === speciesSel.value) - if (!sp) return - const mainOpt = document.createElement('option') - mainOpt.value = sp.mainSvg - mainOpt.textContent = t('svg_editor.view_main') - viewSel.appendChild(mainOpt) - for (const [detailId, detailPath] of Object.entries(sp.details)) { - const opt = document.createElement('option') - opt.value = detailPath - opt.textContent = t('svg_editor.view_detail').replace('{name}', detailId) - viewSel.appendChild(opt) - } - } - populateViews() - speciesSel.addEventListener('change', populateViews) - - const loadBtn = document.createElement('button') - loadBtn.className = 'primary welcome-btn' - loadBtn.textContent = t('svg_editor.load') - loadBtn.addEventListener('click', () => { - const svgPath = viewSel.value - if (!svgPath) return - loadBtn.disabled = true - loadBtn.textContent = '...' - fetch(svgPath) - .then((r) => { - if (!r.ok) throw new Error(r.statusText) - return r.text() - }) - .then((svgText) => { - const filename = svgPath.split('/').pop() || 'anatomy_edited.svg' - loadedFileName = filename.replace('.svg', '_edited.svg') - loadSVG(svgText) - getEl('svg-editor-file-btn').textContent = t('svg_editor.change_file') - }) - .catch(() => { - alert(t('svg_editor.alert_invalid_svg')) - loadBtn.disabled = false - loadBtn.textContent = t('svg_editor.load') - }) - }) - - container.append(speciesLabelEl, speciesSel, viewLabel, viewSel, loadBtn) - } - - function buildUploadPicker(container: HTMLElement) { - const btn = document.createElement('button') - btn.className = 'primary welcome-btn' - btn.textContent = t('svg_editor.choose_file') - btn.addEventListener('click', () => { - const fi = document.getElementById('svg-editor-file-import') as HTMLInputElement | null - fi?.click() - }) - - const hint = document.createElement('div') - hint.className = 'welcome-hint' - hint.textContent = t('svg_editor.welcome_drag_hint') - - container.append(btn, hint) - } - - function setupGlobalDragDrop() { - canvas.addEventListener('dragover', (e) => { - e.preventDefault() - canvas.classList.add('dragging-over') - }, sig) - canvas.addEventListener('dragleave', (e) => { - if (e.target === canvas) canvas.classList.remove('dragging-over') - }, sig) - canvas.addEventListener('drop', (e) => { - e.preventDefault() - canvas.classList.remove('dragging-over') - const file = e.dataTransfer?.files[0] - if (file && (file.name.endsWith('.svg') || file.type === 'image/svg+xml')) { - loadedFileName = file.name.replace('.svg', '_edited.svg') - const reader = new FileReader() - reader.onload = (ev) => { - loadSVG(ev.target?.result as string) - getEl('svg-editor-file-btn').textContent = t('svg_editor.change_file') - } - reader.readAsText(file, 'UTF-8') - } else { - alert(t('svg_editor.alert_drop_svg')) - } - }, sig) - } - - /** Strip active content from an untrusted SVG: scripts, foreignObject, - * event-handler attributes (root included) and javascript: hrefs. */ - function sanitizeSvg(root: Element) { - root.querySelectorAll('script, foreignObject').forEach((el) => el.remove()) - for (const el of [root, ...root.querySelectorAll('*')]) { - for (const attr of [...el.attributes]) { - const isHandler = /^on/i.test(attr.name) - const isJsHref = /href$/i.test(attr.name) && /^\s*javascript:/i.test(attr.value) - if (isHandler || isJsHref) el.removeAttribute(attr.name) - } - } - } - - function loadSVG(svgText: string) { - const parser = new DOMParser() - const doc = parser.parseFromString(svgText, 'image/svg+xml') - const parsedSvg = doc.querySelector('svg') - if (!parsedSvg) { - alert(t('svg_editor.alert_invalid_svg')) - showWelcomeScreen() - return - } - - const imported = document.importNode(parsedSvg, true) - sanitizeSvg(imported) - canvasInner.textContent = '' - canvasInner.appendChild(imported) - svgRoot = canvasInner.querySelector('svg') - if (!svgRoot) { - alert(t('svg_editor.alert_invalid_svg')) - showWelcomeScreen() - return - } - - if (!svgRoot.getAttribute('viewBox')) { - const wAttr = svgRoot.getAttribute('width') - const hAttr = svgRoot.getAttribute('height') - const w = wAttr ? parseFloat(wAttr) : 1000 - const h = hAttr ? parseFloat(hAttr) : 1000 - svgRoot.setAttribute('viewBox', `0 0 ${w} ${h}`) - } - - svgRoot.removeAttribute('width') - svgRoot.removeAttribute('height') - - CATEGORIES = {} - selected = null - dragging = null - draggingHandle = null - zoom = 1 - - migrateOldAttributes() - normalizeDetailZones() - fixDuplicateIds() - detectCategories() - applyAllCategoryColors() - - setupSVGListeners() - refreshCategoryList() - refreshCategorySelects() - refreshElementList() - } - - function normalizeDetailZones() { - if (!svgRoot) return - svgRoot.querySelectorAll('[data-anno-opens-detail]').forEach((el) => { - el.classList.add('detail-zone') - if (el.getAttribute('fill') !== 'transparent') { - el.setAttribute('fill', DETAIL_ZONE_STYLE.fill) - if (!el.getAttribute('fill-opacity')) { - el.setAttribute('fill-opacity', DETAIL_ZONE_STYLE.fillOpacity) - } - if (el.tagName.toLowerCase() === 'polygon') { - el.setAttribute('stroke', DETAIL_ZONE_STYLE.stroke) - if (!el.getAttribute('stroke-dasharray')) { - el.setAttribute('stroke-dasharray', DETAIL_ZONE_STYLE.strokeDasharray) - } - } - } - }) - } - - function migrateOldAttributes() { - if (!svgRoot) return - const MIGRATIONS: [string, string][] = [ - ['data-bone-id', 'data-anno-id'], - ['data-bone-fr', 'data-anno-name-fr'], - ['data-bone-en', 'data-anno-name-en'], - ['data-category', 'data-anno-category'], - ['data-opens-detail', 'data-anno-opens-detail'], - ] - MIGRATIONS.forEach(([oldAttr, newAttr]) => { - svgRoot!.querySelectorAll(`[${oldAttr}]`).forEach((el) => { - if (!el.hasAttribute(newAttr)) { - el.setAttribute(newAttr, el.getAttribute(oldAttr)!) - } - el.removeAttribute(oldAttr) - }) - }) - } - - function fixDuplicateIds() { - if (!svgRoot) return - const byId: Record> = {} - svgRoot.querySelectorAll('[data-anno-id]').forEach((el) => { - const id = el.getAttribute('data-anno-id')! - const cat = el.getAttribute('data-anno-category') || 'unknown' - if (!byId[id]) byId[id] = {} - if (!byId[id][cat]) byId[id][cat] = [] - byId[id][cat].push(el) - }) - - for (const [id, byCat] of Object.entries(byId)) { - const cats = Object.keys(byCat) - if (cats.length > 1) { - cats.slice(1).forEach((cat) => { - const newId = id + '-' + cat - byCat[cat].forEach((el) => { - el.setAttribute('data-anno-id', newId) - if (el.getAttribute('id') === id) el.setAttribute('id', newId) - }) - }) - } - } - } - - function detectCategories() { - if (!svgRoot) return - svgRoot.querySelectorAll('[data-anno-category]').forEach((el) => { - const cat = el.getAttribute('data-anno-category')! - const special = el.getAttribute('data-anno-special') || '' - const storedName = el.getAttribute('data-anno-category-name') || '' - - if (CATEGORIES[cat]) { - if (special && !CATEGORIES[cat].special) { - CATEGORIES[cat].special = special - } - if (storedName && CATEGORIES[cat].name === cat) { - CATEGORIES[cat].name = storedName - } - return - } - - if (CATEGORY_TEMPLATES[cat]) { - CATEGORIES[cat] = { ...CATEGORY_TEMPLATES[cat], visible: true } - } else { - const sample = svgRoot!.querySelector( - `[data-anno-category="${cat}"]:not([fill="transparent"])`, - ) - const fill = sample ? sample.getAttribute('fill') : null - const color = fill && fill.startsWith('#') ? fill : '#00aaff' - CATEGORIES[cat] = { color, name: storedName || cat, visible: true } - } - if (special) CATEGORIES[cat].special = special - }) - } - - function applyAllCategoryColors() { - if (!svgRoot) return - for (const [cat, info] of Object.entries(CATEGORIES)) { - svgRoot.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((el) => { - if (el.getAttribute('fill') === 'transparent') return - el.setAttribute('fill', info.color) - if (el.tagName.toLowerCase() === 'polygon') { - el.setAttribute('stroke', info.color) - } - }) - } - } - - function setupSVGListeners() { - if (!svgRoot) return - svgRoot.addEventListener('click', svgClickHandler, sig) - svgRoot.addEventListener('mousedown', svgMousedownHandler, sig) - svgRoot.addEventListener('contextmenu', svgContextMenuHandler, sig) - } - - function svgClickHandler(e: MouseEvent) { - if (mode === 'point') { - const p = getSVGPoint(e) - addCircleAt(p.x, p.y) - e.stopPropagation() - } else if (mode === 'polygon') { - const p = getSVGPoint(e) - polygonPoints.push([p.x, p.y]) - updatePolygonPreview() - e.stopPropagation() - } else if (mode === 'select') { - const target = e.target as Element - const midhandle = target.closest('.polygon-midhandle') - if (midhandle && selected && selected.tagName.toLowerCase() === 'polygon') { - const edgeIdx = parseInt(midhandle.getAttribute('data-edge-idx')!) - const points = parsePoints(selected.getAttribute('points')!) - const p = getSVGPoint(e) - points.splice(edgeIdx + 1, 0, [p.x, p.y]) - selected.setAttribute('points', pointsToStr(points)) - showPolygonHandles(selected) - e.stopPropagation() - return - } - if (target.closest('.polygon-handle')) { - e.stopPropagation() - return - } - const annoTarget = target.closest('[data-anno-id]') as SVGElement | null - if (annoTarget) { - selectElement(annoTarget) - e.stopPropagation() - } else { - deselect() - } - } - } - - function svgContextMenuHandler(e: MouseEvent) { - if ((e.target as Element).closest('.polygon-handle')) { - e.preventDefault() - } - } - - function svgMousedownHandler(e: MouseEvent) { - if (mode !== 'select') return - - const target = e.target as Element - const handle = target.closest('.polygon-handle') - if (handle && selected && selected.tagName.toLowerCase() === 'polygon') { - const vIdx = parseInt(handle.getAttribute('data-vertex-idx')!) - const points = parsePoints(selected.getAttribute('points')!) - - if (e.altKey || e.button === 2) { - if (points.length > 3) { - points.splice(vIdx, 1) - selected.setAttribute('points', pointsToStr(points)) - showPolygonHandles(selected) - } else { - alert(t('svg_editor.alert_min_3_vertices')) - } - e.preventDefault() - e.stopPropagation() - return - } - - const p = getSVGPoint(e) - draggingHandle = { - vIdx, - points, - originalPoint: [...points[vIdx]], - polygon: selected, - } - dragStart = { x: p.x, y: p.y } - e.preventDefault() - e.stopPropagation() - return - } - - if (target.classList.contains('polygon-midhandle')) { - return - } - - const annoTarget = target.closest('[data-anno-id]') as SVGElement | null - if (!annoTarget) return - selectElement(annoTarget) - dragging = annoTarget - const p = getSVGPoint(e) - const id = annoTarget.getAttribute('data-anno-id')! - const cat = annoTarget.getAttribute('data-anno-category') - const parent = annoTarget.parentNode as Element | null - const siblingSnaps: { el: SVGElement; snap: ReturnType }[] = [] - if (parent) { - parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((sib) => { - if (sib === annoTarget) return - if (sib.getAttribute('data-anno-category') !== cat) return - const snap = snapshotPosition(sib as SVGElement) - if (snap) siblingSnaps.push({ el: sib as SVGElement, snap }) - }) - } - dragStart = { - x: p.x, - y: p.y, - snap: snapshotPosition(annoTarget), - siblingSnaps, - } - e.preventDefault() - } - - function onMouseMove(e: MouseEvent) { - if (draggingHandle) { - const p = getSVGPoint(e) - const dx = p.x - dragStart!.x - const dy = p.y - dragStart!.y - const newPoint = [ - draggingHandle.originalPoint[0] + dx, - draggingHandle.originalPoint[1] + dy, - ] - draggingHandle.points[draggingHandle.vIdx] = newPoint - draggingHandle.polygon.setAttribute( - 'points', - pointsToStr(draggingHandle.points), - ) - showPolygonHandles(draggingHandle.polygon) - return - } - - if (!dragging) return - const p = getSVGPoint(e) - const dx = p.x - dragStart!.x - const dy = p.y - dragStart!.y - moveElement(dragging, dx, dy, dragStart!.snap!) - dragStart!.siblingSnaps?.forEach(({ el: sibEl, snap }) => { - moveElement(sibEl, dx, dy, snap!) - }) - if (dragging === selected && dragging.tagName.toLowerCase() === 'polygon') { - showPolygonHandles(dragging) - } - updateCoordsDisplay() - } - - function onMouseUp() { - dragging = null - draggingHandle = null - dragStart = null - } - - function onKeyDown(e: KeyboardEvent) { - const tag = (e.target as Element).tagName - if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return - if (e.key === 'Enter' && mode === 'polygon') finalizePolygon() - if (e.key === 'Escape') { - if (mode === 'polygon') cancelPolygon() - else deselect() - } - if (e.key === 'Delete' && selected) deleteSelected() - if (e.key === '1') setMode('select') - if (e.key === '2') setMode('point') - if (e.key === '3') setMode('polygon') - } - - function setupGlobalListeners() { - document.addEventListener('mousemove', onMouseMove, sig) - document.addEventListener('mouseup', onMouseUp, sig) - document.addEventListener('keydown', onKeyDown, sig) - - getEl('svg-editor-filter-input').addEventListener('input', refreshElementList, sig) - - ;['svg-editor-edit-fr', 'svg-editor-edit-en', 'svg-editor-edit-category', 'svg-editor-edit-lateral'].forEach( - (id) => { - getEl(id).addEventListener('change', applyEdit, sig) - }, - ) - - function syncSliderNum(rangeId: string, numId: string) { - const range = getEl(rangeId) as HTMLInputElement - const num = getEl(numId) as HTMLInputElement - range.addEventListener('input', () => { - num.value = range.value - if (selected) applyEdit() - }, sig) - num.addEventListener('input', () => { - const v = parseFloat(num.value) - if (!isNaN(v)) { - range.value = String( - Math.max(parseFloat(range.min), Math.min(parseFloat(range.max), v)), - ) - } - if (selected) applyEdit() - }, sig) - } - syncSliderNum('svg-editor-edit-radius', 'svg-editor-edit-radius-num') - syncSliderNum('svg-editor-edit-opacity', 'svg-editor-edit-opacity-num') - - ;(getEl('svg-editor-edit-opens-detail') as HTMLInputElement).addEventListener( - 'change', - () => { - const checked = (getEl('svg-editor-edit-opens-detail') as HTMLInputElement).checked - getEl('svg-editor-detail-target-row').style.display = checked ? 'block' : 'none' - getEl('svg-editor-osteo-fields').style.display = checked ? 'none' : 'block' - applyEdit() - }, - sig, - ) - getEl('svg-editor-edit-detail-target').addEventListener('change', applyEdit, sig) - getEl('svg-editor-edit-detail-target').addEventListener('input', () => { - if (selected) applyEdit() - }, sig) - - ;(getEl('svg-editor-file-import') as HTMLInputElement).addEventListener('change', (e) => { - const file = (e.target as HTMLInputElement).files?.[0] - if (!file) return - loadedFileName = file.name.replace('.svg', '_edited.svg') - const reader = new FileReader() - reader.onload = (ev) => { - loadSVG(ev.target?.result as string) - getEl('svg-editor-file-btn').textContent = t('svg_editor.change_file') - } - reader.readAsText(file, 'UTF-8') - ;(e.target as HTMLInputElement).value = '' - }, sig) - - getEl('svg-editor-file-btn').addEventListener('click', () => { - ;(getEl('svg-editor-file-import') as HTMLInputElement).click() - }, sig) - - getEl('svg-editor-export-btn').addEventListener('click', exportSVG, sig) - - getEl('svg-editor-mode-select').addEventListener('click', () => setMode('select'), sig) - getEl('svg-editor-mode-point').addEventListener('click', () => setMode('point'), sig) - getEl('svg-editor-mode-polygon').addEventListener('click', () => setMode('polygon'), sig) - getEl('svg-editor-finalize-polygon').addEventListener('click', finalizePolygon, sig) - getEl('svg-editor-cancel-polygon').addEventListener('click', cancelPolygon, sig) - getEl('svg-editor-add-cat-btn').addEventListener('click', addCategory, sig) - getEl('svg-editor-delete-btn').addEventListener('click', deleteSelected, sig) - getEl('svg-editor-restart-polygon').addEventListener('click', restartCurrentPolygon, sig) - } - - function getEl(id: string): HTMLElement { - return document.getElementById(id) as HTMLElement - } - - function getSVGPoint(evt: MouseEvent) { - const pt = svgRoot!.createSVGPoint() - pt.x = evt.clientX - pt.y = evt.clientY - return pt.matrixTransform(svgRoot!.getScreenCTM()!.inverse()) - } - - function setMode(m: string) { - if (!svgRoot && m !== 'select') { - alert(t('svg_editor.alert_upload_first')) - return - } - mode = m - canvas.className = 'svg-editor-canvas mode-' + m - document.querySelectorAll('[data-mode]').forEach((b) => { - b.classList.toggle('active', (b as HTMLElement).dataset.mode === m) - }) - getEl('svg-editor-polygon-controls').style.display = m === 'polygon' ? 'block' : 'none' - if (m !== 'polygon') cancelPolygon() - if (m !== 'select') { - deselect() - hidePolygonHandles() - } - } - - function snapshotPosition(svgEl: SVGElement) { - const tag = svgEl.tagName.toLowerCase() - if (tag === 'circle' || tag === 'ellipse') - return { - type: tag, - cx: parseFloat(svgEl.getAttribute('cx')!), - cy: parseFloat(svgEl.getAttribute('cy')!), - points: '', - } - if (tag === 'polygon') - return { type: 'polygon', cx: 0, cy: 0, points: svgEl.getAttribute('points')! } - return null - } - - function moveElement( - svgEl: SVGElement, - dx: number, - dy: number, - snap: NonNullable>, - ) { - if (snap.type === 'circle' || snap.type === 'ellipse') { - svgEl.setAttribute('cx', String(snap.cx + dx)) - svgEl.setAttribute('cy', String(snap.cy + dy)) - } else if (snap.type === 'polygon') { - const pts = snap.points - .split(/\s+/) - .filter((p: string) => p) - .map((p: string) => { - const [x, y] = p.split(',').map(Number) - return [(x + dx).toFixed(1), (y + dy).toFixed(1)] - }) - svgEl.setAttribute('points', pts.map((p: string[]) => p.join(',')).join(' ')) - } - } - - function cssEscape(s: string) { - return CSS.escape ? CSS.escape(s) : s.replace(/[^a-zA-Z0-9_-]/g, '\\$&') - } - - function selectElement(svgEl: SVGElement) { - deselect() - selected = svgEl - svgEl.classList.add('selected') - const id = svgEl.getAttribute('data-anno-id')! - const cat = svgEl.getAttribute('data-anno-category') - const parent = svgEl.parentNode as Element | null - if (parent) { - parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((s) => { - if (s.getAttribute('data-anno-category') === cat) { - s.classList.add('selected') - } - }) - } - showEditPanel(svgEl) - if (svgEl.tagName.toLowerCase() === 'polygon') { - showPolygonHandles(svgEl) - } - refreshElementList() - } - - function deselect() { - document.querySelectorAll('.selected').forEach((svgEl) => svgEl.classList.remove('selected')) - hidePolygonHandles() - selected = null - getEl('svg-editor-edit-section').style.display = 'none' - refreshElementList() - } - - function showEditPanel(svgEl: SVGElement) { - getEl('svg-editor-edit-section').style.display = 'block' - ;(getEl('svg-editor-edit-fr') as HTMLInputElement).value = - svgEl.getAttribute('data-anno-name-fr') || '' - ;(getEl('svg-editor-edit-en') as HTMLInputElement).value = - svgEl.getAttribute('data-anno-name-en') || '' - ;(getEl('svg-editor-edit-category') as HTMLSelectElement).value = - svgEl.getAttribute('data-anno-category') || 'custom' - ;(getEl('svg-editor-edit-lateral') as HTMLSelectElement).value = - svgEl.getAttribute('data-anno-lateral') || '' - - const id = svgEl.getAttribute('data-anno-id')! - const cat = svgEl.getAttribute('data-anno-category') - const parent = svgEl.parentNode as Element | null - let visibleEl: SVGElement = svgEl - if (parent && id) { - const sibs = parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`) - sibs.forEach((s) => { - if ( - s.getAttribute('data-anno-category') === cat && - s.getAttribute('fill') !== 'transparent' - ) { - visibleEl = s as SVGElement - } - }) - } - - const opa = parseFloat(visibleEl.getAttribute('fill-opacity') || '0.65') - const opaPct = Math.round(opa * 100) - ;(getEl('svg-editor-edit-opacity') as HTMLInputElement).value = String(opaPct) - ;(getEl('svg-editor-edit-opacity-num') as HTMLInputElement).value = String(opaPct) - - const tag = svgEl.tagName.toLowerCase() - const radBlock = getEl('svg-editor-lbl-radius') - const radRow = getEl('svg-editor-radius-row') - const visibleTag = visibleEl.tagName.toLowerCase() - if (visibleTag === 'circle') { - radBlock.style.display = 'block' - radRow.style.display = 'flex' - const r = parseFloat(visibleEl.getAttribute('r') || '15') - ;(getEl('svg-editor-edit-radius') as HTMLInputElement).value = String(r) - ;(getEl('svg-editor-edit-radius-num') as HTMLInputElement).value = String(r) - } else { - radBlock.style.display = 'none' - radRow.style.display = 'none' - } - - const polyActions = getEl('svg-editor-polygon-edit-actions') - if (polyActions) polyActions.style.display = tag === 'polygon' ? 'block' : 'none' - - const opensDetail = - visibleEl.getAttribute('data-anno-opens-detail') || - svgEl.getAttribute('data-anno-opens-detail') || - '' - const checkbox = getEl('svg-editor-edit-opens-detail') as HTMLInputElement - const detailInput = getEl('svg-editor-edit-detail-target') as HTMLInputElement - const detailRow = getEl('svg-editor-detail-target-row') - const detailBlock = getEl('svg-editor-detail-toggle-block') - - const osteoFields = getEl('svg-editor-osteo-fields') - if (tag === 'polygon') { - detailBlock.style.display = 'block' - checkbox.checked = !!opensDetail - detailInput.value = opensDetail - detailRow.style.display = opensDetail ? 'block' : 'none' - osteoFields.style.display = opensDetail ? 'none' : 'block' - } else { - detailBlock.style.display = 'none' - checkbox.checked = false - detailInput.value = '' - osteoFields.style.display = 'block' - } - - updateCoordsDisplay() - } - - function updateCoordsDisplay() { - if (!selected) return - const tag = selected.tagName.toLowerCase() - let txt = '' - if (tag === 'circle' || tag === 'ellipse') { - txt = `cx=${Math.round(parseFloat(selected.getAttribute('cx')!))}, cy=${Math.round(parseFloat(selected.getAttribute('cy')!))}` - } else if (tag === 'polygon') { - const pts = selected - .getAttribute('points')! - .split(/\s+/) - .filter((p) => p).length - txt = t('svg_editor.polygon_vertices').replace('{count}', String(pts)) - } - getEl('svg-editor-coords-display').textContent = txt - } - - function applyEdit() { - if (!selected) return - const fr = (getEl('svg-editor-edit-fr') as HTMLInputElement).value.trim() - const en = (getEl('svg-editor-edit-en') as HTMLInputElement).value.trim() - const cat = (getEl('svg-editor-edit-category') as HTMLSelectElement).value - const lateral = (getEl('svg-editor-edit-lateral') as HTMLSelectElement).value - const opacityPct = (getEl('svg-editor-edit-opacity') as HTMLInputElement).value - const opacity = (parseFloat(opacityPct) / 100).toString() - const radius = (getEl('svg-editor-edit-radius') as HTMLInputElement).value - - const oldId = selected.getAttribute('data-anno-id')! - const oldCat = selected.getAttribute('data-anno-category') - const parent = selected.parentNode as Element | null - const siblings = parent - ? Array.from(parent.querySelectorAll(`[data-anno-id="${cssEscape(oldId)}"]`)).filter( - (s) => s.getAttribute('data-anno-category') === oldCat, - ) - : [selected] - - const opensDetailEnabled = (getEl('svg-editor-edit-opens-detail') as HTMLInputElement).checked - const detailTarget = (getEl('svg-editor-edit-detail-target') as HTMLInputElement).value.trim() - - siblings.forEach((s) => { - if (opensDetailEnabled && detailTarget) { - s.setAttribute('data-anno-opens-detail', detailTarget) - s.removeAttribute('data-anno-name-fr') - s.removeAttribute('data-anno-name-en') - s.removeAttribute('data-anno-category') - s.removeAttribute('data-anno-category-name') - s.removeAttribute('data-anno-special') - } else { - s.removeAttribute('data-anno-opens-detail') - s.removeAttribute('stroke-dasharray') - if (fr) s.setAttribute('data-anno-name-fr', fr) - if (en) s.setAttribute('data-anno-name-en', en) - if (cat) { - s.setAttribute('data-anno-category', cat) - if (CATEGORIES[cat]?.name) { - s.setAttribute('data-anno-category-name', CATEGORIES[cat].name) - } - const catSpecial = CATEGORIES[cat]?.special - if (catSpecial?.trim()) { - s.setAttribute('data-anno-special', catSpecial.trim()) - } else { - s.removeAttribute('data-anno-special') - } - } - if (lateral) { - s.setAttribute('data-anno-lateral', lateral) - } else { - s.removeAttribute('data-anno-lateral') - } - } - - if (opensDetailEnabled && detailTarget) { - let title = s.querySelector(':scope > title') as SVGTitleElement | null - if (!title) { - title = document.createElementNS('http://www.w3.org/2000/svg', 'title') as SVGTitleElement - s.insertBefore(title, s.firstChild) - } - title.textContent = 'Zoom: ' + detailTarget - if (s.getAttribute('fill') !== 'transparent') { - s.setAttribute('fill', DETAIL_ZONE_STYLE.fill) - s.setAttribute('fill-opacity', opacity || DETAIL_ZONE_STYLE.fillOpacity) - if (s.tagName.toLowerCase() === 'polygon') { - s.setAttribute('stroke', DETAIL_ZONE_STYLE.stroke) - s.setAttribute('stroke-width', DETAIL_ZONE_STYLE.strokeWidth) - s.setAttribute('stroke-dasharray', DETAIL_ZONE_STYLE.strokeDasharray) - } - } - s.classList.add('detail-zone') - } else { - s.classList.remove('detail-zone') - let title = s.querySelector(':scope > title') as SVGTitleElement | null - if (!title) { - title = document.createElementNS('http://www.w3.org/2000/svg', 'title') as SVGTitleElement - s.insertBefore(title, s.firstChild) - } - title.textContent = (fr || '') + (en ? ' / ' + en : '') - - if (s.getAttribute('fill') !== 'transparent' && cat && CATEGORIES[cat]) { - s.setAttribute('fill', CATEGORIES[cat].color) - if (s.tagName.toLowerCase() === 'polygon') { - s.setAttribute('stroke', CATEGORIES[cat].color) - } - } - if (opacity && s.getAttribute('fill') !== 'transparent') - s.setAttribute('fill-opacity', opacity) - - const stag = s.tagName.toLowerCase() - if (stag === 'circle' && radius) { - if (s.getAttribute('fill') === 'transparent') { - s.setAttribute('r', String(Math.max(1, parseFloat(radius) + 12))) - } else { - s.setAttribute('r', radius) - } - } - } - }) - - refreshElementList() - refreshCategoryList() - } - - function deleteSelected() { - if (!selected) return - if (!confirm(t('svg_editor.confirm_delete_element'))) return - const id = selected.getAttribute('data-anno-id')! - const cat = selected.getAttribute('data-anno-category') - const parent = selected.parentNode as Element | null - if (parent) { - parent.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`).forEach((s) => { - if (s.getAttribute('data-anno-category') === cat) s.parentNode?.removeChild(s) - }) - } - selected = null - getEl('svg-editor-edit-section').style.display = 'none' - refreshElementList() - refreshCategoryList() - } - - function addCircleAt(x: number, y: number) { - if (!svgRoot) return - const cat = (getEl('svg-editor-default-category') as HTMLSelectElement).value || 'custom' - const color = CATEGORIES[cat]?.color || '#00aaff' - - let overlayG = svgRoot.querySelector('#osteo-overlays') - if (!overlayG) { - overlayG = document.createElementNS('http://www.w3.org/2000/svg', 'g') - overlayG.setAttribute('id', 'osteo-overlays') - svgRoot.appendChild(overlayG) - } - - const id = 'point-' + Date.now().toString(36) - const frName = t('svg_editor.new_point_fr') - const enName = t('svg_editor.new_point_en') - - const hit = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - hit.setAttribute('cx', String(Math.round(x))) - hit.setAttribute('cy', String(Math.round(y))) - hit.setAttribute('r', '28') - hit.setAttribute('fill', 'transparent') - hit.setAttribute('pointer-events', 'all') - hit.setAttribute('data-anno-id', id) - hit.setAttribute('data-anno-name-fr', frName) - hit.setAttribute('data-anno-name-en', enName) - hit.setAttribute('data-anno-category', cat) - if (CATEGORIES[cat]?.name) hit.setAttribute('data-anno-category-name', CATEGORIES[cat].name) - if (CATEGORIES[cat]?.special) hit.setAttribute('data-anno-special', CATEGORIES[cat].special!) - hit.setAttribute('style', 'cursor:pointer') - const t1 = document.createElementNS('http://www.w3.org/2000/svg', 'title') - t1.textContent = frName - hit.appendChild(t1) - overlayG.appendChild(hit) - - const vis = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - vis.setAttribute('cx', String(Math.round(x))) - vis.setAttribute('cy', String(Math.round(y))) - vis.setAttribute('r', '16') - vis.setAttribute('fill', color) - vis.setAttribute('fill-opacity', '0.65') - vis.setAttribute('stroke', '#000') - vis.setAttribute('stroke-width', '1.5') - vis.setAttribute('pointer-events', 'none') - vis.setAttribute('id', id) - vis.setAttribute('data-anno-id', id) - vis.setAttribute('data-anno-name-fr', frName) - vis.setAttribute('data-anno-name-en', enName) - vis.setAttribute('data-anno-category', cat) - if (CATEGORIES[cat]?.name) vis.setAttribute('data-anno-category-name', CATEGORIES[cat].name) - if (CATEGORIES[cat]?.special) vis.setAttribute('data-anno-special', CATEGORIES[cat].special!) - const t2 = document.createElementNS('http://www.w3.org/2000/svg', 'title') - t2.textContent = frName - vis.appendChild(t2) - overlayG.appendChild(vis) - - setMode('select') - selectElement(hit as unknown as SVGElement) - refreshElementList() - refreshCategoryList() - setTimeout(() => (getEl('svg-editor-edit-fr') as HTMLInputElement).focus(), 50) - } - - function updatePolygonPreview() { - if (!svgRoot) return - svgRoot - .querySelectorAll('.polygon-preview, .polygon-preview-pt') - .forEach((p) => p.remove()) - if (polygonPoints.length < 1) return - - if (polygonPoints.length >= 2) { - const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon') - poly.setAttribute('points', polygonPoints.map((p) => p.join(',')).join(' ')) - poly.classList.add('polygon-preview') - poly.setAttribute('pointer-events', 'none') - svgRoot.appendChild(poly) - } - polygonPoints.forEach(([x, y]) => { - const pt = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - pt.setAttribute('cx', String(x)) - pt.setAttribute('cy', String(y)) - pt.setAttribute('r', '6') - pt.classList.add('polygon-preview-pt') - pt.setAttribute('pointer-events', 'none') - svgRoot!.appendChild(pt) - }) - } - - let _polygonRestartMemo: { - id: string - fr: string - en: string - cat: string - fill: string - fillOpacity: string - stroke: string - strokeWidth: string - } | null = null - - function finalizePolygon() { - if (!svgRoot) return - if (polygonPoints.length < 3) { - alert(t('svg_editor.alert_min_3')) - return - } - - const memo = _polygonRestartMemo - _polygonRestartMemo = null - - const cat = memo - ? memo.cat - : (getEl('svg-editor-default-category') as HTMLSelectElement).value || 'custom' - const color = memo ? memo.fill : CATEGORIES[cat]?.color || '#00aaff' - - let overlayG = svgRoot.querySelector('#osteo-overlays') - if (!overlayG) { - overlayG = document.createElementNS('http://www.w3.org/2000/svg', 'g') - overlayG.setAttribute('id', 'osteo-overlays') - svgRoot.appendChild(overlayG) - } - - const id = memo ? memo.id : 'zone-' + Date.now().toString(36) - const frName = memo ? memo.fr || t('svg_editor.new_zone_fr') : t('svg_editor.new_zone_fr') - const enName = memo ? memo.en || t('svg_editor.new_zone_en') : t('svg_editor.new_zone_en') - const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon') - poly.setAttribute( - 'points', - polygonPoints.map((p) => p.map(Math.round).join(',')).join(' '), - ) - poly.setAttribute('fill', color) - poly.setAttribute('fill-opacity', memo ? memo.fillOpacity || '0.30' : '0.30') - poly.setAttribute('stroke', memo ? memo.stroke || color : color) - poly.setAttribute('stroke-width', memo ? memo.strokeWidth || '2' : '2') - poly.setAttribute('pointer-events', 'all') - poly.setAttribute('style', 'cursor:pointer') - poly.setAttribute('id', id) - poly.setAttribute('data-anno-id', id) - poly.setAttribute('data-anno-name-fr', frName) - poly.setAttribute('data-anno-name-en', enName) - poly.setAttribute('data-anno-category', cat) - if (CATEGORIES[cat]?.name) - poly.setAttribute('data-anno-category-name', CATEGORIES[cat].name) - if (CATEGORIES[cat]?.special) - poly.setAttribute('data-anno-special', CATEGORIES[cat].special!) - const titleEl = document.createElementNS('http://www.w3.org/2000/svg', 'title') - titleEl.textContent = - poly.getAttribute('data-anno-name-fr') + ' / ' + poly.getAttribute('data-anno-name-en') - poly.appendChild(titleEl) - overlayG.appendChild(poly) - - cancelPolygon() - setMode('select') - selectElement(poly as unknown as SVGElement) - refreshElementList() - refreshCategoryList() - if (!memo) setTimeout(() => (getEl('svg-editor-edit-fr') as HTMLInputElement).focus(), 50) - } - - function cancelPolygon() { - polygonPoints = [] - svgRoot - ?.querySelectorAll('.polygon-preview, .polygon-preview-pt') - .forEach((p) => p.remove()) - } - - function refreshCategoryList() { - const list = getEl('svg-editor-category-list') - - const activeEl = document.activeElement as HTMLElement | null - if (activeEl && list.contains(activeEl)) { - list.querySelectorAll('.cat-row').forEach((row) => { - const cat = (row as HTMLElement).dataset.cat! - const countEl = row.querySelector('.count') - if (countEl && svgRoot) { - const n = svgRoot.querySelectorAll( - `[data-anno-category="${cat}"]:not([fill="transparent"])`, - ).length - countEl.textContent = String(n) - } - }) - return - } - - list.textContent = '' - - if (Object.keys(CATEGORIES).length === 0) { - const emptyMsg = document.createElement('div') - emptyMsg.style.cssText = 'font-size:12px; color:var(--color-ink-muted); padding:8px; text-align:center;' - emptyMsg.textContent = t('svg_editor.no_categories') - list.appendChild(emptyMsg) - return - } - - for (const [cat, info] of Object.entries(CATEGORIES)) { - const count = svgRoot - ? svgRoot.querySelectorAll(`[data-anno-category="${cat}"]:not([fill="transparent"])`).length - : 0 - - const hasSpecial = !!(info.special?.trim()) - const row = document.createElement('div') - row.className = 'cat-row' - row.dataset.cat = cat - - const chk = document.createElement('input') - chk.type = 'checkbox' - chk.checked = info.visible - chk.title = 'Visibility' - - const colorInput = document.createElement('input') - colorInput.type = 'color' - colorInput.value = info.color - colorInput.title = 'Color' - - const nameSpan = document.createElement('span') - nameSpan.className = 'name' - nameSpan.title = cat - nameSpan.textContent = info.name - - const countSpan = document.createElement('span') - countSpan.className = 'count' - countSpan.textContent = String(count) - - const specialBtn = document.createElement('button') - specialBtn.className = 'special-btn' + (hasSpecial ? ' has-value' : '') - specialBtn.title = 'Special behavior' - specialBtn.textContent = '⚡' - - const delBtn = document.createElement('button') - delBtn.className = 'delete' - delBtn.title = 'Delete category' - delBtn.textContent = '×' - - row.append(chk, colorInput, nameSpan) - if (hasSpecial) { - const badge = document.createElement('span') - badge.className = 'special-badge' - badge.title = 'Behavior: ' + (info.special || '') - badge.textContent = '⚡ ' + (info.special || '') - row.appendChild(badge) - } - row.append(countSpan, specialBtn, delBtn) - - chk.addEventListener('change', () => { - info.visible = chk.checked - canvasInner.classList.toggle('hide-' + cat, !info.visible) - }) - - colorInput.addEventListener('change', () => { - info.color = colorInput.value - svgRoot?.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { - if (svgEl.getAttribute('fill') === 'transparent') return - svgEl.setAttribute('fill', info.color) - if (svgEl.tagName.toLowerCase() === 'polygon') { - svgEl.setAttribute('stroke', info.color) - } - }) - refreshElementList() - }) - - nameSpan.addEventListener('click', () => { - const newName = prompt('Rename category:', info.name) - if (newName?.trim()) { - info.name = newName.trim() - svgRoot?.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { - svgEl.setAttribute('data-anno-category-name', info.name) - }) - refreshCategoryList() - refreshCategorySelects() - } - }) - - specialBtn.addEventListener('click', () => openSpecialDialog(cat)) - delBtn.addEventListener('click', () => deleteCategory(cat)) - - list.appendChild(row) - } - } - - function refreshCategorySelects() { - const def = getEl('svg-editor-default-category') as HTMLSelectElement - const editSel = getEl('svg-editor-edit-category') as HTMLSelectElement - const defVal = def.value - const editVal = editSel.value - - def.textContent = '' - editSel.textContent = '' - - for (const [cat, info] of Object.entries(CATEGORIES)) { - const opt1 = document.createElement('option') - opt1.value = cat - opt1.textContent = info.name + ' (' + cat + ')' - def.appendChild(opt1) - - const opt2 = document.createElement('option') - opt2.value = cat - opt2.textContent = info.name + ' (' + cat + ')' - editSel.appendChild(opt2) - } - - if (defVal) def.value = defVal - if (editVal) editSel.value = editVal - } - - function openSpecialDialog(catId: string) { - const info = CATEGORIES[catId] - if (!info) return - const current = info.special || '' - - const lines = SPECIAL_BEHAVIORS.map((b, i) => `${i + 1}. ${b.id} — ${b.desc}`).join('\n') - const txt = `Special behavior for category "${info.name}". - -Suggestions: -${lines} - -Type a name (suggested or custom), or leave empty to remove. -Current: ${current || '(none)'}` - - const result = prompt(txt, current) - if (result === null) return - - const trimmed = result.trim() - info.special = trimmed - - svgRoot?.querySelectorAll(`[data-anno-category="${catId}"]`).forEach((svgEl) => { - if (trimmed) { - svgEl.setAttribute('data-anno-special', trimmed) - } else { - svgEl.removeAttribute('data-anno-special') - } - }) - - refreshCategoryList() - refreshElementList() - } - - function addCategory() { - const name = (getEl('svg-editor-new-cat-name') as HTMLInputElement).value.trim() - const color = (getEl('svg-editor-new-cat-color') as HTMLInputElement).value - if (!name) { - alert(t('svg_editor.alert_cat_name_required')) - return - } - const slug = name - .toLowerCase() - .normalize('NFD') - .replace(/[̀-ͯ]/g, '') - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-|-$/g, '') - if (!slug) { - alert(t('svg_editor.alert_cat_invalid_name')) - return - } - - if (CATEGORIES[slug]) { - alert(t('svg_editor.alert_cat_exists')) - return - } - - CATEGORIES[slug] = { color, name, visible: true } - ;(getEl('svg-editor-new-cat-name') as HTMLInputElement).value = '' - refreshCategoryList() - refreshCategorySelects() - } - - function deleteCategory(cat: string) { - if (!svgRoot) return - const count = svgRoot.querySelectorAll( - `[data-anno-category="${cat}"]:not([fill="transparent"])`, - ).length - let msg = t('svg_editor.confirm_delete_cat').replace('{name}', CATEGORIES[cat].name) - if (count > 0) { - msg += t('svg_editor.confirm_delete_cat_count').replace('{count}', String(count)) - } - if (!confirm(msg)) return - - svgRoot.querySelectorAll(`[data-anno-category="${cat}"]`).forEach((svgEl) => { - svgEl.parentNode?.removeChild(svgEl) - }) - - delete CATEGORIES[cat] - refreshCategoryList() - refreshCategorySelects() - refreshElementList() - } - - function refreshElementList() { - if (!svgRoot) return - const filter = ((getEl('svg-editor-filter-input') as HTMLInputElement).value || '').toLowerCase() - const seen = new Set() - const items: { - id: string - fr: string - cat: string - catName: string - color: string - detail: string - }[] = [] - - svgRoot.querySelectorAll('[data-anno-id]').forEach((svgEl) => { - const id = svgEl.getAttribute('data-anno-id')! - if (seen.has(id)) return - const cat = svgEl.getAttribute('data-anno-category') || '' - seen.add(id) - - const fr = svgEl.getAttribute('data-anno-name-fr') || '' - const catName = CATEGORIES[cat] ? CATEGORIES[cat].name : cat || 'no cat.' - - if ( - filter && - !id.toLowerCase().includes(filter) && - !fr.toLowerCase().includes(filter) && - !catName.toLowerCase().includes(filter) - ) - return - - const visibleEl: Element = - svgRoot!.querySelector(`[data-anno-id="${cssEscape(id)}"]:not([fill="transparent"])`) || - svgEl - const color = visibleEl.getAttribute('fill') || '#888' - const detail = - visibleEl.getAttribute('data-anno-opens-detail') || - svgEl.getAttribute('data-anno-opens-detail') || - '' - - items.push({ id, fr, cat, catName, color, detail }) - }) - - items.sort((a, b) => (a.cat || '').localeCompare(b.cat || '') || a.fr.localeCompare(b.fr)) - - getEl('svg-editor-count').textContent = String(items.length) - - const list = getEl('svg-editor-element-list') - const selId = selected ? selected.getAttribute('data-anno-id') : null - list.textContent = '' - - items.forEach(({ id, fr, catName, color, detail }) => { - const div = document.createElement('div') - div.className = 'element-item' + (id === selId ? ' selected' : '') - div.dataset.id = id - - const swatch = document.createElement('span') - swatch.className = 'swatch' - swatch.style.background = color - - const nameSpan = document.createElement('span') - nameSpan.className = 'name' - nameSpan.textContent = detail ? 'Detail: ' + detail : fr || id - - const catSpan = document.createElement('span') - catSpan.className = 'cat' - catSpan.textContent = detail ? 'detail' : catName - - div.append(swatch, nameSpan, catSpan) - list.appendChild(div) - - div.addEventListener('click', () => { - const candidates = svgRoot!.querySelectorAll( - `[data-anno-id="${cssEscape(id)}"]`, - ) - let target: SVGElement | null = null - candidates.forEach((c) => { - if (target) return - if (c.getAttribute('fill') === 'transparent') return - target = c as SVGElement - }) - if (!target && candidates.length > 0) { - target = candidates[0] as SVGElement - } - if (target) { - setMode('select') - selectElement(target) - scrollSvgElementIntoView(target) - flashSelected(target) - } - }) - }) - } - - function parsePoints(str: string) { - return str - .trim() - .split(/\s+/) - .filter((p) => p) - .map((p) => p.split(',').map(Number)) - } - function pointsToStr(points: number[][]) { - return points.map((p) => p.map((v) => Math.round(v * 10) / 10).join(',')).join(' ') - } - - function showPolygonHandles(polygon: SVGElement) { - hidePolygonHandles() - if (!svgRoot) return - const points = parsePoints(polygon.getAttribute('points')!) - - let handlesG = svgRoot.querySelector('#polygon-handles') - if (!handlesG) { - handlesG = document.createElementNS('http://www.w3.org/2000/svg', 'g') - handlesG.setAttribute('id', 'polygon-handles') - svgRoot.appendChild(handlesG) - } - svgRoot.appendChild(handlesG) - - for (let i = 0; i < points.length; i++) { - const [x1, y1] = points[i] - const [x2, y2] = points[(i + 1) % points.length] - const mx = (x1 + x2) / 2 - const my = (y1 + y2) / 2 - const m = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - m.setAttribute('cx', String(mx)) - m.setAttribute('cy', String(my)) - m.setAttribute('r', '6') - m.classList.add('polygon-midhandle') - m.setAttribute('data-edge-idx', String(i)) - const titleEl = document.createElementNS('http://www.w3.org/2000/svg', 'title') - titleEl.textContent = t('svg_editor.handle_insert') - m.appendChild(titleEl) - handlesG.appendChild(m) - } - - points.forEach(([x, y], i) => { - const h = document.createElementNS('http://www.w3.org/2000/svg', 'circle') - h.setAttribute('cx', String(x)) - h.setAttribute('cy', String(y)) - h.setAttribute('r', '8') - h.classList.add('polygon-handle') - h.setAttribute('data-vertex-idx', String(i)) - const titleEl = document.createElementNS('http://www.w3.org/2000/svg', 'title') - titleEl.textContent = t('svg_editor.handle_drag') - h.appendChild(titleEl) - handlesG!.appendChild(h) - }) - } - - function hidePolygonHandles() { - const g = svgRoot?.querySelector('#polygon-handles') - if (g) g.textContent = '' - } - - function restartCurrentPolygon() { - if (!selected || selected.tagName.toLowerCase() !== 'polygon') return - if (!confirm(t('svg_editor.confirm_redraw'))) return - _polygonRestartMemo = { - id: selected.getAttribute('data-anno-id') || '', - fr: selected.getAttribute('data-anno-name-fr') || '', - en: selected.getAttribute('data-anno-name-en') || '', - cat: selected.getAttribute('data-anno-category') || '', - fill: selected.getAttribute('fill') || '', - fillOpacity: selected.getAttribute('fill-opacity') || '', - stroke: selected.getAttribute('stroke') || '', - strokeWidth: selected.getAttribute('stroke-width') || '', - } - selected.parentNode?.removeChild(selected) - deselect() - setMode('polygon') - } - - function scrollSvgElementIntoView(svgEl: SVGElement) { - const elRect = svgEl.getBoundingClientRect() - const cRect = canvasInner.getBoundingClientRect() - - const visible = - elRect.left >= cRect.left && - elRect.right <= cRect.right && - elRect.top >= cRect.top && - elRect.bottom <= cRect.bottom - if (visible) return - - const dx = elRect.left + elRect.width / 2 - (cRect.left + cRect.width / 2) - const dy = elRect.top + elRect.height / 2 - (cRect.top + cRect.height / 2) - - canvasInner.scrollTo({ - left: canvasInner.scrollLeft + dx, - top: canvasInner.scrollTop + dy, - behavior: 'smooth', - }) - } - - function flashSelected(svgEl: SVGElement) { - const id = svgEl.getAttribute('data-anno-id') - const cat = svgEl.getAttribute('data-anno-category') - if (!id || !svgRoot) return - const all = svgRoot.querySelectorAll(`[data-anno-id="${cssEscape(id)}"]`) - all.forEach((e) => { - if (e.getAttribute('data-anno-category') !== cat) return - e.classList.remove('flashing') - void (e as HTMLElement).getBoundingClientRect() - e.classList.add('flashing') - setTimeout(() => e.classList.remove('flashing'), 1200) - }) - } - - function exportSVG() { - if (!svgRoot) { - alert(t('svg_editor.alert_no_svg_loaded')) - return - } - const clone = svgRoot.cloneNode(true) as SVGSVGElement - clone.querySelectorAll('.polygon-preview, .polygon-preview-pt').forEach((p) => p.remove()) - const handles = clone.querySelector('#polygon-handles') - if (handles) handles.remove() - clone.querySelectorAll('.selected, .flashing').forEach((p) => { - p.classList.remove('selected') - p.classList.remove('flashing') - }) - - const ser = new XMLSerializer() - const txt = `\n` + ser.serializeToString(clone) - - const blob = new Blob([txt], { type: 'image/svg+xml;charset=utf-8' }) - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url - a.download = loadedFileName - document.body.appendChild(a) - a.click() - document.body.removeChild(a) - URL.revokeObjectURL(url) - } - - function applyZoom() { - if (!svgRoot) return - svgRoot.style.transform = `scale(${zoom})` - svgRoot.style.transformOrigin = 'top left' - } - - return () => { ac.abort() } -} diff --git a/apps/app/src/components/brand/Footer.tsx b/apps/app/src/components/brand/Footer.tsx index 6d0bb587..84ff2c6b 100644 --- a/apps/app/src/components/brand/Footer.tsx +++ b/apps/app/src/components/brand/Footer.tsx @@ -1,4 +1,3 @@ -import { Link } from 'react-router-dom' import { useConfig } from '@/app/providers/ConfigProvider' import { useT } from '@/i18n/useT' @@ -9,14 +8,7 @@ export default function Footer() { return (

- © {year} {cfg.footerName}. {t('footer.all_rights_reserved')}{' '} - ·{' '} - - {t('footer.editors')} - + © {year} {cfg.footerName}. {t('footer.all_rights_reserved')}

diff --git a/apps/app/src/components/canvas/AnatomyCanvas.tsx b/apps/app/src/components/canvas/AnatomyCanvas.tsx index 17a410f4..3b321bcc 100644 --- a/apps/app/src/components/canvas/AnatomyCanvas.tsx +++ b/apps/app/src/components/canvas/AnatomyCanvas.tsx @@ -1,77 +1,86 @@ -import { useCallback, useEffect, useRef, useState } from 'react' -import { loadSvg } from '@/anatomy/svgLoader' -import { - getBoneIdFromEvent, - getAnnotatedElement, -} from '@/anatomy/svgConvention' -import type { BoneState } from '@/anatomy/types' +import { useCallback, useEffect, useLayoutEffect, useRef } from 'react' +import { buildViewSvg, type ViewStates } from '@/anatomy/drawing' +import type { SheetIndex } from '@/services/sheetIndex' import { useLocaleStore } from '@/state/localeStore' import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' export interface AnatomyCanvasProps { - src: string - boneStates: Map - onZoneClick: (boneId: string) => void + index: SheetIndex + viewId: string + states: ViewStates + onZoneClick: (annotationId: string, viewId: string) => void 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({ - src, - boneStates, + index, + viewId, + states, onZoneClick, className = '', }: AnatomyCanvasProps) { const wrapperRef = useRef(null) const svgRef = useRef(null) const tooltipRef = useRef(null) - const [loadedSrc, setLoadedSrc] = useState(null) 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(() => { - let cancelled = false - const c = svgRef.current - if (!c) return - c.replaceChildren() - setLoadedSrc(null) - loadSvg(src).then((root) => { - if (cancelled || !c) return - c.appendChild(root) - setLoadedSrc(src) - }) - return () => { cancelled = true } - }, [src]) + const host = svgRef.current + if (!host) return + host.replaceChildren(buildViewSvg(index, viewId, statesRef.current)) + }, [index, viewId]) useEffect(() => { - const c = svgRef.current - if (!c) return - const onClick = (e: Event) => { - const id = getBoneIdFromEvent(e) - if (id) onZoneClick(id) - } - c.addEventListener('click', onClick) - return () => c.removeEventListener('click', onClick) - }, [onZoneClick]) - - useEffect(() => { - const c = svgRef.current - if (!c || loadedSrc !== src) return - const all = c.querySelectorAll('[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) + const host = svgRef.current + if (!host) return + host.querySelectorAll(ANNOTATED).forEach((el) => { + const state = states.get(el.getAttribute('data-anno-id') ?? '') + if (state) el.setAttribute('data-state', 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( (el: Element, x: number, y: number) => { const tip = tooltipRef.current if (!tip) return - const fr = el.getAttribute('data-anno-name-fr') ?? '' - const en = el.getAttribute('data-anno-name-en') ?? '' - const label = pickLocaleLabel(fr, en, locale) - if (!label) { tip.style.opacity = '0'; return } + const label = pickLocaleLabel( + el.getAttribute('data-anno-name-fr') ?? '', + el.getAttribute('data-anno-name-en') ?? '', + locale, + ) + if (!label) { + tip.style.opacity = '0' + return + } tip.textContent = label tip.style.opacity = '1' tip.style.left = `${x + 12}px` @@ -80,46 +89,40 @@ export default function AnatomyCanvas({ [locale], ) - const hideTooltip = useCallback(() => { - const tip = tooltipRef.current - if (tip) tip.style.opacity = '0' - }, []) - useEffect(() => { - const c = svgRef.current - if (!c || loadedSrc !== src) return + const host = svgRef.current + if (!host) return + const hide = () => { + if (tooltipRef.current) tooltipRef.current.style.opacity = '0' + } const onMove = (e: MouseEvent) => { - const el = getAnnotatedElement(e) - if (el && !el.hasAttribute('data-anno-opens-detail')) { - const w = wrapperRef.current - if (!w) return - const rect = w.getBoundingClientRect() - showTooltip(el, e.clientX - rect.left, e.clientY - rect.top) - } else { - hideTooltip() - } + const el = annotatedTarget(e) + const wrapper = wrapperRef.current + if (!el || !wrapper || el.hasAttribute('data-anno-opens-view')) + return hide() + const rect = wrapper.getBoundingClientRect() + showTooltip(el, e.clientX - rect.left, e.clientY - rect.top) } - const onLeave = () => hideTooltip() - c.addEventListener('mousemove', onMove) - c.addEventListener('mouseleave', onLeave) + host.addEventListener('mousemove', onMove) + host.addEventListener('mouseleave', hide) return () => { - c.removeEventListener('mousemove', onMove) - c.removeEventListener('mouseleave', onLeave) + host.removeEventListener('mousemove', onMove) + host.removeEventListener('mouseleave', hide) } - }, [loadedSrc, src, showTooltip, hideTooltip]) + }, [showTooltip]) return (
-
+
) } diff --git a/apps/app/src/components/canvas/DetailModal.tsx b/apps/app/src/components/canvas/DetailModal.tsx index d3056126..3bbe1dae 100644 --- a/apps/app/src/components/canvas/DetailModal.tsx +++ b/apps/app/src/components/canvas/DetailModal.tsx @@ -1,25 +1,27 @@ import Dialog from '@/components/ui/Dialog' 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' export interface DetailModalProps { open: boolean onClose: () => void - detailSrc: string - detailId: string + index: SheetIndex + viewId: string title: string - boneStates: Map - onZoneClick: (boneId: string, detailId: string) => void + states: ViewStates + 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({ open, onClose, - detailSrc, - detailId, + index, + viewId, title, - boneStates, + states, onZoneClick, }: DetailModalProps) { const t = useT() @@ -27,9 +29,10 @@ export default function DetailModal({
onZoneClick(id, detailId)} + index={index} + viewId={viewId} + states={states} + onZoneClick={onZoneClick} />

diff --git a/apps/app/src/components/observation/FindingsTreePicker.tsx b/apps/app/src/components/observation/FindingsTreePicker.tsx index 221aae5f..d41013f8 100644 --- a/apps/app/src/components/observation/FindingsTreePicker.tsx +++ b/apps/app/src/components/observation/FindingsTreePicker.tsx @@ -1,75 +1,84 @@ import { useMemo, useState } from 'react' import { motion } from 'motion/react' import type { + Finding, + FindingCategory, FindingNode, - ZoneFindings, -} from '@/domain/schema/findings' -import type { Finding, LateralSide } from '@/domain/schema/observation' + FindingZone, + LateralSide, + LocalizedOptionalText, +} from '@faunosteo/domain' import Button from '@/components/ui/Button' +import { pickLabel } from '@/services/sheetIndex' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' +import type { Locale } from '@/i18n/types' const levelVariants = { enter: (dir: 1 | -1) => ({ opacity: 0, x: dir * 32 }), center: { opacity: 1, x: 0 }, } +type TreeNode = FindingCategory | FindingNode + export interface FindingsTreePickerProps { - zoneId: string - tree: ZoneFindings + zone: FindingZone side?: LateralSide selected: Finding[] onChange: (next: Finding[]) => void } -function isLeaf(node: FindingNode): boolean { - return !node.children || node.children.length === 0 +function isLeaf(node: TreeNode): boolean { + return node.children.length === 0 } -function samePath(a: string[], b: string[]): boolean { - if (a.length !== b.length) return false - for (let i = 0; i < a.length; i += 1) { - if (a[i] !== b[i]) return false - } - return true +function samePath(a: readonly string[], b: readonly string[]): boolean { + return a.length === b.length && a.every((seg, i) => seg === b[i]) } -function pathStartsWith(full: string[], prefix: string[]): boolean { - if (full.length < prefix.length) return false - for (let i = 0; i < prefix.length; i += 1) { - if (full[i] !== prefix[i]) return false - } - return true +function pathStartsWith( + full: readonly string[], + prefix: readonly string[], +): boolean { + return ( + full.length >= prefix.length && prefix.every((seg, i) => full[i] === seg) + ) } function findNode( - categories: FindingNode[], - path: string[], -): FindingNode | undefined { - let nodes: FindingNode[] = categories - let node: FindingNode | undefined + categories: readonly FindingCategory[], + path: readonly string[], +): TreeNode | undefined { + let nodes: readonly TreeNode[] = categories + let node: TreeNode | undefined for (const segment of path) { node = nodes.find((n) => n.id === segment) if (!node) return undefined - nodes = node.children ?? [] + nodes = node.children } 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({ - zoneId, - tree, + zone, side, selected, onChange, }: FindingsTreePickerProps) { const t = useT() 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([]) const [direction, setDirection] = useState<1 | -1>(1) @@ -86,74 +95,57 @@ export default function FindingsTreePicker({ setPath(path.slice(0, depth)) } - const currentNodes = useMemo(() => { - if (path.length === 0) return tree.categories - const node = findNode(tree.categories, path) - return node?.children ?? [] - }, [tree, path]) + const currentNodes = useMemo(() => { + if (path.length === 0) return zone.categories + return findNode(zone.categories, path)?.children ?? [] + }, [zone, path]) const focusedNode = useMemo( - () => (path.length === 0 ? undefined : findNode(tree.categories, path)), - [tree, path], + () => (path.length === 0 ? undefined : findNode(zone.categories, path)), + [zone, path], ) const breadcrumb = useMemo<{ label: string; depth: number }[]>(() => { - const pick = (z: { name_fr: string; name_en: string }) => - locale === 'en' ? z.name_en : z.name_fr - const crumbs: { label: string; depth: number }[] = [ - { label: pick(tree), depth: 0 }, - ] - let nodes: FindingNode[] = tree.categories + const crumbs = [{ label: pickLabel(zone.name, locale), depth: 0 }] + let nodes: readonly TreeNode[] = zone.categories path.forEach((seg, i) => { const n = nodes.find((x) => x.id === seg) if (n) { - crumbs.push({ label: pick(n), depth: i + 1 }) - nodes = n.children ?? [] + crumbs.push({ label: pickLabel(n.name, locale), depth: i + 1 }) + nodes = n.children } }) return crumbs - }, [tree, path, locale]) + }, [zone, path, locale]) - function matchesSide(f: Finding): boolean { - return f.zoneId === zoneId && f.side === side - } + const matches = (f: Finding) => f.findingZoneId === zone.id && 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 { - 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) { + function toggleLeaf(leafPath: string[], leaf: TreeNode) { if (isLeafSelected(leafPath)) { onChange( - selected.filter( - (f) => !(matchesSide(f) && samePath(f.path, leafPath)), - ), + selected.filter((f) => !(matches(f) && samePath(f.path, leafPath))), ) return } const next: Finding = { - zoneId, + findingZoneId: zone.id, path: leafPath, - labelFrSnapshot: leaf.name_fr, - labelEnSnapshot: leaf.name_en, + labelFrSnapshot: leaf.name.fr, + 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 onChange([...selected, next]) } + const focusedDescription = focusedNode && descriptionOf(focusedNode, locale) + return (

@@ -179,9 +171,9 @@ export default function FindingsTreePicker({ })}
- {focusedNode && descOf(focusedNode) && ( + {focusedDescription && (

- {descOf(focusedNode)} + {focusedDescription}

)} @@ -196,16 +188,15 @@ export default function FindingsTreePicker({ )} - + {currentNodes.length === 0 ? (
  • {t('findings.no_options')} @@ -213,16 +204,17 @@ export default function FindingsTreePicker({ ) : ( currentNodes.map((node) => { const nodePath = [...path, node.id] + const nodeLabel = pickLabel(node.name, locale) + const nodeDesc = descriptionOf(node, locale) if (isLeaf(node)) { - const checked = isLeafSelected(nodePath) - const nodeLabel = nameOf(node) - const nodeDesc = descOf(node) + const vet = + 'requires_vet_referral' in node && node.requires_vet_referral return (
  • ) } diff --git a/apps/app/src/components/observation/LateralityPicker.tsx b/apps/app/src/components/observation/LateralityPicker.tsx index 3d3547e3..c6b34bba 100644 --- a/apps/app/src/components/observation/LateralityPicker.tsx +++ b/apps/app/src/components/observation/LateralityPicker.tsx @@ -1,6 +1,6 @@ import Dialog from '@/components/ui/Dialog' import Button from '@/components/ui/Button' -import type { LateralSide } from '@/domain/schema/observation' +import type { LateralSide } from '@faunosteo/domain' import { useT } from '@/i18n/useT' export interface LateralityPickerProps { diff --git a/apps/app/src/components/observation/ObservationCard.tsx b/apps/app/src/components/observation/ObservationCard.tsx index 86de9ea6..57f5b845 100644 --- a/apps/app/src/components/observation/ObservationCard.tsx +++ b/apps/app/src/components/observation/ObservationCard.tsx @@ -1,16 +1,11 @@ import { useMemo, useState } from 'react' import type { - Observation, - ObservationZone, - Vertebra, + Finding, + FindingZone, LateralSide, -} from '@/domain/schema/observation' -import type { - SpeciesFindings, - ZoneFindings, -} from '@/domain/schema/findings' -import type { Bone } from '@/anatomy/types' -import { matchZoneFindings } from '@/lib/zoneMatch' + Observation, + ReportZone, +} from '@faunosteo/domain' import { AnimatePresence, motion } from 'motion/react' import Card from '@/components/ui/Card' import Badge from '@/components/ui/Badge' @@ -20,9 +15,9 @@ import Textarea from '@/components/ui/Textarea' import FindingsTreePicker from './FindingsTreePicker' import FreeTextFindingInput from './FreeTextFindingInput' import SeveritySelector from './SeveritySelector' +import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' -import { boneLabel } from '@/anatomy/labels' import type { Locale } from '@/i18n/types' export interface ObservationCardProps { @@ -36,35 +31,75 @@ export interface ObservationCardProps { canMoveUp: boolean canMoveDown: boolean // Editor body props (used only when expanded) - bones: Map - findings: SpeciesFindings | null + sheet: SheetIndex onChange: (next: Observation) => void onOpenVertebraPicker: (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( - z: ObservationZone, - bones: Map, + z: ReportZone, + sheet: SheetIndex, locale: Locale, t: (key: string) => string, ): string { - const label = boneLabel(bones.get(z.boneId), locale, z.boneId) + const label = zoneLabel(z, sheet, locale) if (z.vertebrae?.length) { - const vs = z.vertebrae - .map((v: Vertebra) => `${v.region}${v.index}`) - .join(', ') - return `${label} (${vs})` + return `${label} (${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')})` } if (z.side) { - const sideLabel = t( - z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short', - ) - return `${label} (${sideLabel})` + return `${label} (${t(z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})` } 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() + 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({ observation, index, @@ -75,34 +110,37 @@ export default function ObservationCard({ onMoveDown, canMoveUp, canMoveDown, - bones, - findings, + sheet, onChange, onOpenVertebraPicker, onRemoveZone, }: ObservationCardProps) { const t = useT() 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(null) const zoneCount = observation.zones.length const findingCount = observation.findings.length + observation.freeTextFindings.length - - const zoneCountLabel = + const zoneCountLabel = t( zoneCount > 1 - ? t('observation.zone_label_plural') - : t('observation.zone_label_singular') - const findingCountLabel = + ? 'observation.zone_label_plural' + : 'observation.zone_label_singular', + ) + const findingCountLabel = t( findingCount > 1 - ? t('observation.finding_label_plural') - : t('observation.finding_label_singular') + ? 'observation.finding_label_plural' + : '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) { if (event.key === 'Enter' || event.key === ' ') { @@ -110,39 +148,15 @@ export default function ObservationCard({ onToggle() } } - - function stop(fn: () => void) { - return (event: React.MouseEvent) => { - event.stopPropagation() - fn() - } + const stop = (fn: () => void) => (event: React.MouseEvent) => { + event.stopPropagation() + fn() } - - const zonesArray = useMemo( - () => (findings ? Object.values(findings.zones) : []), - [findings], - ) - - const zonesWithTree = useMemo(() => { - if (zonesArray.length === 0) - return [] as { tree: ZoneFindings; side?: LateralSide }[] - const seen = new Set() - 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]) + const removeFinding = (target: Finding) => + onChange({ + ...observation, + findings: observation.findings.filter((f) => f !== target), + }) return (
    - {t('observation.badge_n')}{index + 1} + + {t('observation.badge_n')} + {index + 1} + {observation.severity && ( ) : (
      - {observation.zones.map((z, i) => { - const b = bones.get(z.boneId) - const supportsVertebrae = - b?.special === 'vertebral-precision' - return ( -
    • - - {describeZone(z, bones, locale, t)} - {supportsVertebrae && ( - + {t('observation.unresolved_short')} + )} + {sheet.isSpine(z.annotationId) && ( - -
    • - ) - })} + )} + + + + ))}
    )}
    - {zonesWithTree.length === 0 ? ( + {trees.length === 0 ? (

    {observation.zones.length === 0 ? t('observation.findings_pick_zone_first') @@ -292,26 +315,19 @@ export default function ObservationCard({

    ) : (
      - {zonesWithTree.map(({ tree, side }) => { - const pickerKey = side - ? `${tree.id}:${side}` - : tree.id - const expanded = expandedZoneId === pickerKey + {trees.map(({ zone, side }) => { + const pickerKey = side ? `${zone.id}:${side}` : zone.id + const open = expandedZoneId === pickerKey const selectedCount = observation.findings.filter( - (f) => - f.zoneId === tree.id && f.side === side, + (f) => f.findingZoneId === zone.id && f.side === side, ).length - const selectedAria = `${selectedCount} ${ - selectedCount > 1 - ? t('findings.selected_plural') - : t('findings.selected_singular') - }` + const selectedAria = `${selectedCount} ${selectedCount > 1 ? t('findings.selected_plural') : t('findings.selected_singular')}` return (
    • - setExpandedZoneId(expanded ? null : pickerKey) + setExpandedZoneId(open ? null : pickerKey) } - aria-expanded={expanded} + aria-expanded={open} 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" > - {nameOf(tree)} - {side && ` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`} + {pickLabel(zone.name, locale)} + {side && + ` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`} {selectedCount > 0 && ( - {expanded && ( + {open && (
      - onChange({ ...observation, findings: next }) + onChange({ + ...observation, + findings: next, + }) } />
      @@ -378,6 +397,40 @@ export default function ObservationCard({ )}
    + {unresolved.length > 0 && ( +
    + +

    + {t('observation.findings_unresolved_help')} +

    +
      + {unresolved.map((f, i) => ( +
    • + + {f.requiresVetReferral ? '⚠ ' : ''} + {locale === 'en' + ? f.labelEnSnapshot + : f.labelFrSnapshot} + {f.side && + ` (${t(f.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`} + + +
    • + ))} +
    +
    + )} +
    void onMoveDown: (i: number) => void // Editor body props forwarded to each card - bones: Map - findings: SpeciesFindings | null + sheet: SheetIndex onChange: (i: number, next: Observation) => void onOpenVertebraPicker: (i: number, zoneIndex: number) => void onRemoveZone: (i: number, zoneIndex: number) => void @@ -29,8 +27,7 @@ export default function ObservationList({ onDelete, onMoveUp, onMoveDown, - bones, - findings, + sheet, onChange, onOpenVertebraPicker, onRemoveZone, @@ -64,8 +61,7 @@ export default function ObservationList({ onMoveDown={() => onMoveDown(i)} canMoveUp={i > 0} canMoveDown={i < observations.length - 1} - bones={bones} - findings={findings} + sheet={sheet} onChange={(next) => onChange(i, next)} onOpenVertebraPicker={(zoneIndex) => onOpenVertebraPicker(i, zoneIndex) diff --git a/apps/app/src/components/observation/ObservationPickers.tsx b/apps/app/src/components/observation/ObservationPickers.tsx new file mode 100644 index 00000000..81422a21 --- /dev/null +++ b/apps/app/src/components/observation/ObservationPickers.tsx @@ -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) && ( + { + 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 && ( + { + const fresh = + useReportStore.getState().report?.observations[activeIndex] + if (fresh) + updateObservation( + activeIndex, + addSides(fresh, lateralAnnotation, sides), + ) + onCloseLateral() + }} + /> + )} + + ) +} diff --git a/apps/app/src/components/observation/SeveritySelector.tsx b/apps/app/src/components/observation/SeveritySelector.tsx index 16f22c53..996159fc 100644 --- a/apps/app/src/components/observation/SeveritySelector.tsx +++ b/apps/app/src/components/observation/SeveritySelector.tsx @@ -1,4 +1,4 @@ -import type { Severity } from '@/domain/schema/observation' +import type { Severity } from '@faunosteo/domain' import { useT } from '@/i18n/useT' export interface SeveritySelectorProps { @@ -6,17 +6,25 @@ export interface SeveritySelectorProps { 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 = { - 'légère': 'border-[var(--severity-mild)] text-[var(--severity-mild)]', - 'modérée': 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]', - 'sévère': 'border-[var(--severity-severe)] text-[var(--severity-severe)]', + mild: 'border-[var(--severity-mild)] text-[var(--severity-mild)]', + moderate: 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]', + 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() return ( -
    +
    {SEVERITIES.map((s) => ( ))}
    @@ -89,26 +96,52 @@ export default function VertebraPicker({ {Array.from({ length: count }, (_, k) => k + 1).map((i) => ( toggle(activeRegion, i)} + active={has(active.code, i)} + onClick={() => toggle(active.code, i)} > - {activeRegion}{i} + {active.code} + {i} ))}
    - - + {canExtend && !showExtended && ( + + )} + {canExtend && showExtended && ( + + {t('vertebra.range_note') + .replace('{usual}', String(active.count)) + .replace('{min}', String(active.count_range?.min ?? active.count)) + .replace('{max}', String(maxCount))} + + )}
    - - + +
    ) diff --git a/apps/app/src/components/report/AnimalForm.tsx b/apps/app/src/components/report/AnimalForm.tsx index effc2527..c04f9b67 100644 --- a/apps/app/src/components/report/AnimalForm.tsx +++ b/apps/app/src/components/report/AnimalForm.tsx @@ -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 Input from '@/components/ui/Input' import Select from '@/components/ui/Select' -import { getAllSpecies, speciesLabel } from '@/domain/species/registry' +import { pickLabel } from '@/services/sheetIndex' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' +export interface SpeciesOption { + id: string + name: LocalizedText +} + export interface AnimalFormProps { animal: Animal owner: Owner + /** Species that have a sheet in this build (one today). */ + species: readonly SpeciesOption[] onChangeAnimal: (next: Animal) => 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 locale = useLocaleStore((s) => s.locale) - const species = getAllSpecies() - const setA = (patch: Partial) => onChangeAnimal({ ...animal, ...patch }) + const setA = (patch: Partial) => + onChangeAnimal({ ...animal, ...patch }) return (
    @@ -31,25 +44,45 @@ export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwne onChange={(e) => setA({ speciesId: e.target.value })} > {species.map((s) => ( - + ))}
    - setA({ name: e.target.value })} /> + setA({ name: e.target.value })} + />
    - setA({ breed: e.target.value || undefined })} /> + setA({ breed: e.target.value || undefined })} + />
    - setA({ age: e.target.value || undefined })} /> + setA({ age: e.target.value || undefined })} + />
    - onChangeOwner({ name: e.target.value })} /> + onChangeOwner({ name: e.target.value })} + />
    ) diff --git a/apps/app/src/components/report/ConclusionPanel.tsx b/apps/app/src/components/report/ConclusionPanel.tsx index 72757b8d..d73b8651 100644 --- a/apps/app/src/components/report/ConclusionPanel.tsx +++ b/apps/app/src/components/report/ConclusionPanel.tsx @@ -1,4 +1,4 @@ -import type { Report } from '@/domain/schema/report' +import type { Report } from '@faunosteo/domain' import Label from '@/components/ui/Label' import Textarea from '@/components/ui/Textarea' import NextAppointmentPicker from './NextAppointmentPicker' @@ -29,13 +29,26 @@ export default function ConclusionPanel({
    -