From 8f217d81035564f2dd519f4c890fb4314c52e024 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 21:41:51 +0200 Subject: [PATCH] chore: purge transient planning artifacts (BDR-065) --- .../plans/2026-05-18-osteo-report-mvp.md | 4269 ----------------- .../plans/2026-05-20-b3-i18n-fr-en.md | 1598 ------ .../plans/2026-05-23-laterality-support.md | 738 --- .../plans/2026-05-23-responsive-mobile.md | 760 --- .../2026-05-18-osteo-report-mvp-design.md | 378 -- .../specs/2026-05-20-b3-i18n-fr-en-design.md | 115 - .../2026-05-22-pathology-editor-design.md | 387 -- .../2026-05-23-laterality-support-design.md | 234 - .../2026-05-23-responsive-mobile-design.md | 98 - 9 files changed, 8577 deletions(-) delete mode 100644 docs/superpowers/plans/2026-05-18-osteo-report-mvp.md delete mode 100644 docs/superpowers/plans/2026-05-20-b3-i18n-fr-en.md delete mode 100644 docs/superpowers/plans/2026-05-23-laterality-support.md delete mode 100644 docs/superpowers/plans/2026-05-23-responsive-mobile.md delete mode 100644 docs/superpowers/specs/2026-05-18-osteo-report-mvp-design.md delete mode 100644 docs/superpowers/specs/2026-05-20-b3-i18n-fr-en-design.md delete mode 100644 docs/superpowers/specs/2026-05-22-pathology-editor-design.md delete mode 100644 docs/superpowers/specs/2026-05-23-laterality-support-design.md delete mode 100644 docs/superpowers/specs/2026-05-23-responsive-mobile-design.md diff --git a/docs/superpowers/plans/2026-05-18-osteo-report-mvp.md b/docs/superpowers/plans/2026-05-18-osteo-report-mvp.md deleted file mode 100644 index e63bb43b..00000000 --- a/docs/superpowers/plans/2026-05-18-osteo-report-mvp.md +++ /dev/null @@ -1,4269 +0,0 @@ -# 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-anno-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-anno-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-anno-name-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-anno-id') ?? '' - for (const attr of ['data-anno-name-fr', 'data-anno-name-en', 'data-anno-category']) { - if (!el.getAttribute(attr)) { - throw new SvgConventionError( - `Element data-anno-id="${boneId}" missing attribute ${attr}`, - boneId, - attr, - ) - } - } - const cat = el.getAttribute('data-anno-category') ?? '' - if (!isValidCategory(cat)) { - throw new SvgConventionError( - `Element data-anno-id="${boneId}" has unknown data-anno-category="${cat}"`, - boneId, - 'data-anno-category', - ) - } -} - -export function parseSvgBones(svgRoot: SVGSVGElement): Map { - const map = new Map() - const all = svgRoot.querySelectorAll('[data-anno-id]') - all.forEach((el) => { - validateBoneElement(el) - const id = el.getAttribute('data-anno-id') as string - const fr = el.getAttribute('data-anno-name-fr') as string - const en = el.getAttribute('data-anno-name-en') as string - const category = el.getAttribute('data-anno-category') as BoneCategory - const opensDetail = el.getAttribute('data-anno-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-anno-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-anno-id] { cursor: pointer; } -.svg-canvas [data-anno-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-anno-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-anno-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-anno-id]') - all.forEach((el) => { - const id = el.getAttribute('data-anno-id') as string - const state = boneStates.get(id) - if (state && state !== 'default') el.setAttribute('data-state', state) - else el.removeAttribute('data-state') - }) - }, [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 })} - /> -
- -
- -