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) <noreply@anthropic.com>
This commit is contained in:
Bastien ChanotandClaude Opus 4.7 committed 2026-05-18 20:55:10 +02:00
1 parent 12a3e48fdf
commit 8ca36b5ccd
104 files changed
+12448

No files matched your search

+10
View File
@@ -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/<id>/` folder
3. Defining vertebralFormula + pathology DB
4. Registering in `src/domain/species/registry.ts`
5. Testing with convention parser + pathology integrity tests
+172
View File
@@ -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: transparent fill, receives pointer events -->
<polygon
data-bone-id="cervical-spine"
data-bone-fr="Colonne cervicale"
data-bone-en="Cervical spine"
data-category="spine-zone"
class="bone-hitbox"
fill="transparent"
style="pointer-events: all; cursor: pointer"
/>
<!-- visible twin: colored fill, no pointer events -->
<polygon
data-bone-id="cervical-spine"
class="bone-visible"
fill="#c8d8e8"
style="pointer-events: none"
/>
```
- 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
<polygon
data-bone-id="thoracic-t1-t18"
data-bone-fr="Thoracique T1-T18"
data-bone-en="Thoracic T1-T18"
data-category="spine-zone"
fill="#d4e8d4"
style="pointer-events: all; cursor: pointer"
/>
```
---
## 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<string, Bone>`.
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 `<svg>` 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/<speciesId>/<filename>.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.
+12
View File
@@ -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
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,370 @@
# Osteo Report — MVP Architecture Spec
Date: 2026-05-18
Status: Approved at validation gate #1.
## Purpose
Single-praticien web app for veterinary osteopathy bilans. The praticien
selects an animal species, clicks anatomical zones on an SVG schematic to
build clinical observations (groups of zones sharing one problem), attaches
pathologies (curated DB + free-text) and severity per observation, writes a
conclusion + recommendations + next RDV, and exports the whole report as a
self-contained A4 PDF whose JSON state is carried as a native PDF
attachment. Re-importing the PDF restores the state for a follow-up.
Static SPA, no backend, no auth, no analytics. Deployed as a Docker image
serving nginx behind a host nginx reverse proxy on Scaleway VPS. Identity
strings (site name, brand, footer) come from env vars, never hardcoded.
Open-source (MIT).
MVP species: equine only.
## Stack
| Concern | Choice | Why |
|---|---|---|
| Build | Vite 7 + @vitejs/plugin-react-swc | Fast HMR, ESM-native, no Webpack tax. |
| UI | React 19 + TypeScript 5 strict | Editor complexity warrants components; React 19's automatic memo + concurrent rendering. |
| Styling | Tailwind v4 (CSS-first config) + design tokens in CSS | No PostCSS config, design tokens via @theme. |
| State | Zustand 5 | Lighter than Redux, simpler than Context for editor; selectors avoid re-render storms. |
| Validation | Zod 3 | Mirrors persisted JSON schema, gives import-time errors. |
| PDF | pdf-lib 1.17 | Pure-JS, supports native PDF attachments via `attach()`. |
| SVG raster | canvg 4 → canvas → PNG → `embedPng` | A4 print quality at 2× scale. |
| Animation | motion 11 | Modal transitions, toasts, observation cards. |
| Tests | vitest 3 + happy-dom + RTL | Unit-first; no e2e for MVP. |
| Tooling | ESLint 9 flat config, Prettier, pnpm 9, Node 20 | Modern defaults. |
| Deploy | Multi-stage Docker → nginx:alpine | Static dist served; entrypoint injects env into runtime config. |
## Folder tree
```
osteo/
├─ public/species/equine/{Horse,Horse_head}.svg
├─ src/
│ ├─ app/{App,routes/{Home,NewReport,Editor,NotFound}Route,providers/ConfigProvider}.tsx
│ ├─ config/env.ts
│ ├─ domain/
│ │ ├─ schema/{report,observation,practitioner,animal,pathology}.ts
│ │ └─ species/{registry,types,equine/{index,vertebrae,pathologies}}.ts
│ ├─ state/{reportStore,practitionerCache}.ts
│ ├─ anatomy/{svgLoader,svgConvention,types}.ts
│ ├─ 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,import,attachment,fonts}.ts + pdf/render/{header,footer,observationPage,conclusionPage,svgToPng}.ts
│ ├─ lib/{dates,id,assert}.ts
│ ├─ styles/{index,tokens}.css
│ └─ main.tsx
├─ tests/unit/*.test.ts + tests/setup.ts
├─ docs/{ANATOMY-SVG-CONVENTION,ADDING-A-SPECIES,PDF-FORMAT}.md + docs/superpowers/specs/
├─ .claude/{tasks/TODO.md,memory/{decisions,learnings,blockers,journal,evals}.md,audits/.gitkeep}
├─ Dockerfile, docker-compose.yml, nginx.conf
├─ .env.example, .editorconfig, .nvmrc, .prettierrc.json, .gitignore, .dockerignore
├─ eslint.config.js, index.html, package.json, tsconfig*.json, vite.config.ts, vitest.config.ts
└─ CLAUDE.md, README.md, LICENSE (MIT)
```
## Data model
```ts
type Severity = 'légère' | 'modérée' | 'sévère';
type Vertebra = { region: 'C' | 'T' | 'L' | 'S' | 'Cd'; index: number };
type ObservationZone = {
boneId: string; // matches data-bone-id from SVG
detailSourceId?: string; // when this zone came from a detail pop-up SVG
vertebrae?: Vertebra[]; // when boneId is a spine-zone
};
type Observation = {
id: string;
zones: ObservationZone[];
pathologyIds: string[];
freeTextPathologies: string[];
severity?: Severity;
comment: string;
};
type Report = {
version: 1;
id: string;
createdAt: string; // ISO
date: string; // clinical date (ISO)
practitioner: { name: string; cabinet?: string; contact?: string; siret?: string };
animal: { speciesId: string; name: string; breed?: string; age?: string };
owner: { name: string };
observations: Observation[];
conclusion: string;
recommendations: string;
nextAppointment?:
| { kind: 'date'; date: string }
| { kind: 'period'; text: string };
};
type PathologyCategory =
| 'osseux' | 'articulaire' | 'musculaire' | 'tendino-ligamentaire'
| 'fascial' | 'visceral' | 'cranio-sacre' | 'nerveux' | 'autre';
type PathologyRef = {
type: 'manual' | 'journal' | 'database' | 'web';
citation: string; // human-readable
url?: string;
};
type Pathology = {
id: string; // stable kebab-case
labelFr: string;
description: string;
category: PathologyCategory;
speciesIds: string[]; // [] = applicable to all species
boneIds: string[]; // [] = applicable to all zones
sources: PathologyRef[]; // 1+
};
```
All JSON carries `version: 1`. Future migrations bump the version.
## SVG convention (source of truth)
A clickable zone is any element carrying `data-bone-id`. Required data
attributes: `data-bone-id`, `data-bone-fr`, `data-bone-en`, `data-category`.
Optional: `data-opens-detail="<id>"`.
Categories: `articulation` · `charniere` · `spine-zone` · `os` · `os-overlay`
· `head` · `cadran-crane`.
Two rendering patterns are tolerated in the SVG:
1. **hitbox + visible twin** (articulation, charniere, os-overlay, head):
two elements share the same `data-bone-id`. One has `class*="hitbox"`,
transparent fill, `pointer-events: all`. The other has `class*="visible"`,
colored fill, `pointer-events: none`.
2. **single element** (spine-zone, head zone): one polygon carries everything;
`pointer-events: all` and `cursor: pointer` directly.
Parser strategy (`src/anatomy/svgConvention.ts`):
- Walk all elements with `data-bone-id`.
- Group by `data-bone-id` → one logical `Bone`.
- Bone fields: `id`, `fr`, `en`, `category`, `opensDetail?`, `hitboxEls[]`,
`visibleEls[]`.
- Validate: must have `data-bone-fr`, `data-bone-en`, `data-category` (in
the allowed enum). Throws structured `SvgConventionError` on missing
attributes.
Click handling: a single delegated listener on the root `<svg>` walks up
from `event.target` to the nearest element with `data-bone-id`. If
`data-opens-detail` is present → open the detail modal mapped via the
species manifest. If the bone's category is `spine-zone` → open the
vertebra picker. Otherwise add the bone to the current observation.
Colorization: when the current observation contains a bone, all elements
matching that `data-bone-id` get a `data-state` attribute toggled by JS:
`current` (solid accent), `linked` (faded dashed border, "in another
observation"), `multi` (striped pattern, "in ≥2 observations").
> MVP scope cut: hover tooltip listing the owning observations is deferred.
> Visual state classes alone communicate participation in v1.
## Detail-popup mechanism
The mapping `detailId → SVG path` is held in the species manifest:
```ts
// src/domain/species/equine/index.ts
export const equine = {
id: 'equine',
mainSvg: '/species/equine/Horse.svg',
details: { head: '/species/equine/Horse_head.svg' },
vertebralFormula: { C: 7, T: 18, L: 6, S: 5, Cd: 18 }, // approx Cd cap
pathologies: () => import('./pathologies'),
};
```
When a zone with `data-opens-detail="head"` is clicked, the canvas
emits a `requestDetail({id: 'head'})` event handled by `DetailModal`, which
loads `/species/equine/Horse_head.svg` and renders it inline. Clicks inside
the modal add zones with `detailSourceId: 'head'` to the current
observation. The "entry" zone (e.g. the head polygon itself) is never
persisted in the report.
## Vertebra picker
Triggered when a clicked bone has `data-category="spine-zone"`. Modal with
region tabs (Cervicales C1–C7, Thoraciques T1–T18, Lombaires L1–L6,
Sacrales S1–S5, Caudales Cd1–Cd18). Each region renders chips in a grid;
multi-select; ≥40 px touch targets; per-region "Tout cocher / décocher".
Stored as `vertebrae: Vertebra[]` on the `ObservationZone` (replaces the
global zone semantically: PDF prints precise vertebrae rather than the
bloc).
If a praticien clicks an individual vertebra (rendered under the same
`bone-id` as the bloc), it is treated identically to clicking the
spine-zone — opens the picker. Avoids duplicate UI paths.
## Multi-observation zone overlay
A bone may belong to several observations. Visual states (`data-state`
attribute on matching SVG elements, styled via `src/styles/index.css`):
- `current` — bone is in the active observation. Solid accent fill.
- `linked` — bone is in another observation (not current). Dashed border,
faded accent fill.
- `multi` — bone is in ≥2 observations. Same fill + heavier stroke to
signal sharing.
> MVP scope cut: per-observation HSL accent cycling (6 clinical-warm tones)
> deferred to v1.1. v1 uses a single accent color across all states; PDF
> renders per-observation pages, so colour ambiguity does not bleed into
> the printed report.
## PDF format
A4 portrait (595.28 × 841.89 pt). One pdf-lib document per export. Pages
share a header drawer (praticien left block, animal+owner+date right) and a
footer drawer (env-driven brand name, export date, page x/y).
Per observation: one page with
- the full main SVG rasterized at 2× scale with that observation's zones
colored (canvg writes to canvas → PNG → `embedPng`);
- if the observation includes detail-sourced zones (e.g. head): a second
rasterization of the detail SVG with those zones colored, placed beside
or below the main raster;
- a structured block beneath the schematic: zones (with precise vertebrae
formatted as "T12, T15"), pathologies (selected + free-text), severity,
comment.
> MVP scope cut: source citations under each cited pathology are deferred
> to post-MVP. Pathology IDs/labels render without their `sources[]` block.
Final page: conclusion, recommendations, next appointment.
JSON attachment: the full `Report` object is serialized and attached via
`pdfDoc.attach(bytes, 'osteo-report.json', { mimeType: 'application/json',
description: 'Osteo Report state v1', creationDate, modificationDate,
afRelationship: 'Data' })`. Bytes are pretty-printed JSON (UTF-8).
MVP fonts: pdf-lib standard Helvetica + Helvetica-Bold (body) + Times-Roman
(headings). Inter Sans + Fraunces TTF bundling deferred to v1.1 to avoid
shipping ~600KB of font assets in the initial Docker image.
## PDF import
`pdf-lib loadDocument()` → walk catalog `Names → EmbeddedFiles` tree → find
an attachment whose filename starts with `osteo-report` and whose mime is
`application/json` (or, fallback, parse-then-validate). Extract the stream,
flate-decompress if needed (pako), parse JSON, validate with Zod. On
success: hydrate the store and route to `/editor`. On failure: throw
`ImportError` with the French message
"Ce PDF n'a pas été généré par Osteo Report (pas de données détectées)." and
show a toast.
## Configurable identity
Env vars consumed at runtime:
| Name | Default | Use |
|---|---|---|
| `PORT` | `8080` | nginx listen port. |
| `APP_SITE_NAME` | `Osteo Report` | `<title>`. |
| `APP_BRAND_NAME` | `Osteo Report` | UI header, hero. |
| `APP_FOOTER_NAME` | `Osteo Report` | PDF footer. |
| `APP_TAGLINE` | `Bilans d'ostéopathie animalière` | Home tagline. |
Mechanism: Docker entrypoint templates `index.html` to inject a
`<script>window.__APP_CONFIG__ = {...}</script>` tag using container env
vars. `src/config/env.ts` reads `window.__APP_CONFIG__` first, falls back
to `import.meta.env.VITE_APP_*` build-time values, then to defaults.
`ConfigProvider` exposes the resolved config via React context. No identity
string is hardcoded in any component.
## Routes
- `/` — Home. Two CTAs ("Nouveau bilan", "Importer un PDF"). Quick-resume
card if a sessionStorage draft exists.
- `/new` — New report form. Species select (equine only for MVP),
praticien fields (prefilled from `osteo:lastPractitioner`), animal
(name + optional race/age), owner name, date (default today).
- `/editor` — Editor. Split layout: anatomy canvas + observation panel.
Bottom bar: export button.
- `*` — NotFoundRoute.
## State persistence
- Zustand store in memory.
- sessionStorage mirror (`osteo:draft`) auto-restored on `/editor` if the
user reloads accidentally; cleared after export.
- localStorage (`osteo:lastPractitioner`) caches the praticien block to
prefill next "Nouveau bilan".
- No long-term storage. PDF is the only durable artifact.
## Test strategy
- vitest + happy-dom.
- TDD-first for: schema (Zod parse + reject malformed), store actions, id
generator, anatomy convention parser (valid SVG → bones; bad SVG →
structured error), pathology DB integrity (every entry validates + has
≥1 source), pdf attachment write+extract roundtrip on a fixture file.
- UI smoke test: AnatomyCanvas mounts a fixture SVG and emits click for a
known bone.
- No e2e (no gstack plugin); manual QA in browser before commit.
## Docker / deploy
Multi-stage Dockerfile:
1. **builder** — `node:20-alpine`. `corepack enable && pnpm i --frozen-lockfile && pnpm build`.
2. **runner** — `nginx:alpine`. Copy `dist/` to `/usr/share/nginx/html`,
custom `nginx.conf` listening on `${PORT:-8080}`, `entrypoint.sh` writes
`/usr/share/nginx/html/env.js` from `APP_*` env vars, then runs nginx.
`docker-compose.yml` exposes `${PORT}:${PORT}` and passes `APP_*` env vars
through `env_file`. The host nginx reverse-proxies any subdomain to that
port.
## Open decisions resolved
| Decision | Resolution |
|---|---|
| SVG injection | Fetch text → DOMParser → inline render (consistent + CSS-controllable + sandboxing irrelevant since assets are local). |
| Vertebra picker UX | Region tabs + chip grid, multi-select, ≥40 px touch targets. |
| Multi-obs zone overlay | current / linked / multi states; striped pattern + tooltip. |
| Detail SVG trigger | `data-opens-detail` → modal with inline detail SVG, clicks add to current obs. |
| SVG → PDF | canvg → canvas @ 2× → PNG → `embedPng`. |
| Pathology sources in PDF | Abbreviated citation list below each obs, no raw URLs. |
| Brand env vars | Runtime `window.__APP_CONFIG__` + Vite-define fallback. |
| MVP scope | Equine only. |
| Drag-reorder obs | ↑/↓ buttons, no DnD. |
| Practitioner default | localStorage cache. |
| State persistence | sessionStorage mirror + PDF for long-term. |
| Animation lib | motion 11. |
| License | MIT. |
## Prerequisites / REMAINING
- Real anatomical SVGs delivered by user at repo root: `Horse.svg` +
`Horse_head.svg`. Moved into `public/species/equine/` by the scaffolder.
- **Pathology DB authoring — deferred to post-MVP.** v1 ships with an
empty `EQUINE_PATHOLOGIES = []` and a relaxed integrity test (length
0..100). Pathology picker shows the "aucune pathologie de référence"
empty-state; praticien adds entries via free-text. Client osteo (or a
Phase 2 multi-user authoring tool) will populate the curated DB once
the long-term account architecture is decided.
- **Source citations in PDF — deferred to v1.1.** Once the DB exists,
re-enable the abbreviated-citation block on each observation page.
- **Hover tooltip on canvas — deferred to v1.1.** Visual state classes
alone in v1.
- **Per-observation HSL accent cycling — deferred to v1.1.** Single
accent in v1.
- **Inter + Fraunces TTF bundling — deferred to v1.1.** PDF uses standard
Helvetica + Times-Roman in v1.
- **`docs/ADDING-A-SPECIES.md` — content to be authored** from the
observed SVG convention + species manifest pattern (placeholder file
exists today).
- Final brand name, domain, identity strings.
- Phase 2 (out of MVP): user accounts, server persistence, animal history,
and curated pathology DB authoring tooling.