From 8ca36b5ccd245cc77fcc735c5515945e396820e1 Mon Sep 17 00:00:00 2001 From: Bastien Chanot Date: Mon, 18 May 2026 20:55:10 +0200 Subject: [PATCH] chore: initial scaffold + design spec + implementation plan Skeleton for Osteo Report MVP. Build passes, 7 smoke tests green, real Horse.svg + Horse_head.svg in public/species/equine/. Zod schemas are the contract; store/anatomy/pdf modules are typed stubs throwing "not implemented" awaiting implementation. Spec: docs/superpowers/specs/2026-05-18-osteo-report-mvp-design.md Plan: docs/superpowers/plans/2026-05-18-osteo-report-mvp.md (23 phases, ~70 TDD tasks) Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/audits/.gitkeep | 0 .claude/memory/blockers.md | 20 + .claude/memory/decisions.md | 58 + .claude/memory/evals.md | 12 + .claude/memory/journal.md | 11 + .claude/memory/learnings.md | 28 + .claude/settings.json | 38 + .claude/tasks/IMPLEMENTATION-PLAN.md | 14 + .claude/tasks/TODO.md | 105 + .claudeignore | 55 + .dockerignore | 13 + .editorconfig | 15 + .env.example | 12 + .npmrc | 2 + .nvmrc | 1 + .prettierrc.json | 11 + CLAUDE.md | 303 ++ Dockerfile | 34 + LICENSE | 21 + README.md | 116 + docker-compose.yml | 10 + docker/entrypoint.sh | 27 + docker/nginx.conf | 23 + docs/ADDING-A-SPECIES.md | 10 + docs/ANATOMY-SVG-CONVENTION.md | 172 + docs/PDF-FORMAT.md | 12 + .../plans/2026-05-18-osteo-report-mvp.md | 4269 +++++++++++++++++ .../2026-05-18-osteo-report-mvp-design.md | 370 ++ eslint.config.js | 41 + index.html | 20 + package.json | 50 + pnpm-lock.yaml | 4155 ++++++++++++++++ pnpm-workspace.yaml | 3 + public/species/equine/Horse.svg | 698 +++ public/species/equine/Horse_head.svg | 698 +++ src/anatomy/svgConvention.ts | 42 + src/anatomy/svgLoader.ts | 18 + src/anatomy/types.ts | 40 + src/app/App.tsx | 21 + src/app/providers/ConfigProvider.tsx | 17 + src/app/routes/EditorRoute.tsx | 3 + src/app/routes/HomeRoute.tsx | 3 + src/app/routes/NewReportRoute.tsx | 3 + src/app/routes/NotFoundRoute.tsx | 3 + src/components/brand/Brand.tsx | 3 + src/components/canvas/AnatomyCanvas.tsx | 3 + src/components/canvas/DetailModal.tsx | 3 + src/components/canvas/ZoneTooltip.tsx | 3 + .../observation/FreeTextPathologyInput.tsx | 3 + .../observation/ObservationCard.tsx | 3 + .../observation/ObservationEditor.tsx | 3 + .../observation/ObservationList.tsx | 3 + .../observation/PathologyPicker.tsx | 3 + .../observation/SeveritySelector.tsx | 3 + src/components/observation/VertebraPicker.tsx | 3 + src/components/report/AnimalForm.tsx | 3 + src/components/report/ConclusionPanel.tsx | 3 + .../report/NextAppointmentPicker.tsx | 3 + src/components/report/PractitionerForm.tsx | 3 + src/components/report/ReportHeader.tsx | 3 + src/components/ui/Badge.tsx | 3 + src/components/ui/Button.tsx | 3 + src/components/ui/Card.tsx | 3 + src/components/ui/Chip.tsx | 3 + src/components/ui/Dialog.tsx | 3 + src/components/ui/Input.tsx | 3 + src/components/ui/Label.tsx | 3 + src/components/ui/Select.tsx | 3 + src/components/ui/Textarea.tsx | 3 + src/components/ui/Toast.tsx | 3 + src/config/env.ts | 52 + src/domain/schema/animal.ts | 17 + src/domain/schema/observation.ts | 38 + src/domain/schema/pathology.ts | 47 + src/domain/schema/practitioner.ts | 11 + src/domain/schema/report.ts | 30 + src/domain/species/equine/index.ts | 13 + src/domain/species/equine/pathologies.ts | 10 + src/domain/species/equine/vertebrae.ts | 13 + src/domain/species/registry.ts | 17 + src/domain/species/types.ts | 30 + src/lib/assert.ts | 17 + src/lib/dates.ts | 20 + src/lib/id.ts | 13 + src/main.tsx | 16 + src/pdf/attachment.ts | 23 + src/pdf/export.ts | 10 + src/pdf/fonts.ts | 18 + src/pdf/import.ts | 25 + src/pdf/render/conclusionPage.ts | 15 + src/pdf/render/footer.ts | 15 + src/pdf/render/header.ts | 14 + src/pdf/render/observationPage.ts | 19 + src/pdf/render/svgToPng.ts | 11 + src/state/practitionerCache.ts | 28 + src/state/reportStore.ts | 83 + src/styles/index.css | 29 + src/styles/tokens.css | 19 + tests/setup.ts | 1 + tests/unit/smoke.test.ts | 55 + tsconfig.json | 28 + tsconfig.node.json | 14 + vite.config.ts | 22 + vitest.config.ts | 20 + 104 files changed, 12448 insertions(+) create mode 100644 .claude/audits/.gitkeep create mode 100644 .claude/memory/blockers.md create mode 100644 .claude/memory/decisions.md create mode 100644 .claude/memory/evals.md create mode 100644 .claude/memory/journal.md create mode 100644 .claude/memory/learnings.md create mode 100644 .claude/settings.json create mode 100644 .claude/tasks/IMPLEMENTATION-PLAN.md create mode 100644 .claude/tasks/TODO.md create mode 100644 .claudeignore create mode 100644 .dockerignore create mode 100644 .editorconfig create mode 100644 .env.example create mode 100644 .npmrc create mode 100644 .nvmrc create mode 100644 .prettierrc.json create mode 100644 CLAUDE.md create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100644 docker/entrypoint.sh create mode 100644 docker/nginx.conf create mode 100644 docs/ADDING-A-SPECIES.md create mode 100644 docs/ANATOMY-SVG-CONVENTION.md create mode 100644 docs/PDF-FORMAT.md create mode 100644 docs/superpowers/plans/2026-05-18-osteo-report-mvp.md create mode 100644 docs/superpowers/specs/2026-05-18-osteo-report-mvp-design.md create mode 100644 eslint.config.js create mode 100644 index.html create mode 100644 package.json create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 public/species/equine/Horse.svg create mode 100644 public/species/equine/Horse_head.svg create mode 100644 src/anatomy/svgConvention.ts create mode 100644 src/anatomy/svgLoader.ts create mode 100644 src/anatomy/types.ts create mode 100644 src/app/App.tsx create mode 100644 src/app/providers/ConfigProvider.tsx create mode 100644 src/app/routes/EditorRoute.tsx create mode 100644 src/app/routes/HomeRoute.tsx create mode 100644 src/app/routes/NewReportRoute.tsx create mode 100644 src/app/routes/NotFoundRoute.tsx create mode 100644 src/components/brand/Brand.tsx create mode 100644 src/components/canvas/AnatomyCanvas.tsx create mode 100644 src/components/canvas/DetailModal.tsx create mode 100644 src/components/canvas/ZoneTooltip.tsx create mode 100644 src/components/observation/FreeTextPathologyInput.tsx create mode 100644 src/components/observation/ObservationCard.tsx create mode 100644 src/components/observation/ObservationEditor.tsx create mode 100644 src/components/observation/ObservationList.tsx create mode 100644 src/components/observation/PathologyPicker.tsx create mode 100644 src/components/observation/SeveritySelector.tsx create mode 100644 src/components/observation/VertebraPicker.tsx create mode 100644 src/components/report/AnimalForm.tsx create mode 100644 src/components/report/ConclusionPanel.tsx create mode 100644 src/components/report/NextAppointmentPicker.tsx create mode 100644 src/components/report/PractitionerForm.tsx create mode 100644 src/components/report/ReportHeader.tsx create mode 100644 src/components/ui/Badge.tsx create mode 100644 src/components/ui/Button.tsx create mode 100644 src/components/ui/Card.tsx create mode 100644 src/components/ui/Chip.tsx create mode 100644 src/components/ui/Dialog.tsx create mode 100644 src/components/ui/Input.tsx create mode 100644 src/components/ui/Label.tsx create mode 100644 src/components/ui/Select.tsx create mode 100644 src/components/ui/Textarea.tsx create mode 100644 src/components/ui/Toast.tsx create mode 100644 src/config/env.ts create mode 100644 src/domain/schema/animal.ts create mode 100644 src/domain/schema/observation.ts create mode 100644 src/domain/schema/pathology.ts create mode 100644 src/domain/schema/practitioner.ts create mode 100644 src/domain/schema/report.ts create mode 100644 src/domain/species/equine/index.ts create mode 100644 src/domain/species/equine/pathologies.ts create mode 100644 src/domain/species/equine/vertebrae.ts create mode 100644 src/domain/species/registry.ts create mode 100644 src/domain/species/types.ts create mode 100644 src/lib/assert.ts create mode 100644 src/lib/dates.ts create mode 100644 src/lib/id.ts create mode 100644 src/main.tsx create mode 100644 src/pdf/attachment.ts create mode 100644 src/pdf/export.ts create mode 100644 src/pdf/fonts.ts create mode 100644 src/pdf/import.ts create mode 100644 src/pdf/render/conclusionPage.ts create mode 100644 src/pdf/render/footer.ts create mode 100644 src/pdf/render/header.ts create mode 100644 src/pdf/render/observationPage.ts create mode 100644 src/pdf/render/svgToPng.ts create mode 100644 src/state/practitionerCache.ts create mode 100644 src/state/reportStore.ts create mode 100644 src/styles/index.css create mode 100644 src/styles/tokens.css create mode 100644 tests/setup.ts create mode 100644 tests/unit/smoke.test.ts create mode 100644 tsconfig.json create mode 100644 tsconfig.node.json create mode 100644 vite.config.ts create mode 100644 vitest.config.ts diff --git a/.claude/audits/.gitkeep b/.claude/audits/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md new file mode 100644 index 00000000..82d16ffa --- /dev/null +++ b/.claude/memory/blockers.md @@ -0,0 +1,20 @@ +# Blockers Registry + +Format: BLK-XXX | Date | Friction | Root cause | Solution | Status + +--- + +## BLK-001 | 2026-05-18 | pnpm not on PATH + +pnpm command not found on shell start. +Root: corepack shim broken on Node 20.20.0 (ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING). +Fix: curl https://get.pnpm.io/install.sh → ~/.local/share/pnpm/bin/pnpm. +Status: resolved. + +--- + +## BLK-002 | 2026-05-18 | Pathology DB empty — pending content review + +40-60 equine entries needed; source-cited from Merck Vet Manual, IMAIOS, PubMed, EVJ, WikiVet, LCAO. +Client osteo will review post-scaffold. +Status: open — Phase 2d. diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md new file mode 100644 index 00000000..00fc7214 --- /dev/null +++ b/.claude/memory/decisions.md @@ -0,0 +1,58 @@ +# Decisions Registry + +Format: BDR-XXX | Date | Title | Rationale | Alternatives | Status + +--- + +## BDR-001 | 2026-05-18 | React SPA exception for tool app + +Tool is practitioner-only, no public indexing needed → SPA valid per CLAUDE.md rule. +Alt: Next.js SSR rejected — no server, static deploy only. +Status: closed. + +--- + +## BDR-002 | 2026-05-18 | SVG inline via DOMParser, not img/object + +Inline SVG = full CSS control, pointer-events, data-* access. +img/object = sandboxed, no DOM access, no click delegation. +Status: closed. + +--- + +## BDR-003 | 2026-05-18 | PDF attachment via native pdf-lib attach() + +Native EmbeddedFiles (afRelationship:Data) = proper PDF spec, survives re-save in Acrobat. +Alt: custom metadata → rejected (non-standard, stripped by some viewers). +Status: closed. + +--- + +## BDR-004 | 2026-05-18 | Runtime identity via window.__APP_CONFIG__ + +Build-time VITE_APP_* → baked into bundle; runtime injection via entrypoint.sh → no rebuild needed for brand changes. +Order: runtime > build-time > defaults. +Status: closed. + +--- + +## BDR-005 | 2026-05-18 | Vertebra picker: region tabs + chip grid + +≥40px touch targets, multi-select, per-region toggle. +Alt: flat list → too long for 54 total vertebrae. +Status: closed. + +--- + +## BDR-006 | 2026-05-18 | Drag-reorder: up/down buttons, not DnD + +DnD on mobile unreliable; ↑/↓ buttons accessible + simple. +Status: closed. + +--- + +## BDR-007 | 2026-05-18 | pnpm 11 used instead of pnpm 9 + +pnpm@9 not available on host; corepack resolved 11.1.3. +Package.json engine constraint set to >=9 for Docker (Docker uses corepack latest). +Status: closed — deviation accepted. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md new file mode 100644 index 00000000..abb565ba --- /dev/null +++ b/.claude/memory/evals.md @@ -0,0 +1,12 @@ +# Evals Registry + +Format: EVAL-XXX | Date | What evaluated | Method | Result | Anomalies | Action + +--- + +## EVAL-001 | 2026-05-18 | Scaffold build + test pass + +Method: pnpm install → pnpm build → pnpm test:run → pnpm typecheck. +Result: all pass, 0 errors. +Anomalies: pnpm version 11 instead of 9 (corepack issue on host). +Action: document in BDR-007, BLK-001. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md new file mode 100644 index 00000000..84d1b885 --- /dev/null +++ b/.claude/memory/journal.md @@ -0,0 +1,11 @@ +# Journal + +--- + +## 2026-05-18 + +Scaffolded Osteo Report MVP skeleton from approved design spec. +Created 80+ files: schemas, stubs, routes, stores, PDF modules, Docker infra. +Moved Horse.svg + Horse_head.svg to public/species/equine/. +pnpm install + build + typecheck + tests passing. +pnpm 11 used (corepack shim broken on host Node 20.20.0). diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md new file mode 100644 index 00000000..d69cda1c --- /dev/null +++ b/.claude/memory/learnings.md @@ -0,0 +1,28 @@ +# Learnings Registry + +Format: LRN-XXX | Date | Pattern | Context | Future application + +--- + +## LRN-001 | 2026-05-18 | Zod discriminatedUnion for nextAppointment + +Report.nextAppointment uses discriminatedUnion('kind', [...]). +Gives precise TS narrowing on .kind; avoids optional union type ambiguity. +Apply: any polymorphic field with a literal discriminant. + +--- + +## LRN-002 | 2026-05-18 | SVG hitbox+visible twin pattern + +Two SVG elements share same data-bone-id: hitbox (pointer-events:all, fill:transparent) + visible (pointer-events:none, colored). +Parser groups by data-bone-id → Bone.hitboxEls[], Bone.visibleEls[]. +Apply: any SVG-based interactive map needing precise click areas. + +--- + +## LRN-003 | 2026-05-18 | pnpm via corepack shim breaks on older Node 20 + +corepack shim on Node 20.20.0 throws ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +Fix: install pnpm directly via get.pnpm.io/install.sh. +Binary lands at ~/.local/share/pnpm/bin/pnpm. +Apply: CI/dev envs without system pnpm. diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000..fbd7995d --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,38 @@ +{ + "permissions": { + "allow": [ + "Bash(pnpm *)", + "Bash(node *)", + "Bash(npx *)", + "Bash(tsc *)", + "Bash(vite *)", + "Bash(vitest *)", + "Bash(eslint *)", + "Bash(prettier *)", + "Bash(docker build *)", + "Bash(docker compose *)", + "Bash(docker ps*)", + "Bash(docker images*)", + "Bash(docker logs *)", + "Bash(git status)", + "Bash(git log *)", + "Bash(git diff *)", + "Bash(git add *)", + "Bash(git commit *)", + "Bash(git mv *)", + "Bash(find *)", + "Bash(ls *)", + "Bash(mkdir *)", + "Bash(mv *)", + "Bash(cp *)" + ], + "ask": [ + "Bash(docker stop *)", + "Bash(docker rm *)", + "Bash(git push *)", + "Bash(git reset *)", + "Bash(git rebase *)" + ], + "deny": [] + } +} diff --git a/.claude/tasks/IMPLEMENTATION-PLAN.md b/.claude/tasks/IMPLEMENTATION-PLAN.md new file mode 100644 index 00000000..ff0011ee --- /dev/null +++ b/.claude/tasks/IMPLEMENTATION-PLAN.md @@ -0,0 +1,14 @@ +# Implementation plan + +Full plan lives at: + +- [docs/superpowers/plans/2026-05-18-osteo-report-mvp.md](../../docs/superpowers/plans/2026-05-18-osteo-report-mvp.md) + +The full design spec lives at: + +- [docs/superpowers/specs/2026-05-18-osteo-report-mvp-design.md](../../docs/superpowers/specs/2026-05-18-osteo-report-mvp-design.md) + +Read those two files before executing any task. The plan is structured in +23 phases of bite-sized TDD tasks (2–5 min each), with exact file paths and +complete code blocks per step. Use `superpowers:subagent-driven-development` +to execute it. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md new file mode 100644 index 00000000..6562e1fa --- /dev/null +++ b/.claude/tasks/TODO.md @@ -0,0 +1,105 @@ +# TODO — Osteo Report MVP + +## Status: Scaffold complete — ready for feature implementation + +--- + +## Phase 1 — Skeleton (DONE) +- [x] Directory structure created +- [x] package.json + tsconfig + vite + vitest config +- [x] ESLint 9 flat config + Prettier +- [x] Zod schemas: report, observation, practitioner, animal, pathology +- [x] Species registry + equine manifest +- [x] Zustand store shape (stubs) +- [x] Anatomy types + empty parsers +- [x] PDF module stubs (export, import, attachment, fonts, render/*) +- [x] Component stubs (ui/*, canvas/*, observation/*, report/*, brand/*) +- [x] App router + ConfigProvider +- [x] Docker: Dockerfile + docker-compose + entrypoint.sh + nginx.conf +- [x] Env injection mechanism (window.__APP_CONFIG__) +- [x] Smoke tests pass +- [x] pnpm build passes + +--- + +## Phase 2 — Core domain (next) + +### 2a. Lib utilities +- [ ] `src/lib/id.ts` — generateId: already implemented (crypto.randomUUID) +- [ ] `src/lib/dates.ts` — formatDateFr: implement Intl.DateTimeFormat +- [ ] `src/lib/assert.ts` — already implemented + +### 2b. Anatomy convention parser +- [ ] `src/anatomy/svgConvention.ts` — parseSvgBones: walk DOM, group by data-bone-id +- [ ] `src/anatomy/svgLoader.ts` — loadSvg: fetch + DOMParser inline +- [ ] Tests: valid SVG fixture → bones map; bad SVG → SvgConventionError + +### 2c. Zustand store +- [ ] `src/state/reportStore.ts` — implement all actions +- [ ] `src/state/practitionerCache.ts` — localStorage read/write with Zod validation +- [ ] Tests: initReport, addObservation, updateObservation, hydrateReport + +### 2d. Equine pathology DB +- [ ] `src/domain/species/equine/pathologies.ts` — 40-60 entries, source-cited +- [ ] Tests: all entries pass PathologySchema.parse() + have ≥1 source + +--- + +## Phase 3 — UI components + +### 3a. UI primitives +- [ ] Button, Card, Dialog, Input, Label, Select, Textarea, Badge, Chip, Toast + +### 3b. Canvas +- [ ] AnatomyCanvas: inline SVG, delegated click listener, bone state colorization +- [ ] DetailModal: load detail SVG, click handler with detailSourceId +- [ ] ZoneTooltip: hover tooltip listing all observations owning the bone + +### 3c. Observation panel +- [ ] ObservationList + ObservationCard +- [ ] ObservationEditor +- [ ] PathologyPicker + FreeTextPathologyInput +- [ ] VertebraPicker: region tabs + chip grid +- [ ] SeveritySelector + +### 3d. Report forms +- [ ] PractitionerForm + AnimalForm (prefill from localStorage cache) +- [ ] ConclusionPanel + NextAppointmentPicker +- [ ] ReportHeader + +--- + +## Phase 4 — Routes + +- [ ] HomeRoute: CTAs + session draft card +- [ ] NewReportRoute: form → initReport → navigate /editor +- [ ] EditorRoute: split layout canvas + observation panel + export bar +- [ ] sessionStorage draft sync (osteo:draft) + +--- + +## Phase 5 — PDF + +- [ ] fonts.ts: fetch Inter + Fraunces TTF, embedFonts +- [ ] render/header + footer +- [ ] render/svgToPng: canvg → canvas → PNG bytes +- [ ] render/observationPage + conclusionPage +- [ ] attachment.ts: attachReportJson + extractReportJson +- [ ] export.ts + import.ts: full roundtrip +- [ ] Tests: attachment write+extract fixture + +--- + +## Phase 6 — Docker deploy + +- [ ] Verify pnpm-lock.yaml committed for --frozen-lockfile +- [ ] docker build smoke test on CI +- [ ] nginx.conf: PORT envsubst verified + +--- + +## Phase 7 — QA + +- [ ] Manual browser test: full report → export PDF → re-import +- [ ] Font embedding verified in PDF viewer +- [ ] Brand identity via env vars verified end-to-end diff --git a/.claudeignore b/.claudeignore new file mode 100644 index 00000000..b6c4a4e7 --- /dev/null +++ b/.claudeignore @@ -0,0 +1,55 @@ +# ============================================================ +# .claudeignore — files Claude cannot read or use as context +# ============================================================ + +# Secrets & credentials +.env +.env.* +!.env.example +secrets/ +*.pem +*.key + +# Build artifacts & caches +node_modules/ +dist/ +.vite/ +coverage/ +.nyc_output/ +*.tsbuildinfo + +# Binary & media assets — reference by path only when needed +public/species/**/*.svg +src/assets/** +*.png +*.jpg +*.jpeg +*.gif +*.webp +*.ico +*.pdf +*.woff +*.woff2 +*.ttf +*.otf +*.zip +*.tar.gz + +# Large generated files +graphify-out/ +.ctx7-cache/ + +# OS / IDE +.DS_Store +Thumbs.db +.vscode/ +.idea/ +*.swp +*~ + +# Logs +*.log +logs/ + +# Lock files (read if needed for dep debugging) +# pnpm-lock.yaml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..d8af93ec --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +node_modules/ +dist/ +.git/ +.env +.env.* +!.env.example +coverage/ +.vite/ +*.log +.DS_Store +Thumbs.db +graphify-out/ +.claude/ diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..4250a327 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..45113aec --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +# Server port (nginx listen port inside Docker) +PORT=8080 + +# UI identity strings — injected at runtime via entrypoint.sh +# Never hardcode these in application code. +APP_SITE_NAME=Osteo Report +APP_BRAND_NAME=Osteo Report +APP_FOOTER_NAME=Osteo Report +APP_TAGLINE=Bilans d'ostéopathie animalière + +# Docker Compose project namespace +COMPOSE_PROJECT_NAME=osteo-report diff --git a/.npmrc b/.npmrc new file mode 100644 index 00000000..3e6c04e8 --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +shamefully-hoist=false +strict-peer-dependencies=false diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000..209e3ef4 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +20 diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..cc3bb350 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,11 @@ +{ + "semi": false, + "singleQuote": true, + "tabWidth": 2, + "useTabs": false, + "trailingComma": "all", + "printWidth": 80, + "bracketSpacing": true, + "arrowParens": "always", + "endOfLine": "lf" +} diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..d51815f4 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,303 @@ +# Osteo Report — CLAUDE.md + +# Generated by scaffolder 2026-05-18. Single source of truth for Claude in this repo. +# Global rules: ~/.claude/CLAUDE.md — this file extends or overrides them. + +--- + +## Project overview + +Single-praticien French web app for veterinary osteopathy bilans on animal anatomy SVGs. +Practitioner clicks anatomical zones, builds observations with pathologies/severity, +writes conclusion, and exports an A4 PDF. PDF carries the full JSON state as a native +attachment so importing it restores the session for a follow-up. +Static SPA, no backend, no auth. Deployed via Docker + nginx on Scaleway VPS. +MVP species: equine only. Open-source MIT. + +--- + +## Stack + +| Concern | Choice | Version | +|---|---|---| +| Runtime | Node.js | 20 | +| Package manager | pnpm | >=9 (11.x on host) | +| Build | Vite + @vitejs/plugin-react-swc | 7.x | +| UI | React | 19 | +| Language | TypeScript strict | 5.x | +| Styling | Tailwind CSS v4 CSS-first (no postcss config) | 4.x | +| State | Zustand | 5 | +| Validation | Zod | 3 | +| PDF | pdf-lib | 1.17 | +| SVG raster | canvg | 4 | +| Animation | motion | 11 | +| Tests | vitest + happy-dom + @testing-library/react | 3.x | +| Deploy | Docker multi-stage → nginx:alpine | — | + +--- + +## Build commands + +```bash +# Development +pnpm dev + +# Production build (typecheck + vite build) +pnpm build + +# Type-check only (no emit) +pnpm typecheck + +# Preview production build +pnpm preview + +# Tests (watch) +pnpm test + +# Tests (CI / single run) +pnpm test:run + +# Lint (0 warnings allowed) +pnpm lint + +# Format +pnpm format +``` + +## Docker commands + +```bash +# Build image +docker build -t osteo-report . + +# Run with compose (reads .env for APP_* vars) +docker compose up --build + +# Stop +docker compose down +``` + +Note: pnpm binary at `~/.local/share/pnpm/bin/pnpm` on dev host (corepack broken). +Add it to PATH: `export PATH="$HOME/.local/share/pnpm/bin:$PATH"`. + +--- + +## Test commands + +```bash +pnpm test:run # vitest run — all tests, single pass, CI-safe +pnpm test # vitest watch — dev loop +``` + +Test files live in `tests/unit/*.test.ts` and `tests/unit/*.test.tsx`. +Setup: `tests/setup.ts` imports @testing-library/jest-dom. + +--- + +## Lint / format commands + +```bash +pnpm lint # ESLint 9 flat config — max-warnings 0 +pnpm format # Prettier write +``` + +--- + +## Folder structure + +``` +osteo/ +├─ public/ +│ └─ species/equine/{Horse,Horse_head}.svg ← real anatomy SVGs +├─ src/ +│ ├─ app/ +│ │ ├─ App.tsx ← root router +│ │ ├─ 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 +│ │ │ └─ pathology.ts +│ │ └─ species/ +│ │ ├─ types.ts ← SpeciesManifest interface +│ │ ├─ registry.ts ← getSpecies(), getAllSpecies() +│ │ └─ equine/{index,vertebrae,pathologies}.ts +│ ├─ state/ +│ │ ├─ reportStore.ts ← Zustand store +│ │ └─ practitionerCache.ts ← localStorage prefill +│ ├─ anatomy/ +│ │ ├─ types.ts ← Bone, BoneCategory, BoneState +│ │ ├─ svgConvention.ts ← parseSvgBones() +│ │ └─ svgLoader.ts ← loadSvg(), svgToPngDataUrl() +│ ├─ components/ +│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip,Toast}.tsx +│ │ ├─ canvas/{AnatomyCanvas,DetailModal,ZoneTooltip}.tsx +│ │ ├─ observation/{ObservationList,ObservationCard,ObservationEditor, +│ │ │ PathologyPicker,VertebraPicker,SeveritySelector, +│ │ │ FreeTextPathologyInput}.tsx +│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm, +│ │ │ ConclusionPanel,NextAppointmentPicker}.tsx +│ │ └─ brand/Brand.tsx +│ ├─ pdf/ +│ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts +│ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng}.ts +│ ├─ lib/{dates,id,assert}.ts +│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first +│ └─ main.tsx +├─ tests/ +│ ├─ setup.ts +│ └─ unit/*.test.ts +├─ docker/ +│ ├─ 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 +│ ├─ PDF-FORMAT.md +│ └─ superpowers/specs/ +│ └─ 2026-05-18-osteo-report-mvp-design.md +├─ .claude/{tasks/TODO.md,memory/,audits/} +├─ Dockerfile, docker-compose.yml +├─ .env.example, .editorconfig, .nvmrc, .prettierrc.json +├─ eslint.config.js, index.html +├─ package.json, tsconfig*.json +├─ vite.config.ts, vitest.config.ts +├─ CLAUDE.md, README.md, LICENSE +``` + +--- + +## Architecture + +``` +User interaction + → React routes (BrowserRouter) + → Zustand store (reportStore) + → Components read store via selectors (no prop drilling) + +SVG interaction + → AnatomyCanvas fetches SVG text via loadSvg() + → parseSvgBones() walks DOM → Bone map + → delegated click listener → getBoneIdFromEvent() + → if spine-zone → VertebraPicker modal + → if data-opens-detail → DetailModal (loads detail SVG) + → else → updateObservation() in store + +PDF export + → exportReportToPdf(report) + → pdf-lib PDFDocument + → embedFonts (Inter body + Fraunces heading) + → for each observation: addObservationPage (rasterize SVG → PNG) + → addConclusionPage + → attachReportJson (native EmbeddedFiles) + → Uint8Array → browser download + +PDF import + → importReportFromPdf(bytes) + → extractReportJson → Zod validate + → hydrateReport() → navigate /editor + +Runtime config + → Docker entrypoint writes env.js (window.__APP_CONFIG__) + → index.html loads env.js before bundle + → src/config/env.ts reads window.__APP_CONFIG__ → VITE_APP_* → defaults + → ConfigProvider exposes via React context +``` + +--- + +## Project conventions + +### Language split +- UI strings: French (labels, placeholders, error messages, toasts) +- Code: English (variable names, function names, comments, docs) +- Never mix: no French variable names, no English labels in JSX + +### Identity strings +- NEVER hardcode APP_SITE_NAME, APP_BRAND_NAME, APP_FOOTER_NAME, APP_TAGLINE +- 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-bone-id, data-bone-fr, data-bone-en, data-category +- SvgConventionError thrown on any missing required attribute +- Never rely on element id or className for click targeting — always data-bone-id + +### Schemas +- domain/schema/*.ts are the data contracts — never change without bumping version +- All user-provided data goes through Zod parse before hitting the store +- ReportSchema.version = 1 for MVP; future breaking changes → version 2 + +### 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) +- 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 +- Fonts are TTF (pdf-lib limitation — no woff2) + +### 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 + +### Component stubs +- Scaffold stubs render
ComponentName placeholder
+- Replace stub body entirely when implementing — no partial edits on stubs + +--- + +## Exceptions to global rules + +- **React SPA**: explicit exception — this is a practitioner tool, not a public website. + No indexing needed. SPA is correct. (See BDR-001) +- **No API versioning**: no backend, no API routes. Section N/A. +- **80-char line limit**: relaxed to 100 for TypeScript generics and long Zod chains. + +--- + +## Key dependencies + +| Package | Purpose | +|---|---| +| react 19 | UI framework, automatic memo + concurrent rendering | +| react-dom 19 | DOM renderer | +| react-router-dom 7 | Client-side routing (BrowserRouter) | +| vite 7 | Build tool, HMR, ESM-native | +| @vitejs/plugin-react-swc | Fast React transform via SWC | +| typescript 5 | Type safety, strict mode | +| tailwindcss 4 | CSS-first utility framework | +| zustand 5 | Lightweight global state | +| zod 3 | Schema validation + type inference | +| pdf-lib 1.17 | Pure-JS PDF generation + native attachments | +| canvg 4 | SVG → Canvas rasterization for PDF | +| motion 11 | Animations (modals, toasts, observation cards) | +| vitest 3 | Test runner | +| happy-dom | DOM environment for tests | +| @testing-library/react | Component testing utilities | +| @testing-library/jest-dom | Custom DOM matchers | +| eslint 9 | Linting (flat config) | +| prettier 3 | Code formatting | + +--- + +## 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 pako decompression. +- pnpm binary: `~/.local/share/pnpm/bin/pnpm` on dev host. Add to PATH in shell profile. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..9016b613 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +# ---- stage 1: builder ----------------------------------------------- +FROM node:20-alpine AS builder + +WORKDIR /app + +# Install pnpm via corepack +RUN corepack enable && corepack prepare pnpm@latest --activate + +# Copy manifests first for layer caching +COPY package.json pnpm-lock.yaml* ./ + +RUN pnpm install --frozen-lockfile + +# Copy source and build +COPY . . +RUN pnpm build + +# ---- stage 2: runner ------------------------------------------------ +FROM nginx:alpine AS runner + +# Copy built static assets +COPY --from=builder /app/dist /usr/share/nginx/html + +# Copy custom nginx config and entrypoint +COPY docker/nginx.conf /etc/nginx/conf.d/default.conf +COPY docker/entrypoint.sh /entrypoint.sh + +RUN chmod +x /entrypoint.sh + +# Drop root: nginx master runs as root for port binding, workers as nginx +# The entrypoint writes env.js before exec-ing nginx +EXPOSE 8080 + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..88655165 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Bastien Chanot + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 00000000..ccad2c57 --- /dev/null +++ b/README.md @@ -0,0 +1,116 @@ +# Osteo Report + +Single-praticien web app for veterinary osteopathy bilans on animal anatomy SVGs — click zones, build observations, export a self-contained PDF with embedded JSON for re-import. + +--- + +## Features + +- **Anatomy canvas** — inline SVG with clickable zones; hitbox+visible twin pattern; delegated click listener +- **Observation builder** — group zones into clinical observations with pathology selection, severity, and free-text notes +- **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 (canvg @ 2×), structured observations, and the full report JSON as a native PDF attachment +- **PDF re-import** — open a previously exported PDF to restore the session for a follow-up +- **Configurable identity** — site name, brand, footer, tagline all come from env vars; nothing hardcoded +- **Practitioner cache** — last-used practitioner block prefilled via localStorage + +--- + +## Stack + +- Node.js 20 +- React 19 + TypeScript 5 (strict) +- Vite 7 + @vitejs/plugin-react-swc +- Tailwind CSS v4 (CSS-first, no postcss config) +- Zustand 5 (state) +- Zod 3 (schema + runtime validation) +- pdf-lib 1.17 (PDF generation + native attachments) +- canvg 4 (SVG → canvas rasterization) +- motion 11 (animations) +- vitest 3 + happy-dom + @testing-library/react + +--- + +## Quick start (dev) + +Single process, no Docker: + +```bash +# Requires pnpm — install if needed: +curl -fsSL https://get.pnpm.io/install.sh | sh +source ~/.bashrc # or restart your shell + +pnpm install +cp .env.example .env # edit APP_* vars if desired +pnpm dev # http://localhost:5173 +``` + +Docker Compose (matches production topology): + +```bash +cp .env.example .env # set APP_* identity vars +docker compose up --build +# app at http://localhost:8080 +``` + +--- + +## Verifying a change + +```bash +pnpm typecheck # TypeScript strict, no emit +pnpm lint # ESLint 9 flat config, 0 warnings +pnpm test:run # vitest run (7 tests pass on skeleton) +pnpm build # tsc + vite build → dist/ +``` + +--- + +## Build & deploy + +```bash +pnpm build # production build → dist/ +docker build -t osteo-report . # multi-stage Docker image +docker compose up --build # run with env_file: .env +``` + +For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy, backups) — see [DEPLOY.md](DEPLOY.md) (to be written post-scaffold). + +--- + +## 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/PDF-FORMAT.md](docs/PDF-FORMAT.md) — PDF page layout and attachment contract +- [.claude/tasks/TODO.md](.claude/tasks/TODO.md) — implementation roadmap + +--- + +## Project layout + +``` +osteo/ +├─ public/species/equine/ anatomy SVGs (Horse.svg, Horse_head.svg) +├─ src/app/ routes + ConfigProvider +├─ src/config/ runtime env config resolution +├─ src/domain/ Zod schemas + species registry + equine data +├─ src/state/ Zustand store + localStorage cache +├─ src/anatomy/ SVG parser + loader +├─ 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 +├─ docker/ entrypoint.sh + nginx.conf +└─ docs/ conventions + species guide + PDF spec +``` + +--- + +## Status + +Pre-1.0 — skeleton complete. MVP feature implementation in progress (see `.claude/tasks/TODO.md`). +License: [MIT](LICENSE). diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..09d8f593 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,10 @@ +services: + app: + build: + context: . + dockerfile: Dockerfile + ports: + - "${PORT:-8080}:${PORT:-8080}" + env_file: + - .env + restart: unless-stopped diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh new file mode 100644 index 00000000..4357ba23 --- /dev/null +++ b/docker/entrypoint.sh @@ -0,0 +1,27 @@ +#!/bin/sh +# Injects runtime env vars into /usr/share/nginx/html/env.js +# which is loaded by index.html before the React bundle. +# Values come from Docker env vars (set via env_file in docker-compose.yml). + +set -e + +ENV_JS="/usr/share/nginx/html/env.js" + +cat > "$ENV_JS" < /tmp/nginx_default.conf +cp /tmp/nginx_default.conf /etc/nginx/conf.d/default.conf + +exec nginx -g "daemon off;" diff --git a/docker/nginx.conf b/docker/nginx.conf new file mode 100644 index 00000000..d3df7789 --- /dev/null +++ b/docker/nginx.conf @@ -0,0 +1,23 @@ +server { + listen ${PORT:-8080}; + server_name _; + + root /usr/share/nginx/html; + index index.html; + + # Serve env.js with no-cache so runtime config is always fresh + location = /env.js { + add_header Cache-Control "no-store, no-cache, must-revalidate"; + try_files $uri =404; + } + + # Assets with long-lived cache (Vite hashes filenames) + location /assets/ { + add_header Cache-Control "public, max-age=31536000, immutable"; + } + + # SPA fallback — serve index.html for all non-file routes + location / { + try_files $uri $uri/ /index.html; + } +} diff --git a/docs/ADDING-A-SPECIES.md b/docs/ADDING-A-SPECIES.md new file mode 100644 index 00000000..2c49f7bf --- /dev/null +++ b/docs/ADDING-A-SPECIES.md @@ -0,0 +1,10 @@ +# Adding a New Species + +Placeholder — to be written when adding the second species post-MVP. + +Steps will cover: +1. Preparing anatomy SVGs per docs/ANATOMY-SVG-CONVENTION.md +2. Creating `src/domain/species//` folder +3. Defining vertebralFormula + pathology DB +4. Registering in `src/domain/species/registry.ts` +5. Testing with convention parser + pathology integrity tests diff --git a/docs/ANATOMY-SVG-CONVENTION.md b/docs/ANATOMY-SVG-CONVENTION.md new file mode 100644 index 00000000..783fd56d --- /dev/null +++ b/docs/ANATOMY-SVG-CONVENTION.md @@ -0,0 +1,172 @@ +# Anatomy SVG Convention + +**Status**: Source of truth. All SVG assets and parser code must conform. + +--- + +## Required data attributes + +Every clickable zone element must carry all four attributes: + +| Attribute | Type | Description | +|---|---|---| +| `data-bone-id` | `string` | Stable kebab-case identifier. Unique per bone. | +| `data-bone-fr` | `string` | French anatomical label (e.g. "Colonne cervicale"). | +| `data-bone-en` | `string` | English anatomical label (e.g. "Cervical spine"). | +| `data-category` | `BoneCategory` | One of the seven valid categories below. | + +## Optional data attributes + +| Attribute | Type | Description | +|---|---|---| +| `data-opens-detail` | `string` | Id of the detail popup SVG to open on click. Key must exist in `SpeciesManifest.details`. | + +--- + +## Valid categories + +| Value | Meaning | +|---|---| +| `articulation` | Joint space | +| `charniere` | Junctional / transitional zone | +| `spine-zone` | Vertebral region bloc — click opens VertebraPicker | +| `os` | Single bone | +| `os-overlay` | Overlapping bone layer | +| `head` | Head region (main SVG entry point for detail popup) | +| `cadran-crane` | Cranial quadrant (inside detail popup) | + +--- + +## Rendering patterns + +### Pattern 1 — Hitbox + visible twin + +Used for: `articulation`, `charniere`, `os-overlay`, `head`. + +Two sibling SVG elements share the **same** `data-bone-id`: + +```xml + + + + + +``` + +- Hitbox must have `class` containing `hitbox` (case-insensitive substring). +- Visible twin must have `class` containing `visible`. +- Order in DOM does not matter — parser groups by `data-bone-id`. + +### Pattern 2 — Single element + +Used for: `spine-zone`, standalone `head` zones inside detail SVGs. + +One polygon carries everything: + +```xml + +``` + +--- + +## Parser behavior (`src/anatomy/svgConvention.ts`) + +1. `parseSvgBones(svgRoot)` — walks all elements with `data-bone-id`. +2. Groups by `data-bone-id` → one `Bone` per id. +3. For each group, validates required attributes. +4. Classifies elements into `hitboxEls` (class contains "hitbox") and `visibleEls` (class contains "visible"). Elements in neither class land in `visibleEls` by default. +5. Returns `Map`. +6. Throws `SvgConventionError(message, boneId, missingAttribute)` on first violation. + +### Validated rules + +- `data-bone-fr` must be non-empty. +- `data-bone-en` must be non-empty. +- `data-category` must be one of the seven valid values. +- If `data-opens-detail` is present, the value must be a non-empty string (runtime check against species manifest happens in the canvas component). + +--- + +## Click handling (delegated listener) + +A single `click` listener on the root `` element: + +``` +event.target → walk up ancestors → find data-bone-id + → if data-opens-detail present → emit requestDetail({id}) + → else if category === 'spine-zone' → open VertebraPicker + → else → add bone to current observation +``` + +Never attach per-element click listeners — the SVG may have thousands of elements. + +--- + +## Zone visual states + +Applied as `data-state` attribute on all elements sharing a `data-bone-id`: + +| `data-state` | Condition | Visual | +|---|---|---| +| `current` | Bone is in the active observation | Solid accent fill | +| `linked` | Bone is in another (non-active) observation | Faded dashed border, accent color of owning obs | +| `multi` | Bone is in ≥2 observations | Striped CSS background pattern + indicator badge | +| *(absent)* | Default / unselected | SVG original fill | + +Accent colors cycle through 6 HSL tones (defined in `src/styles/tokens.css`): +terracotta → sauge → bleu canard → ambre → prune → ocre. + +--- + +## Detail popup mechanism + +When a zone has `data-opens-detail="head"`: + +1. Canvas emits `requestDetail({ id: 'head' })`. +2. `DetailModal` resolves the path via `SpeciesManifest.details['head']`. +3. Loads and renders the detail SVG inline. +4. Clicks inside the modal add `ObservationZone` entries with `detailSourceId: 'head'`. +5. The "entry" zone itself (the polygon that triggered the popup) is **never** persisted. + +--- + +## Vertebra picker trigger + +When a bone has `data-category="spine-zone"`, clicking it opens `VertebraPicker`: + +- Region tabs: Cervicales (C1–C7), Thoraciques (T1–T18), Lombaires (L1–L6), Sacrales (S1–S5), Caudales (Cd1–Cd18). +- Multi-select chip grid, ≥40 px touch targets. +- Per-region "Tout cocher / Tout décocher". +- Stored as `vertebrae: Vertebra[]` on `ObservationZone`, replacing the bloc semantically. +- PDF prints precise vertebrae: "T12, T15" instead of the zone label. + +--- + +## Adding a new SVG + +1. Place SVG at `public/species//.svg`. +2. Ensure every clickable element has the four required attributes. +3. Use Pattern 1 or Pattern 2 consistently per category. +4. Add to `SpeciesManifest.details` if it is a detail popup SVG. +5. Run `pnpm test:run` — the convention parser tests will catch missing attributes. +6. See `docs/ADDING-A-SPECIES.md` for adding a full new species. diff --git a/docs/PDF-FORMAT.md b/docs/PDF-FORMAT.md new file mode 100644 index 00000000..a19a681c --- /dev/null +++ b/docs/PDF-FORMAT.md @@ -0,0 +1,12 @@ +# PDF Format + +Placeholder — to be written when implementing src/pdf/. + +Will cover: +- A4 portrait dimensions (595.28 × 841.89 pt) +- Page layout: header / body / footer zones +- Observation page structure +- Conclusion page structure +- JSON attachment spec (EmbeddedFiles, afRelationship:Data) +- Font embedding (Inter TTF body, Fraunces TTF heading) +- Import/re-import roundtrip contract diff --git a/docs/superpowers/plans/2026-05-18-osteo-report-mvp.md b/docs/superpowers/plans/2026-05-18-osteo-report-mvp.md new file mode 100644 index 00000000..6cbd126f --- /dev/null +++ b/docs/superpowers/plans/2026-05-18-osteo-report-mvp.md @@ -0,0 +1,4269 @@ +# Osteo Report MVP — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Wire the full Osteo Report MVP on top of the scaffold so a praticien can create a clinical report (observations on SVG anatomy + pathologies + severity + conclusion), export it as a self-contained A4 PDF with the JSON state attached, and re-import that PDF to start a follow-up — all in a static React/Vite SPA, served by nginx in Docker, with identity strings driven by env vars. + +**Architecture:** Layered TS modules under `src/`. Schemas (`domain/schema/`) are the contract; Zustand store (`state/reportStore.ts`) owns the in-memory `Report`; anatomy modules (`anatomy/`) parse the SVG convention and the React canvas listens via event delegation; observation/report React components mutate the store; PDF pipeline (`pdf/`) renders pages with canvg-rasterized SVGs and attaches the report JSON via `pdf-lib`'s native embedded-file API. Identity comes from `config/env.ts` at runtime. No backend. + +**Tech Stack:** Vite 7 · React 19 · TypeScript 5 (strict) · Tailwind v4 · Zustand 5 · Zod 3 · pdf-lib 1.17 · canvg 4 · motion 11 · vitest 3 · happy-dom · @testing-library/react · ESLint 9 · Prettier · pnpm 9+ · Node 20 · nginx:alpine. + +**Verification commands (after every task):** +- `pnpm typecheck` clean. +- `pnpm test:run -- ` for the affected file. +- `pnpm test:run` for full suite. +- `pnpm build` before any commit touching build wiring. + +--- + +## Phase 0 — Setup & ergonomics + +### Task 0.1 — Commit-message convention note + +**Files:** +- Modify: `CLAUDE.md` + +- [ ] **Step 1:** Read `CLAUDE.md`. If no "Commit message convention" section, append: + +```markdown +## Commit message convention + +Conventional Commits format. Subject ≤72 chars, imperative mood, no trailing period. +Allowed scopes: `schema`, `store`, `anatomy`, `pdf`, `editor`, `home`, `new`, `ui`, `config`, `species`, `docker`, `docs`, `tests`, `chore`. + +Examples: +- `test(schema): cover Report version literal` +- `feat(store): implement addObservation` +- `feat(anatomy): parse data-bone-id from SVG` +``` + +- [ ] **Step 2:** Commit +```bash +git add CLAUDE.md +git commit -m "docs(chore): document commit message convention" +``` + +### Task 0.2 — Lint + format baseline + +- [ ] **Step 1:** Verify clean +```bash +pnpm lint +pnpm format --check +``` + +- [ ] **Step 2:** No commit if both clean. + +--- + +## Phase 1 — Library utilities + +### Task 1.1 — `formatDateFr` + +**Files:** +- Create: `tests/unit/lib.dates.test.ts` + +- [ ] **Step 1:** Write the failing test +```ts +import { describe, it, expect } from 'vitest' +import { formatDateFr, todayIso, nowIso } from '@/lib/dates' + +describe('formatDateFr', () => { + it('formats an ISO date as "18 mai 2026"', () => { + expect(formatDateFr('2026-05-18')).toBe('18 mai 2026') + }) + + it('formats a leading-zero day correctly', () => { + expect(formatDateFr('2026-01-03')).toBe('3 janvier 2026') + }) + + it('throws on invalid input', () => { + expect(() => formatDateFr('not-a-date')).toThrow() + }) +}) + +describe('todayIso', () => { + it('returns YYYY-MM-DD', () => { + expect(todayIso()).toMatch(/^\d{4}-\d{2}-\d{2}$/) + }) +}) + +describe('nowIso', () => { + it('returns a full ISO instant', () => { + expect(nowIso()).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/) + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL on `formatDateFr` +```bash +pnpm test:run -- tests/unit/lib.dates.test.ts +``` + +- [ ] **Step 3:** Implement `formatDateFr` in `src/lib/dates.ts` +```ts +export function formatDateFr(isoDate: string): string { + const match = isoDate.match(/^(\d{4})-(\d{2})-(\d{2})$/) + if (!match) throw new Error(`Invalid ISO date: ${isoDate}`) + const [, y, mo, d] = match + const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d))) + if (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date: ${isoDate}`) + return new Intl.DateTimeFormat('fr-FR', { + day: 'numeric', + month: 'long', + year: 'numeric', + timeZone: 'UTC', + }).format(date) +} +``` + +- [ ] **Step 4:** Re-run; expect PASS +```bash +pnpm test:run -- tests/unit/lib.dates.test.ts +``` + +- [ ] **Step 5:** Commit +```bash +git add tests/unit/lib.dates.test.ts src/lib/dates.ts +git commit -m "feat(lib): implement formatDateFr (fr-FR locale)" +``` + +### Task 1.2 — Cover `generateId` + +**Files:** +- Create: `tests/unit/lib.id.test.ts` + +- [ ] **Step 1:** Write the test +```ts +import { describe, it, expect } from 'vitest' +import { generateId } from '@/lib/id' + +describe('generateId', () => { + it('returns a non-empty string', () => { + expect(generateId().length).toBeGreaterThan(0) + }) + + it('returns distinct ids on consecutive calls', () => { + const a = generateId() + const b = generateId() + expect(a).not.toBe(b) + }) +}) +``` + +- [ ] **Step 2:** Run; expect PASS +```bash +pnpm test:run -- tests/unit/lib.id.test.ts +``` + +- [ ] **Step 3:** Commit +```bash +git add tests/unit/lib.id.test.ts +git commit -m "test(lib): cover generateId uniqueness" +``` + +--- + +## Phase 2 — Schema coverage + +### Task 2.1 — ObservationSchema + +**Files:** +- Create: `tests/unit/schema.observation.test.ts` + +- [ ] **Step 1:** Write the test +```ts +import { describe, it, expect } from 'vitest' +import { + ObservationSchema, + VertebraSchema, + SeveritySchema, +} from '@/domain/schema/observation' + +describe('SeveritySchema', () => { + it('accepts the three documented values', () => { + expect(SeveritySchema.parse('légère')).toBe('légère') + expect(SeveritySchema.parse('modérée')).toBe('modérée') + expect(SeveritySchema.parse('sévère')).toBe('sévère') + }) + + it('rejects unknown severity', () => { + expect(() => SeveritySchema.parse('critique')).toThrow() + }) +}) + +describe('VertebraSchema', () => { + it('accepts a region+index pair', () => { + expect(VertebraSchema.parse({ region: 'T', index: 12 })).toEqual({ + region: 'T', + index: 12, + }) + }) + + it('rejects index 0', () => { + expect(() => VertebraSchema.parse({ region: 'C', index: 0 })).toThrow() + }) + + it('rejects unknown region', () => { + expect(() => VertebraSchema.parse({ region: 'X', index: 1 })).toThrow() + }) +}) + +describe('ObservationSchema', () => { + const baseObs = { + id: 'obs-1', + zones: [{ boneId: 'epaule' }], + pathologyIds: [], + freeTextPathologies: [], + comment: '', + } + + it('accepts a minimal observation', () => { + expect(() => ObservationSchema.parse(baseObs)).not.toThrow() + }) + + it('accepts a spine-zone observation with precise vertebrae', () => { + const obs = { + ...baseObs, + zones: [ + { + boneId: 'thoracic-vertebrae-spine-zone', + vertebrae: [ + { region: 'T', index: 12 }, + { region: 'T', index: 13 }, + ], + }, + ], + } + expect(() => ObservationSchema.parse(obs)).not.toThrow() + }) + + it('rejects empty id', () => { + expect(() => ObservationSchema.parse({ ...baseObs, id: '' })).toThrow() + }) +}) +``` + +- [ ] **Step 2:** Run; expect PASS +```bash +pnpm test:run -- tests/unit/schema.observation.test.ts +``` + +- [ ] **Step 3:** Commit +```bash +git add tests/unit/schema.observation.test.ts +git commit -m "test(schema): cover ObservationSchema + Vertebra + Severity" +``` + +### Task 2.2 — ReportSchema + +**Files:** +- Create: `tests/unit/schema.report.test.ts` + +- [ ] **Step 1:** Write the test +```ts +import { describe, it, expect } from 'vitest' +import { ReportSchema } from '@/domain/schema/report' + +const minimal = { + version: 1 as const, + id: 'r1', + createdAt: '2026-05-18T10:00:00Z', + date: '2026-05-18', + practitioner: { name: 'Dr. Dupont' }, + animal: { speciesId: 'equine', name: 'Mistral' }, + owner: { name: 'Jean Martin' }, + observations: [], + conclusion: '', + recommendations: '', +} + +describe('ReportSchema', () => { + it('accepts a minimal valid report', () => { + expect(() => ReportSchema.parse(minimal)).not.toThrow() + }) + + it('accepts nextAppointment kind=date', () => { + expect(() => + ReportSchema.parse({ + ...minimal, + nextAppointment: { kind: 'date', date: '2026-06-08' }, + }), + ).not.toThrow() + }) + + it('accepts nextAppointment kind=period', () => { + expect(() => + ReportSchema.parse({ + ...minimal, + nextAppointment: { kind: 'period', text: 'dans 3 semaines' }, + }), + ).not.toThrow() + }) + + it('rejects version !== 1', () => { + expect(() => ReportSchema.parse({ ...minimal, version: 2 })).toThrow() + }) + + it('rejects empty practitioner.name', () => { + expect(() => + ReportSchema.parse({ ...minimal, practitioner: { name: '' } }), + ).toThrow() + }) +}) +``` + +- [ ] **Step 2:** Run; expect PASS +```bash +pnpm test:run -- tests/unit/schema.report.test.ts +``` + +- [ ] **Step 3:** Commit +```bash +git add tests/unit/schema.report.test.ts +git commit -m "test(schema): cover ReportSchema discriminated union + version" +``` + +### Task 2.3 — PathologySchema + +**Files:** +- Create: `tests/unit/schema.pathology.test.ts` + +- [ ] **Step 1:** Write the test +```ts +import { describe, it, expect } from 'vitest' +import { PathologySchema } from '@/domain/schema/pathology' + +describe('PathologySchema', () => { + const base = { + id: 'desmite-suspenseur', + labelFr: 'Desmite du ligament suspenseur', + description: 'Inflammation du ligament suspenseur du boulet.', + category: 'tendino-ligamentaire' as const, + speciesIds: ['equine'], + boneIds: ['boulet-ant', 'boulet-post'], + sources: [ + { type: 'manual' as const, citation: 'Merck Vet Manual (2024).' }, + ], + } + + it('accepts a valid entry', () => { + expect(() => PathologySchema.parse(base)).not.toThrow() + }) + + it('rejects zero sources', () => { + expect(() => PathologySchema.parse({ ...base, sources: [] })).toThrow() + }) + + it('rejects empty id', () => { + expect(() => PathologySchema.parse({ ...base, id: '' })).toThrow() + }) + + it('rejects non-URL urls', () => { + expect(() => + PathologySchema.parse({ + ...base, + sources: [{ type: 'web', citation: 'X', url: 'not-a-url' }], + }), + ).toThrow() + }) +}) +``` + +- [ ] **Step 2:** Run; expect PASS +```bash +pnpm test:run -- tests/unit/schema.pathology.test.ts +``` + +- [ ] **Step 3:** Commit +```bash +git add tests/unit/schema.pathology.test.ts +git commit -m "test(schema): enforce >=1 source + url validation on Pathology" +``` + +--- + +## Phase 3 — Species registry + +### Task 3.1 — Registry lookup + +**Files:** +- Create: `tests/unit/species.registry.test.ts` + +- [ ] **Step 1:** Write the test +```ts +import { describe, it, expect } from 'vitest' +import { getSpecies, getAllSpecies } from '@/domain/species/registry' + +describe('species registry', () => { + it('returns the equine manifest', () => { + const eq = getSpecies('equine') + expect(eq).toBeDefined() + expect(eq?.labelFr).toBe('Cheval') + expect(eq?.mainSvg).toBe('/species/equine/Horse.svg') + expect(eq?.details.head).toBe('/species/equine/Horse_head.svg') + expect(eq?.vertebralFormula).toEqual({ C: 7, T: 18, L: 6, S: 5, Cd: 18 }) + }) + + it('returns undefined for unknown species', () => { + expect(getSpecies('martian')).toBeUndefined() + }) + + it('lists at least the equine species', () => { + const all = getAllSpecies() + expect(all.length).toBeGreaterThanOrEqual(1) + expect(all.find((s) => s.id === 'equine')).toBeDefined() + }) +}) +``` + +- [ ] **Step 2:** Run; expect PASS +```bash +pnpm test:run -- tests/unit/species.registry.test.ts +``` + +- [ ] **Step 3:** Commit +```bash +git add tests/unit/species.registry.test.ts +git commit -m "test(species): cover registry lookup + equine manifest" +``` + +--- + +## Phase 4 — SVG convention parser + +### Task 4.1 — Synthetic SVG tests + parser impl + +**Files:** +- Create: `tests/unit/anatomy.svgConvention.test.ts` + +- [ ] **Step 1:** Test +```ts +import { describe, it, expect } from 'vitest' +import { + parseSvgBones, + getBoneIdFromEvent, + isValidCategory, +} from '@/anatomy/svgConvention' +import { SvgConventionError } from '@/anatomy/types' + +function svgFromString(s: string): SVGSVGElement { + const doc = new DOMParser().parseFromString(s, 'image/svg+xml') + return doc.documentElement as unknown as SVGSVGElement +} + +const FIXTURE = ` + + + + + +` + +describe('parseSvgBones', () => { + it('groups hitbox + visible by data-bone-id', () => { + const map = parseSvgBones(svgFromString(FIXTURE)) + const epaule = map.get('epaule') + expect(epaule).toBeDefined() + expect(epaule?.fr).toBe('Épaule') + expect(epaule?.category).toBe('articulation') + expect(epaule?.hitboxEls.length).toBe(1) + expect(epaule?.visibleEls.length).toBe(1) + }) + + it('captures opensDetail when present', () => { + const map = parseSvgBones(svgFromString(FIXTURE)) + expect(map.get('zone-head')?.opensDetail).toBe('head') + }) + + it('records spine-zone single-element bones', () => { + const map = parseSvgBones(svgFromString(FIXTURE)) + const bone = map.get('cervical-vertebrae-spine-zone') + expect(bone?.category).toBe('spine-zone') + }) +}) + +describe('parseSvgBones validation', () => { + it('throws on missing data-bone-fr', () => { + const bad = ` + + ` + expect(() => parseSvgBones(svgFromString(bad))).toThrow(SvgConventionError) + }) + + it('throws on unknown category', () => { + const bad = ` + + ` + expect(() => parseSvgBones(svgFromString(bad))).toThrow(SvgConventionError) + }) +}) + +describe('isValidCategory', () => { + it('accepts documented categories', () => { + expect(isValidCategory('articulation')).toBe(true) + expect(isValidCategory('spine-zone')).toBe(true) + expect(isValidCategory('cadran-crane')).toBe(true) + }) + + it('rejects unknown values', () => { + expect(isValidCategory('nope')).toBe(false) + }) +}) + +describe('getBoneIdFromEvent', () => { + it('returns null when no bone in ancestry', () => { + const div = document.createElement('div') + const evt = new Event('click') + Object.defineProperty(evt, 'target', { value: div }) + expect(getBoneIdFromEvent(evt)).toBeNull() + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL +```bash +pnpm test:run -- tests/unit/anatomy.svgConvention.test.ts +``` + +- [ ] **Step 3:** Implement `src/anatomy/svgConvention.ts` +```ts +import { SvgConventionError } from './types' +import type { Bone, BoneCategory } from './types' + +const VALID_CATEGORIES: readonly BoneCategory[] = [ + 'articulation', + 'charniere', + 'spine-zone', + 'os', + 'os-overlay', + 'head', + 'cadran-crane', +] + +export function isValidCategory(value: string): value is BoneCategory { + return (VALID_CATEGORIES as readonly string[]).includes(value) +} + +function classList(el: Element): string[] { + return (el.getAttribute('class') ?? '').split(/\s+/).filter(Boolean) +} + +export function validateBoneElement(el: Element): void { + const boneId = el.getAttribute('data-bone-id') ?? '' + for (const attr of ['data-bone-fr', 'data-bone-en', 'data-category']) { + if (!el.getAttribute(attr)) { + throw new SvgConventionError( + `Element data-bone-id="${boneId}" missing attribute ${attr}`, + boneId, + attr, + ) + } + } + const cat = el.getAttribute('data-category') ?? '' + if (!isValidCategory(cat)) { + throw new SvgConventionError( + `Element data-bone-id="${boneId}" has unknown data-category="${cat}"`, + boneId, + 'data-category', + ) + } +} + +export function parseSvgBones(svgRoot: SVGSVGElement): Map { + const map = new Map() + const all = svgRoot.querySelectorAll('[data-bone-id]') + all.forEach((el) => { + validateBoneElement(el) + const id = el.getAttribute('data-bone-id') as string + const fr = el.getAttribute('data-bone-fr') as string + const en = el.getAttribute('data-bone-en') as string + const category = el.getAttribute('data-category') as BoneCategory + const opensDetail = el.getAttribute('data-opens-detail') ?? undefined + const classes = classList(el) + const isHitbox = classes.includes('hitbox') + + const existing = map.get(id) + if (existing) { + if (isHitbox) existing.hitboxEls.push(el) + else existing.visibleEls.push(el) + if (opensDetail && !existing.opensDetail) existing.opensDetail = opensDetail + } else { + map.set(id, { + id, + fr, + en, + category, + opensDetail, + hitboxEls: isHitbox ? [el] : [], + visibleEls: isHitbox ? [] : [el], + }) + } + }) + return map +} + +export function getBoneIdFromEvent(event: Event): string | null { + let node = event.target as Element | null + while (node && node.nodeType === 1) { + const id = node.getAttribute?.('data-bone-id') + if (id) return id + node = node.parentElement + } + return null +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add tests/unit/anatomy.svgConvention.test.ts src/anatomy/svgConvention.ts +git commit -m "feat(anatomy): parse SVG convention into Bone map with validation" +``` + +### Task 4.2 — Real Horse.svg + +**Files:** +- Create: `tests/unit/anatomy.horse.test.ts` + +- [ ] **Step 1:** Test (use `import.meta.url` — `__dirname` is undefined under Vitest ESM) +```ts +import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +import { parseSvgBones } from '@/anatomy/svgConvention' + +const HORSE_PATH = fileURLToPath(new URL('../../public/species/equine/Horse.svg', import.meta.url)) +const HEAD_PATH = fileURLToPath(new URL('../../public/species/equine/Horse_head.svg', import.meta.url)) + +function loadSvg(path: string): SVGSVGElement { + const raw = readFileSync(path, 'utf8') + const doc = new DOMParser().parseFromString(raw, 'image/svg+xml') + return doc.documentElement as unknown as SVGSVGElement +} + +describe('real Horse.svg', () => { + const map = parseSvgBones(loadSvg(HORSE_PATH)) + + it('parses without throwing', () => { + expect(map.size).toBeGreaterThan(10) + }) + + it('contains all 5 spine-zone bones', () => { + const spine = [...map.values()].filter((b) => b.category === 'spine-zone') + expect(spine.length).toBe(5) + }) + + it('contains the head zone with opensDetail=head', () => { + const head = [...map.values()].find((b) => b.category === 'head') + expect(head?.opensDetail).toBe('head') + }) + + it('contains the 3 vertebral hinges', () => { + const charn = [...map.values()].filter((b) => b.category === 'charniere') + expect(charn.map((b) => b.id).sort()).toEqual(['c7-t1', 'l6-s1', 't18-l1']) + }) + + it('contains main joint articulations', () => { + for (const id of ['epaule', 'coude', 'hanche', 'grasset', 'jarret']) { + expect(map.get(id)?.category).toBe('articulation') + } + }) +}) + +describe('real Horse_head.svg', () => { + const map = parseSvgBones(loadSvg(HEAD_PATH)) + + it('parses without throwing', () => { + expect(map.size).toBeGreaterThan(5) + }) + + it('contains cadran-crane categories', () => { + const cadran = [...map.values()].filter((b) => b.category === 'cadran-crane') + expect(cadran.length).toBeGreaterThan(0) + }) +}) +``` + +- [ ] **Step 2:** Run; expect PASS + +- [ ] **Step 3:** Commit +```bash +git add tests/unit/anatomy.horse.test.ts +git commit -m "test(anatomy): cover real Horse.svg + Horse_head.svg parsing" +``` + +### Task 4.3 — `loadSvg` + +**Files:** +- Modify: `src/anatomy/svgLoader.ts` +- Create: `tests/unit/anatomy.svgLoader.test.ts` + +- [ ] **Step 1:** Test +```ts +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { loadSvg } from '@/anatomy/svgLoader' + +const SVG = '' + +describe('loadSvg', () => { + beforeEach(() => { + vi.stubGlobal('fetch', vi.fn(async () => ({ + ok: true, + text: async () => SVG, + })) as unknown as typeof fetch) + }) + + it('returns an SVGSVGElement', async () => { + const root = await loadSvg('/whatever.svg') + expect(root.tagName.toLowerCase()).toBe('svg') + }) + + it('throws on non-ok response', async () => { + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404, text: async () => '' })) as unknown as typeof fetch) + await expect(loadSvg('/missing.svg')).rejects.toThrow() + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Implement +```ts +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 +} + +export async function svgToPngDataUrl( + _svgEl: SVGSVGElement, + _scale: number, +): Promise { + throw new Error('not implemented') +} +``` + +- [ ] **Step 4:** Re-run; expect PASS +```bash +pnpm test:run -- tests/unit/anatomy.svgLoader.test.ts +``` + +- [ ] **Step 5:** Commit +```bash +git add tests/unit/anatomy.svgLoader.test.ts src/anatomy/svgLoader.ts +git commit -m "feat(anatomy): implement loadSvg via fetch + DOMParser" +``` + +--- + +## Phase 5 — Zustand store + +### Task 5.1 — initReport + reset + +**Files:** +- Create: `tests/unit/state.reportStore.test.ts` + +- [ ] **Step 1:** Test +```ts +import { describe, it, expect, beforeEach } from 'vitest' +import { useReportStore } from '@/state/reportStore' + +const draft = { + date: '2026-05-18', + practitioner: { name: 'Dr. Dupont' }, + animal: { speciesId: 'equine', name: 'Mistral' }, + owner: { name: 'Jean Martin' }, + observations: [], + conclusion: '', + recommendations: '', +} + +beforeEach(() => { + useReportStore.getState().reset() +}) + +describe('reportStore.initReport', () => { + it('sets a report with version=1, id, and createdAt', () => { + useReportStore.getState().initReport(draft) + const r = useReportStore.getState().report! + expect(r.version).toBe(1) + expect(r.id.length).toBeGreaterThan(0) + expect(r.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/) + expect(r.practitioner.name).toBe('Dr. Dupont') + }) + + it('resets activeObservationIndex to 0', () => { + useReportStore.getState().initReport(draft) + expect(useReportStore.getState().activeObservationIndex).toBe(0) + }) +}) + +describe('reportStore.reset', () => { + it('clears the report', () => { + useReportStore.getState().initReport(draft) + useReportStore.getState().reset() + expect(useReportStore.getState().report).toBeNull() + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL +```bash +pnpm test:run -- tests/unit/state.reportStore.test.ts +``` + +- [ ] **Step 3:** Implement (replace stubs in `src/state/reportStore.ts`) +```ts +import { create } from 'zustand' +import type { Report } from '@/domain/schema/report' +import type { Observation } from '@/domain/schema/observation' +import { generateId } from '@/lib/id' +import { nowIso } from '@/lib/dates' + +export interface ReportStore { + report: Report | null + activeObservationIndex: number + initReport: (draft: Omit) => void + hydrateReport: (report: Report) => void + addObservation: () => void + removeObservation: (index: number) => void + moveObservationUp: (index: number) => void + moveObservationDown: (index: number) => void + updateObservation: (index: number, obs: Observation) => void + setActiveObservation: (index: number) => void + setConclusion: (text: string) => void + setRecommendations: (text: string) => void + setNextAppointment: (next: Report['nextAppointment']) => void + reset: () => void +} + +function emptyObservation(): Observation { + return { + id: generateId(), + zones: [], + pathologyIds: [], + freeTextPathologies: [], + comment: '', + } +} + +export const useReportStore = create((set) => ({ + report: null, + activeObservationIndex: 0, + + initReport: (draft) => + set({ + report: { ...draft, version: 1, id: generateId(), createdAt: nowIso() }, + activeObservationIndex: 0, + }), + + hydrateReport: (report) => set({ report, activeObservationIndex: 0 }), + + addObservation: () => + set((s) => { + if (!s.report) return s + const obs = emptyObservation() + const observations = [...s.report.observations, obs] + return { + report: { ...s.report, observations }, + activeObservationIndex: observations.length - 1, + } + }), + + removeObservation: (index) => + set((s) => { + if (!s.report) return s + const observations = s.report.observations.filter((_, i) => i !== index) + const active = Math.min( + s.activeObservationIndex, + Math.max(0, observations.length - 1), + ) + return { + report: { ...s.report, observations }, + activeObservationIndex: active, + } + }), + + moveObservationUp: (index) => + set((s) => { + if (!s.report || index <= 0) return s + const observations = [...s.report.observations] + ;[observations[index - 1], observations[index]] = [ + observations[index], + observations[index - 1], + ] + return { report: { ...s.report, observations } } + }), + + moveObservationDown: (index) => + set((s) => { + if (!s.report || index >= s.report.observations.length - 1) return s + const observations = [...s.report.observations] + ;[observations[index], observations[index + 1]] = [ + observations[index + 1], + observations[index], + ] + return { report: { ...s.report, observations } } + }), + + updateObservation: (index, obs) => + set((s) => { + if (!s.report) return s + const observations = s.report.observations.map((o, i) => + i === index ? obs : o, + ) + return { report: { ...s.report, observations } } + }), + + setActiveObservation: (index) => set({ activeObservationIndex: index }), + + setConclusion: (text) => + set((s) => (s.report ? { report: { ...s.report, conclusion: text } } : s)), + + setRecommendations: (text) => + set((s) => + s.report ? { report: { ...s.report, recommendations: text } } : s, + ), + + setNextAppointment: (next) => + set((s) => + s.report ? { report: { ...s.report, nextAppointment: next } } : s, + ), + + reset: () => set({ report: null, activeObservationIndex: 0 }), +})) +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add tests/unit/state.reportStore.test.ts src/state/reportStore.ts +git commit -m "feat(store): implement initReport / reset / hydrateReport" +``` + +### Task 5.2 — Observation CRUD coverage + +**Files:** +- Modify: `tests/unit/state.reportStore.test.ts` + +- [ ] **Step 1:** Append +```ts +describe('reportStore.addObservation', () => { + it('appends an empty observation and sets it active', () => { + useReportStore.getState().initReport(draft) + useReportStore.getState().addObservation() + const s = useReportStore.getState() + expect(s.report!.observations.length).toBe(1) + expect(s.activeObservationIndex).toBe(0) + }) +}) + +describe('reportStore.updateObservation', () => { + it('replaces the observation at the given index', () => { + useReportStore.getState().initReport(draft) + useReportStore.getState().addObservation() + const next = { + ...useReportStore.getState().report!.observations[0], + comment: 'patate', + } + useReportStore.getState().updateObservation(0, next) + expect(useReportStore.getState().report!.observations[0].comment).toBe('patate') + }) +}) + +describe('reportStore.removeObservation', () => { + it('drops the observation at the given index', () => { + const store = useReportStore.getState() + store.initReport(draft) + store.addObservation() + store.addObservation() + store.removeObservation(0) + expect(useReportStore.getState().report!.observations.length).toBe(1) + }) + + it('clamps activeObservationIndex within bounds', () => { + const store = useReportStore.getState() + store.initReport(draft) + store.addObservation() + store.addObservation() + store.setActiveObservation(1) + store.removeObservation(1) + expect(useReportStore.getState().activeObservationIndex).toBe(0) + }) +}) + +describe('reportStore.move up/down', () => { + it('moveObservationUp swaps with previous', () => { + const s = useReportStore.getState() + s.initReport(draft) + s.addObservation() + s.addObservation() + const idA = useReportStore.getState().report!.observations[0].id + const idB = useReportStore.getState().report!.observations[1].id + s.moveObservationUp(1) + const after = useReportStore.getState().report!.observations + expect(after[0].id).toBe(idB) + expect(after[1].id).toBe(idA) + }) + + it('moveObservationDown swaps with next', () => { + const s = useReportStore.getState() + s.initReport(draft) + s.addObservation() + s.addObservation() + const idA = useReportStore.getState().report!.observations[0].id + const idB = useReportStore.getState().report!.observations[1].id + s.moveObservationDown(0) + const after = useReportStore.getState().report!.observations + expect(after[0].id).toBe(idB) + expect(after[1].id).toBe(idA) + }) +}) +``` + +- [ ] **Step 2:** Run; expect PASS + +- [ ] **Step 3:** Commit +```bash +git add tests/unit/state.reportStore.test.ts +git commit -m "test(store): cover observation CRUD + reorder" +``` + +### Task 5.3 — sessionStorage mirror + +**Files:** +- Modify: `src/state/reportStore.ts` +- Create: `tests/unit/state.draftMirror.test.ts` + +- [ ] **Step 1:** Test +```ts +import { describe, it, expect, beforeEach } from 'vitest' +import { useReportStore } from '@/state/reportStore' + +const STORAGE_KEY = 'osteo:draft' + +const draft = { + date: '2026-05-18', + practitioner: { name: 'Dr. Dupont' }, + animal: { speciesId: 'equine', name: 'Mistral' }, + owner: { name: 'Jean Martin' }, + observations: [], + conclusion: '', + recommendations: '', +} + +beforeEach(() => { + useReportStore.getState().reset() + sessionStorage.clear() +}) + +describe('reportStore sessionStorage mirror', () => { + it('mirrors the report on every change', () => { + useReportStore.getState().initReport(draft) + const raw = sessionStorage.getItem(STORAGE_KEY) + expect(raw).not.toBeNull() + const parsed = JSON.parse(raw!) + expect(parsed.practitioner.name).toBe('Dr. Dupont') + }) + + it('clears the mirror on reset', () => { + useReportStore.getState().initReport(draft) + useReportStore.getState().reset() + expect(sessionStorage.getItem(STORAGE_KEY)).toBeNull() + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Append to `src/state/reportStore.ts` +```ts +const DRAFT_KEY = 'osteo:draft' + +useReportStore.subscribe((state) => { + if (typeof sessionStorage === 'undefined') return + if (state.report) { + sessionStorage.setItem(DRAFT_KEY, JSON.stringify(state.report)) + } else { + sessionStorage.removeItem(DRAFT_KEY) + } +}) + +export function readPersistedDraft(): Report | null { + if (typeof sessionStorage === 'undefined') return null + const raw = sessionStorage.getItem(DRAFT_KEY) + if (!raw) return null + try { + return JSON.parse(raw) as Report + } catch { + return null + } +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add src/state/reportStore.ts tests/unit/state.draftMirror.test.ts +git commit -m "feat(store): mirror current report to sessionStorage" +``` + +--- + +## Phase 6 — Practitioner cache + +### Task 6.1 — read / write / clear + +**Files:** +- Create: `tests/unit/state.practitionerCache.test.ts` + +- [ ] **Step 1:** Test +```ts +import { describe, it, expect, beforeEach } from 'vitest' +import { + readCachedPractitioner, + writeCachedPractitioner, + clearPractitionerCache, +} from '@/state/practitionerCache' + +beforeEach(() => localStorage.clear()) + +describe('practitionerCache', () => { + it('returns undefined when empty', () => { + expect(readCachedPractitioner()).toBeUndefined() + }) + + it('round-trips a valid practitioner', () => { + writeCachedPractitioner({ name: 'Dr. Dupont', cabinet: 'Clinic A' }) + expect(readCachedPractitioner()).toEqual({ + name: 'Dr. Dupont', + cabinet: 'Clinic A', + }) + }) + + it('returns undefined on malformed JSON', () => { + localStorage.setItem('osteo:lastPractitioner', 'not-json') + expect(readCachedPractitioner()).toBeUndefined() + }) + + it('clear removes the entry', () => { + writeCachedPractitioner({ name: 'Dr. Dupont' }) + clearPractitionerCache() + expect(readCachedPractitioner()).toBeUndefined() + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Implement `src/state/practitionerCache.ts` +```ts +import { + PractitionerSchema, + type Practitioner, +} from '@/domain/schema/practitioner' + +const STORAGE_KEY = 'osteo:lastPractitioner' + +export function readCachedPractitioner(): Practitioner | undefined { + if (typeof localStorage === 'undefined') return undefined + const raw = localStorage.getItem(STORAGE_KEY) + if (!raw) return undefined + try { + const data = JSON.parse(raw) + const parsed = PractitionerSchema.safeParse(data) + return parsed.success ? parsed.data : undefined + } catch { + return undefined + } +} + +export function writeCachedPractitioner(practitioner: Practitioner): void { + if (typeof localStorage === 'undefined') return + localStorage.setItem(STORAGE_KEY, JSON.stringify(practitioner)) +} + +export function clearPractitionerCache(): void { + if (typeof localStorage === 'undefined') return + localStorage.removeItem(STORAGE_KEY) +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add tests/unit/state.practitionerCache.test.ts src/state/practitionerCache.ts +git commit -m "feat(state): implement practitioner localStorage cache" +``` + +--- + +## Phase 7 — UI primitives + +### Task 7.1 — Button + +**Files:** +- Modify: `src/components/ui/Button.tsx` +- Create: `tests/unit/ui.Button.test.tsx` + +- [ ] **Step 1:** Test +```tsx +import { describe, it, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import Button from '@/components/ui/Button' + +describe('Button', () => { + it('renders children and handles clicks', async () => { + const onClick = vi.fn() + render() + await userEvent.click(screen.getByRole('button', { name: 'Save' })) + expect(onClick).toHaveBeenCalledOnce() + }) + + it('respects disabled', () => { + render() + expect(screen.getByRole('button')).toBeDisabled() + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Implement `src/components/ui/Button.tsx` +```tsx +import type { ButtonHTMLAttributes, ReactNode } from 'react' + +export interface ButtonProps extends ButtonHTMLAttributes { + variant?: 'primary' | 'secondary' | 'ghost' | 'danger' + size?: 'sm' | 'md' | 'lg' + children?: ReactNode +} + +const VARIANTS: Record, string> = { + primary: + 'bg-[var(--color-accent)] text-white hover:bg-[var(--color-accent-strong)] focus-visible:ring-[var(--color-accent)]', + secondary: + 'bg-[var(--color-surface)] text-[var(--color-ink)] border border-[var(--color-border)] hover:bg-[var(--color-surface-strong)]', + ghost: + 'bg-transparent text-[var(--color-ink)] hover:bg-[var(--color-surface)]', + danger: + 'bg-[var(--color-danger)] text-white hover:bg-[var(--color-danger-strong)]', +} + +const SIZES: Record, string> = { + sm: 'h-8 px-3 text-sm rounded-md', + md: 'h-10 px-4 text-base rounded-lg', + lg: 'h-12 px-6 text-base rounded-lg', +} + +export default function Button({ + variant = 'primary', + size = 'md', + className = '', + children, + ...rest +}: ButtonProps) { + return ( + + ) +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add src/components/ui/Button.tsx tests/unit/ui.Button.test.tsx +git commit -m "feat(ui): Button with variants + sizes + disabled state" +``` + +### Task 7.2 — Card, Input, Label, Textarea, Select, Badge, Chip + +Each follows the same pattern (replace placeholder, no test). Implement per spec then commit each separately. + +`Card.tsx`: +```tsx +import type { ReactNode } from 'react' + +export interface CardProps { + children: ReactNode + className?: string + as?: 'div' | 'section' | 'article' +} + +export default function Card({ children, className = '', as: Tag = 'div' }: CardProps) { + return ( + + {children} + + ) +} +``` + +`Input.tsx`: +```tsx +import { forwardRef, type InputHTMLAttributes } from 'react' + +const Input = forwardRef>( + ({ className = '', ...rest }, ref) => ( + + ), +) +Input.displayName = 'Input' +export default Input +``` + +`Label.tsx`: +```tsx +import type { LabelHTMLAttributes, ReactNode } from 'react' + +export default function Label({ + children, + className = '', + ...rest +}: LabelHTMLAttributes & { children: ReactNode }) { + return ( + + ) +} +``` + +`Textarea.tsx`: +```tsx +import { forwardRef, type TextareaHTMLAttributes } from 'react' + +const Textarea = forwardRef>( + ({ className = '', ...rest }, ref) => ( + + ), +) +Textarea.displayName = 'Textarea' +export default Textarea +``` + +`Select.tsx`: +```tsx +import { forwardRef, type SelectHTMLAttributes } from 'react' + +const Select = forwardRef>( + ({ className = '', children, ...rest }, ref) => ( + + ), +) +Select.displayName = 'Select' +export default Select +``` + +`Badge.tsx`: +```tsx +import type { ReactNode } from 'react' + +export default function Badge({ + children, + tone = 'neutral', + className = '', +}: { + children: ReactNode + tone?: 'neutral' | 'accent' | 'warn' | 'danger' + className?: string +}) { + const map = { + neutral: 'bg-[var(--color-surface-strong)] text-[var(--color-ink)]', + accent: 'bg-[var(--color-accent)]/10 text-[var(--color-accent-strong)]', + warn: 'bg-amber-50 text-amber-700', + danger: 'bg-red-50 text-red-700', + } as const + return ( + + {children} + + ) +} +``` + +`Chip.tsx`: +```tsx +import type { ButtonHTMLAttributes, ReactNode } from 'react' + +export default function Chip({ + active = false, + children, + className = '', + ...rest +}: ButtonHTMLAttributes & { active?: boolean; children: ReactNode }) { + return ( + + ) +} +``` + +- [ ] **Commit each primitive separately** +```bash +git add src/components/ui/Card.tsx && git commit -m "feat(ui): Card" +git add src/components/ui/Input.tsx && git commit -m "feat(ui): Input" +git add src/components/ui/Label.tsx && git commit -m "feat(ui): Label" +git add src/components/ui/Textarea.tsx && git commit -m "feat(ui): Textarea" +git add src/components/ui/Select.tsx && git commit -m "feat(ui): Select" +git add src/components/ui/Badge.tsx && git commit -m "feat(ui): Badge with tones" +git add src/components/ui/Chip.tsx && git commit -m "feat(ui): Chip toggle" +``` + +### Task 7.3 — Dialog + +**Files:** +- Modify: `src/components/ui/Dialog.tsx` +- Create: `tests/unit/ui.Dialog.test.tsx` + +- [ ] **Step 1:** Test +```tsx +import { describe, it, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import Dialog from '@/components/ui/Dialog' + +describe('Dialog', () => { + it('renders nothing when open=false', () => { + render( + {}} title="X"> + body + , + ) + expect(screen.queryByText('body')).toBeNull() + }) + + it('renders content when open=true', () => { + render( + {}} title="X"> + body + , + ) + expect(screen.getByText('body')).toBeInTheDocument() + }) + + it('calls onClose on backdrop click', async () => { + const onClose = vi.fn() + render( + + body + , + ) + await userEvent.click(screen.getByTestId('dialog-backdrop')) + expect(onClose).toHaveBeenCalled() + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Implement +```tsx +import { useEffect, type ReactNode } from 'react' +import { AnimatePresence, motion } from 'motion/react' + +export interface DialogProps { + open: boolean + onClose: () => void + title: string + children: ReactNode + size?: 'sm' | 'md' | 'lg' | 'xl' +} + +const SIZE: Record, string> = { + sm: 'max-w-sm', + md: 'max-w-md', + lg: 'max-w-2xl', + xl: 'max-w-4xl', +} + +export default function Dialog({ open, onClose, title, children, size = 'md' }: DialogProps) { + useEffect(() => { + if (!open) return + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [open, onClose]) + + return ( + + {open && ( +
+ + +
+

{title}

+ +
+
{children}
+
+
+ )} +
+ ) +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add src/components/ui/Dialog.tsx tests/unit/ui.Dialog.test.tsx +git commit -m "feat(ui): Dialog with backdrop + escape + motion fade" +``` + +### Task 7.4 — Toast (deferred — DROPPED FROM v1) + +> Plan-review decision: Toast is unused in v1. HomeRoute renders import errors +> inline (`

`). Skip this task. Leave the +> placeholder file as-is; do not implement. Re-introduce in v1.1 when +> notifications grow beyond one inline error. + +--- + +## Phase 8 — Design tokens + canvas state styling + +### Task 8.1 — Tokens + svg-canvas rules + +**Files:** +- Modify: `src/styles/tokens.css` +- Modify: `src/styles/index.css` + +- [ ] **Step 1:** `src/styles/tokens.css` +```css +:root { + --color-bg: #fbf9f5; + --color-surface: #ffffff; + --color-surface-strong: #f4efe6; + --color-ink: #1f1b16; + --color-ink-muted: #6b6359; + --color-border: #e7e0d2; + + --color-accent: #b85a3f; + --color-accent-strong: #9c4831; + --color-danger: #c0392b; + --color-danger-strong: #962c21; + + --obs-accent-0: #b85a3f; + --obs-accent-1: #6b8e6b; + --obs-accent-2: #3f7d8c; + --obs-accent-3: #b88a3f; + --obs-accent-4: #7a3f7d; + --obs-accent-5: #8a6b3f; + + --severity-mild: #6b8e6b; + --severity-moderate: #b88a3f; + --severity-severe: #c0392b; + + --font-sans: 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif; + --font-serif: 'Fraunces', 'Iowan Old Style', Georgia, serif; +} +``` + +- [ ] **Step 2:** `src/styles/index.css` +```css +@import 'tailwindcss'; +@import './tokens.css'; + +html, body, #root { height: 100%; } +body { + background: var(--color-bg); + color: var(--color-ink); + font-family: var(--font-sans); + -webkit-font-smoothing: antialiased; +} + +.svg-canvas [data-state='current'] { fill: var(--color-accent) !important; fill-opacity: 0.85 !important; } +.svg-canvas [data-state='linked'] { stroke-dasharray: 4 3; stroke: var(--color-accent); fill-opacity: 0.35 !important; } +.svg-canvas [data-state='multi'] { fill: var(--color-accent) !important; fill-opacity: 0.65 !important; stroke: var(--color-ink); stroke-width: 1.5; } +.svg-canvas [data-bone-id] { cursor: pointer; } +.svg-canvas [data-bone-id]:hover { filter: brightness(1.05); } +``` + +- [ ] **Step 3:** Verify build +```bash +pnpm build +``` + +- [ ] **Step 4:** Commit +```bash +git add src/styles/tokens.css src/styles/index.css +git commit -m "feat(styles): design tokens + svg-canvas state rules" +``` + +--- + +## Phase 9 — Brand component + +### Task 9.1 — Brand renders config + +**Files:** +- Modify: `src/components/brand/Brand.tsx` +- Create: `tests/unit/components.Brand.test.tsx` + +- [ ] **Step 1:** Test +```tsx +import { describe, it, expect } from 'vitest' +import { render, screen } from '@testing-library/react' +import { ConfigProvider } from '@/app/providers/ConfigProvider' +import Brand from '@/components/brand/Brand' + +describe('Brand', () => { + it('renders the brand name from config', () => { + render( + + + , + ) + expect(screen.getByText(/Osteo Report/i)).toBeInTheDocument() + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Implement `src/components/brand/Brand.tsx` +```tsx +import { useConfig } from '@/app/providers/ConfigProvider' + +export default function Brand({ size = 'md' }: { size?: 'sm' | 'md' | 'lg' }) { + const cfg = useConfig() + const cls = size === 'lg' ? 'text-3xl' : size === 'sm' ? 'text-base' : 'text-xl' + return ( + + {cfg.brandName} + + ) +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add src/components/brand/Brand.tsx tests/unit/components.Brand.test.tsx +git commit -m "feat(brand): render brandName from runtime config" +``` + +--- + +## Phase 10 — Anatomy canvas + +### Task 10.1 — AnatomyCanvas + +**Files:** +- Modify: `src/components/canvas/AnatomyCanvas.tsx` +- Create: `tests/unit/components.AnatomyCanvas.test.tsx` + +- [ ] **Step 1:** Test +```tsx +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, waitFor } from '@testing-library/react' +import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' + +vi.mock('@/anatomy/svgLoader', () => ({ + loadSvg: vi.fn(async () => { + const doc = new DOMParser().parseFromString( + ` + + + `, + 'image/svg+xml', + ) + return doc.documentElement as unknown as SVGSVGElement + }), +})) + +beforeEach(() => vi.clearAllMocks()) + +describe('AnatomyCanvas', () => { + it('renders the loaded SVG inline', async () => { + render( {}} />) + await waitFor(() => + expect(document.querySelector('[data-bone-id="epaule"]')).not.toBeNull(), + ) + }) + + it('calls onZoneClick with the clicked bone id', async () => { + const onZoneClick = vi.fn() + render() + await waitFor(() => screen.getByTestId('anatomy-canvas')) + ;(document.querySelector('[data-bone-id="epaule"]') as Element).dispatchEvent( + new Event('click', { bubbles: true }), + ) + await waitFor(() => expect(onZoneClick).toHaveBeenCalledWith('epaule')) + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Implement `src/components/canvas/AnatomyCanvas.tsx`. Use `replaceChildren()` to clear the host element — never assign to `innerHTML`. +```tsx +import { useEffect, useRef } from 'react' +import { loadSvg } from '@/anatomy/svgLoader' +import { getBoneIdFromEvent } from '@/anatomy/svgConvention' +import type { BoneState } from '@/anatomy/types' + +export interface AnatomyCanvasProps { + src: string + boneStates: Map + onZoneClick: (boneId: string) => void + className?: string +} + +export default function AnatomyCanvas({ + src, + boneStates, + onZoneClick, + className = '', +}: AnatomyCanvasProps) { + const containerRef = useRef(null) + + useEffect(() => { + let cancelled = false + const c = containerRef.current + if (!c) return + c.replaceChildren() + loadSvg(src).then((root) => { + if (cancelled || !c) return + c.appendChild(root) + }) + return () => { cancelled = true } + }, [src]) + + useEffect(() => { + const c = containerRef.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 = containerRef.current + if (!c) return + const all = c.querySelectorAll('[data-bone-id]') + all.forEach((el) => { + const id = el.getAttribute('data-bone-id') as string + const state = boneStates.get(id) + if (state && state !== 'default') el.setAttribute('data-state', state) + else el.removeAttribute('data-state') + }) + }, [boneStates]) + + return ( +

+ ) +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add src/components/canvas/AnatomyCanvas.tsx tests/unit/components.AnatomyCanvas.test.tsx +git commit -m "feat(canvas): inline SVG load + delegated click + state classes" +``` + +### Task 10.2 — DetailModal + +**Files:** +- Modify: `src/components/canvas/DetailModal.tsx` + +- [ ] **Step 1:** Implement +```tsx +import Dialog from '@/components/ui/Dialog' +import AnatomyCanvas from './AnatomyCanvas' +import type { BoneState } from '@/anatomy/types' + +export interface DetailModalProps { + open: boolean + onClose: () => void + detailSrc: string + detailId: string + title: string + boneStates: Map + onZoneClick: (boneId: string, detailId: string) => void +} + +export default function DetailModal({ + open, + onClose, + detailSrc, + detailId, + title, + boneStates, + onZoneClick, +}: DetailModalProps) { + return ( + +
+ onZoneClick(id, detailId)} + /> +
+

+ Cliquez sur les zones pour les ajouter à l'observation en cours. +

+
+ ) +} +``` + +- [ ] **Step 2:** Commit +```bash +git add src/components/canvas/DetailModal.tsx +git commit -m "feat(canvas): DetailModal renders detail SVG in Dialog" +``` + +### Task 10.3 — ZoneTooltip (deferred — DROPPED FROM v1) + +> Plan-review decision: spec hover-tooltip deferred to v1.1. Leave the +> placeholder file as-is; do not implement. Visual state classes alone +> (`current` / `linked` / `multi`) communicate zone participation in v1. + +--- + +## Phase 11 — Vertebra picker + +### Task 11.1 — Region tabs + chip grid + +**Files:** +- Modify: `src/components/observation/VertebraPicker.tsx` +- Create: `tests/unit/components.VertebraPicker.test.tsx` + +- [ ] **Step 1:** Test +```tsx +import { describe, it, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import VertebraPicker from '@/components/observation/VertebraPicker' +import { EQUINE_VERTEBRAL_FORMULA } from '@/domain/species/equine/vertebrae' + +describe('VertebraPicker', () => { + it('renders region tabs based on the formula', () => { + render( + {}} + onConfirm={() => {}} + initial={[]} + formula={EQUINE_VERTEBRAL_FORMULA} + title="Vertèbres cervicales" + />, + ) + expect(screen.getByRole('tab', { name: /Cervicales/ })).toBeInTheDocument() + expect(screen.getByRole('tab', { name: /Thoraciques/ })).toBeInTheDocument() + }) + + it('toggles a chip and confirms', async () => { + const onConfirm = vi.fn() + render( + {}} + onConfirm={onConfirm} + initial={[]} + formula={EQUINE_VERTEBRAL_FORMULA} + title="Vertèbres thoraciques" + />, + ) + await userEvent.click(screen.getByRole('tab', { name: /Thoraciques/ })) + await userEvent.click(screen.getByRole('button', { name: 'T12' })) + await userEvent.click(screen.getByRole('button', { name: 'Valider' })) + expect(onConfirm).toHaveBeenCalledWith([{ region: 'T', index: 12 }]) + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Implement +```tsx +import { useState } from 'react' +import Dialog from '@/components/ui/Dialog' +import Button from '@/components/ui/Button' +import Chip from '@/components/ui/Chip' +import type { Vertebra, VertebralRegion } from '@/domain/schema/observation' +import type { VertebralFormula } from '@/domain/species/types' + +const REGION_LABELS: Record = { + C: 'Cervicales', + T: 'Thoraciques', + L: 'Lombaires', + S: 'Sacrales', + Cd: 'Caudales', +} + +export interface VertebraPickerProps { + open: boolean + onClose: () => void + onConfirm: (vertebrae: Vertebra[]) => void + initial: Vertebra[] + formula: VertebralFormula + title: string +} + +export default function VertebraPicker({ + open, + onClose, + onConfirm, + initial, + formula, + title, +}: VertebraPickerProps) { + const [selected, setSelected] = useState(initial) + const [activeRegion, setActiveRegion] = useState('C') + + const has = (r: VertebralRegion, i: number) => + selected.some((v) => v.region === r && v.index === i) + + const toggle = (r: VertebralRegion, i: number) => { + setSelected((cur) => + has(r, i) + ? cur.filter((v) => !(v.region === r && v.index === i)) + : [...cur, { region: r, index: i }], + ) + } + + const all = (r: VertebralRegion, count: number) => { + setSelected((cur) => { + const rest = cur.filter((v) => v.region !== r) + return [...rest, ...Array.from({ length: count }, (_, k) => ({ region: r, index: k + 1 }))] + }) + } + + const none = (r: VertebralRegion) => + setSelected((cur) => cur.filter((v) => v.region !== r)) + + const count = formula[activeRegion] + + return ( + +
+ {(Object.keys(REGION_LABELS) as VertebralRegion[]).map((r) => ( + + ))} +
+ +
+ {Array.from({ length: count }, (_, k) => k + 1).map((i) => ( + toggle(activeRegion, i)} + > + {activeRegion}{i} + + ))} +
+ +
+ + +
+ +
+ + +
+
+ ) +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add src/components/observation/VertebraPicker.tsx tests/unit/components.VertebraPicker.test.tsx +git commit -m "feat(observation): VertebraPicker dialog with region tabs + chip grid" +``` + +--- + +## Phase 12 — Pathology picker + free-text + severity + +### Task 12.1 — PathologyPicker + +**Files:** +- Modify: `src/components/observation/PathologyPicker.tsx` +- Create: `tests/unit/components.PathologyPicker.test.tsx` + +- [ ] **Step 1:** Test +```tsx +import { describe, it, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import PathologyPicker from '@/components/observation/PathologyPicker' +import type { Pathology } from '@/domain/schema/pathology' + +const POOL: Pathology[] = [ + { + id: 'a', + labelFr: 'Aïe', + description: '', + category: 'osseux', + speciesIds: ['equine'], + boneIds: ['epaule'], + sources: [{ type: 'manual', citation: 'X' }], + }, + { + id: 'b', + labelFr: 'Aïe-aïe', + description: '', + category: 'osseux', + speciesIds: ['equine'], + boneIds: ['hanche'], + sources: [{ type: 'manual', citation: 'X' }], + }, +] + +describe('PathologyPicker', () => { + it('shows only pathologies matching zones', () => { + render( + {}} + />, + ) + expect(screen.getByLabelText('Aïe')).toBeInTheDocument() + expect(screen.queryByLabelText('Aïe-aïe')).toBeNull() + }) + + it('toggles selection', async () => { + const onChange = vi.fn() + render( + , + ) + await userEvent.click(screen.getByLabelText('Aïe')) + expect(onChange).toHaveBeenCalledWith(['a']) + }) +}) +``` + +- [ ] **Step 2:** Run; expect FAIL + +- [ ] **Step 3:** Implement +```tsx +import { useMemo } from 'react' +import type { Pathology } from '@/domain/schema/pathology' + +export interface PathologyPickerProps { + pool: Pathology[] + speciesId: string + boneIds: string[] + selected: string[] + onChange: (next: string[]) => void +} + +function matches(p: Pathology, speciesId: string, boneIds: string[]): boolean { + const speciesOk = p.speciesIds.length === 0 || p.speciesIds.includes(speciesId) + if (!speciesOk) return false + if (boneIds.length === 0) return true + if (p.boneIds.length === 0) return true + return p.boneIds.some((b) => boneIds.includes(b)) +} + +export default function PathologyPicker({ + pool, + speciesId, + boneIds, + selected, + onChange, +}: PathologyPickerProps) { + const filtered = useMemo( + () => pool.filter((p) => matches(p, speciesId, boneIds)), + [pool, speciesId, boneIds], + ) + + function toggle(id: string) { + onChange(selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id]) + } + + if (filtered.length === 0) { + return ( +

+ Aucune pathologie de référence pour ces zones. Ajoutez-en une en texte libre ci-dessous. +

+ ) + } + + return ( +
    + {filtered.map((p) => ( +
  • + +
  • + ))} +
+ ) +} +``` + +- [ ] **Step 4:** Re-run; expect PASS + +- [ ] **Step 5:** Commit +```bash +git add src/components/observation/PathologyPicker.tsx tests/unit/components.PathologyPicker.test.tsx +git commit -m "feat(observation): PathologyPicker filtered by species + zones" +``` + +### Task 12.2 — FreeTextPathologyInput + +**Files:** +- Modify: `src/components/observation/FreeTextPathologyInput.tsx` + +- [ ] **Step 1:** Implement +```tsx +import { useState } from 'react' +import Input from '@/components/ui/Input' +import Button from '@/components/ui/Button' +import Badge from '@/components/ui/Badge' + +export interface FreeTextPathologyInputProps { + items: string[] + onChange: (next: string[]) => void +} + +export default function FreeTextPathologyInput({ + items, + onChange, +}: FreeTextPathologyInputProps) { + const [v, setV] = useState('') + function add() { + const trimmed = v.trim() + if (!trimmed) return + onChange([...items, trimmed]) + setV('') + } + function remove(i: number) { + onChange(items.filter((_, k) => k !== i)) + } + return ( +
+
+ setV(e.target.value)} + placeholder="Pathologie additionnelle (texte libre)" + onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); add() } }} + aria-label="Pathologie libre" + /> + +
+ {items.length > 0 && ( +
    + {items.map((it, i) => ( +
  • + + {it} + + +
  • + ))} +
+ )} +
+ ) +} +``` + +- [ ] **Step 2:** Commit +```bash +git add src/components/observation/FreeTextPathologyInput.tsx +git commit -m "feat(observation): FreeTextPathologyInput with chip removal" +``` + +### Task 12.3 — SeveritySelector + +**Files:** +- Modify: `src/components/observation/SeveritySelector.tsx` + +- [ ] **Step 1:** Implement +```tsx +import type { Severity } from '@/domain/schema/observation' + +export interface SeveritySelectorProps { + value: Severity | undefined + onChange: (s: Severity | undefined) => void +} + +const SEVERITIES: Severity[] = ['légère', 'modérée', 'sévère'] +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)]', +} + +export default function SeveritySelector({ value, onChange }: SeveritySelectorProps) { + return ( +
+ {SEVERITIES.map((s) => ( + + ))} +
+ ) +} +``` + +- [ ] **Step 2:** Commit +```bash +git add src/components/observation/SeveritySelector.tsx +git commit -m "feat(observation): SeveritySelector radio chips" +``` + +--- + +## Phase 13 — Observation list, card, editor + +### Task 13.1 — ObservationCard + +**Files:** +- Modify: `src/components/observation/ObservationCard.tsx` + +- [ ] **Step 1:** Implement +```tsx +import type { Observation } from '@/domain/schema/observation' +import Card from '@/components/ui/Card' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' + +export interface ObservationCardProps { + observation: Observation + index: number + active: boolean + onSelect: () => void + onDelete: () => void + onMoveUp: () => void + onMoveDown: () => void + canMoveUp: boolean + canMoveDown: boolean +} + +export default function ObservationCard({ + observation, + index, + active, + onSelect, + onDelete, + onMoveUp, + onMoveDown, + canMoveUp, + canMoveDown, +}: ObservationCardProps) { + const zoneCount = observation.zones.length + const patCount = + observation.pathologyIds.length + observation.freeTextPathologies.length + + return ( + +
+ +
+ + + +
+
+
+ ) +} +``` + +- [ ] **Step 2:** Commit +```bash +git add src/components/observation/ObservationCard.tsx +git commit -m "feat(observation): ObservationCard with reorder + delete affordances" +``` + +### Task 13.2 — ObservationList + +**Files:** +- Modify: `src/components/observation/ObservationList.tsx` + +- [ ] **Step 1:** Implement +```tsx +import type { Observation } from '@/domain/schema/observation' +import ObservationCard from './ObservationCard' +import Button from '@/components/ui/Button' + +export interface ObservationListProps { + observations: Observation[] + activeIndex: number + onSelect: (i: number) => void + onAdd: () => void + onDelete: (i: number) => void + onMoveUp: (i: number) => void + onMoveDown: (i: number) => void +} + +export default function ObservationList({ + observations, + activeIndex, + onSelect, + onAdd, + onDelete, + onMoveUp, + onMoveDown, +}: ObservationListProps) { + return ( +
+
+

Observations

+ +
+ {observations.length === 0 ? ( +

+ Aucune observation. Cliquez sur "+ Nouvelle observation" puis sur les zones du schéma. +

+ ) : ( +
    + {observations.map((obs, i) => ( +
  • + onSelect(i)} + onDelete={() => onDelete(i)} + onMoveUp={() => onMoveUp(i)} + onMoveDown={() => onMoveDown(i)} + canMoveUp={i > 0} + canMoveDown={i < observations.length - 1} + /> +
  • + ))} +
+ )} +
+ ) +} +``` + +- [ ] **Step 2:** Commit +```bash +git add src/components/observation/ObservationList.tsx +git commit -m "feat(observation): ObservationList with add + per-card actions" +``` + +### Task 13.3 — ObservationEditor + +**Files:** +- Modify: `src/components/observation/ObservationEditor.tsx` + +- [ ] **Step 1:** Implement +```tsx +import { useMemo } from 'react' +import type { Observation, ObservationZone, Vertebra } from '@/domain/schema/observation' +import type { Pathology } from '@/domain/schema/pathology' +import type { Bone } from '@/anatomy/types' +import Label from '@/components/ui/Label' +import Textarea from '@/components/ui/Textarea' +import Badge from '@/components/ui/Badge' +import PathologyPicker from './PathologyPicker' +import FreeTextPathologyInput from './FreeTextPathologyInput' +import SeveritySelector from './SeveritySelector' + +export interface ObservationEditorProps { + observation: Observation + bones: Map + speciesId: string + pathologyPool: Pathology[] + onChange: (next: Observation) => void + onOpenVertebraPicker: (zoneIndex: number) => void + onRemoveZone: (zoneIndex: number) => void +} + +function describeZone(z: ObservationZone, bones: Map): string { + const b = bones.get(z.boneId) + const label = b?.fr ?? z.boneId + if (z.vertebrae?.length) { + const vs = z.vertebrae.map((v: Vertebra) => `${v.region}${v.index}`).join(', ') + return `${label} (${vs})` + } + return label +} + +export default function ObservationEditor({ + observation, + bones, + speciesId, + pathologyPool, + onChange, + onOpenVertebraPicker, + onRemoveZone, +}: ObservationEditorProps) { + const zoneBoneIds = useMemo( + () => observation.zones.map((z) => z.boneId), + [observation.zones], + ) + + return ( +
+
+ + {observation.zones.length === 0 ? ( +

+ Cliquez sur les zones du schéma pour les ajouter à cette observation. +

+ ) : ( +
    + {observation.zones.map((z, i) => { + const b = bones.get(z.boneId) + const isSpine = b?.category === 'spine-zone' + return ( +
  • + + {describeZone(z, bones)} + {isSpine && ( + + )} + + +
  • + ) + })} +
+ )} +
+ +
+ + onChange({ ...observation, pathologyIds: ids })} + /> +
+ +
+ + onChange({ ...observation, freeTextPathologies: items })} + /> +
+ +
+ + onChange({ ...observation, severity: s })} + /> +
+ +
+ +