User updated the clickable-zone convention in the source SVGs:
data-bone-id → data-anno-id
data-bone-fr → data-anno-name-fr
data-bone-en → data-anno-name-en
data-category → data-anno-category
data-opens-detail → data-anno-opens-detail
Bulk-renamed across:
- public/species/equine/Horse.svg + Horse_head.svg (86 anno-attrs each)
- src/anatomy/svgConvention.ts (parser + getBoneIdFromEvent)
- src/anatomy/types.ts (doc strings)
- src/components/canvas/AnatomyCanvas.tsx (querySelector + delegated click)
- src/styles/index.css (`[data-bone-id]` selectors → `[data-anno-id]`)
- src/domain/species/types.ts + schema/observation.ts (doc strings)
- docs/{ANATOMY-SVG-CONVENTION,ADDING-A-SPECIES,superpowers/specs,plans}.md
- CLAUDE.md + .claude/{memory/learnings,tasks/TODO}.md
- tests/unit/{anatomy.svgConvention,anatomy.svgLoader,components.AnatomyCanvas}.test.tsx
Internal TS type names and field names (Bone, boneId, parseSvgBones,
getBoneIdFromEvent) are kept intentionally — they're the application's
logical shape and the persisted JSON contract. ObservationZone.boneId is
the identifier seen in already-exported PDFs; renaming it would break
re-import of those PDFs. Only the SVG-side attribute names change.
90/90 tests pass, lint clean, build clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
4270 lines
126 KiB
Markdown
4270 lines
126 KiB
Markdown
# 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 -- <path>` 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 = `
|
||
<svg xmlns="http://www.w3.org/2000/svg">
|
||
<circle data-anno-id="epaule" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
|
||
data-anno-category="articulation" class="bone osteo articulation hitbox bone-epaule" />
|
||
<circle data-anno-id="epaule" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
|
||
data-anno-category="articulation" class="bone osteo articulation visible bone-epaule" />
|
||
<polygon data-anno-id="cervical-vertebrae-spine-zone" data-anno-name-fr="Vertèbres cervicales"
|
||
data-anno-name-en="Cervical Vertebrae" data-anno-category="spine-zone"
|
||
class="bone osteo spine-zone bone-cervical-vertebrae" />
|
||
<polygon data-anno-id="zone-head" data-anno-name-fr="Crane" data-anno-name-en="Head"
|
||
data-anno-category="head" data-anno-opens-detail="head" />
|
||
</svg>`
|
||
|
||
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 = `<svg xmlns="http://www.w3.org/2000/svg">
|
||
<circle data-anno-id="x" data-anno-name-en="X" data-anno-category="os" />
|
||
</svg>`
|
||
expect(() => parseSvgBones(svgFromString(bad))).toThrow(SvgConventionError)
|
||
})
|
||
|
||
it('throws on unknown category', () => {
|
||
const bad = `<svg xmlns="http://www.w3.org/2000/svg">
|
||
<circle data-anno-id="x" data-anno-name-fr="X" data-anno-name-en="X" data-anno-category="bogus" />
|
||
</svg>`
|
||
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<string, Bone> {
|
||
const map = new Map<string, Bone>()
|
||
const all = svgRoot.querySelectorAll<Element>('[data-anno-id]')
|
||
all.forEach((el) => {
|
||
validateBoneElement(el)
|
||
const id = el.getAttribute('data-anno-id') as string
|
||
const fr = el.getAttribute('data-anno-name-fr') 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 = '<svg xmlns="http://www.w3.org/2000/svg"><g data-anno-id="x"/></svg>'
|
||
|
||
describe('loadSvg', () => {
|
||
beforeEach(() => {
|
||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||
ok: true,
|
||
text: async () => SVG,
|
||
})) as unknown as typeof fetch)
|
||
})
|
||
|
||
it('returns an SVGSVGElement', async () => {
|
||
const root = await loadSvg('/whatever.svg')
|
||
expect(root.tagName.toLowerCase()).toBe('svg')
|
||
})
|
||
|
||
it('throws on non-ok response', async () => {
|
||
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404, text: async () => '' })) as unknown as typeof fetch)
|
||
await expect(loadSvg('/missing.svg')).rejects.toThrow()
|
||
})
|
||
})
|
||
```
|
||
|
||
- [ ] **Step 2:** Run; expect FAIL
|
||
|
||
- [ ] **Step 3:** Implement
|
||
```ts
|
||
export async function loadSvg(publicPath: string): Promise<SVGSVGElement> {
|
||
const resp = await fetch(publicPath)
|
||
if (!resp.ok) {
|
||
throw new Error(`Failed to load SVG ${publicPath}: HTTP ${resp.status}`)
|
||
}
|
||
const text = await resp.text()
|
||
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
|
||
const parseErr = doc.querySelector('parsererror')
|
||
if (parseErr) {
|
||
throw new Error(`Invalid SVG at ${publicPath}: ${parseErr.textContent}`)
|
||
}
|
||
const root = doc.documentElement
|
||
if (root.tagName.toLowerCase() !== 'svg') {
|
||
throw new Error(`Root element of ${publicPath} is not <svg>`)
|
||
}
|
||
return root as unknown as SVGSVGElement
|
||
}
|
||
|
||
export async function svgToPngDataUrl(
|
||
_svgEl: SVGSVGElement,
|
||
_scale: number,
|
||
): Promise<string> {
|
||
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<Report, 'id' | 'createdAt' | 'version'>) => 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<ReportStore>((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(<Button onClick={onClick}>Save</Button>)
|
||
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||
expect(onClick).toHaveBeenCalledOnce()
|
||
})
|
||
|
||
it('respects disabled', () => {
|
||
render(<Button disabled>Save</Button>)
|
||
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<HTMLButtonElement> {
|
||
variant?: 'primary' | 'secondary' | 'ghost' | 'danger'
|
||
size?: 'sm' | 'md' | 'lg'
|
||
children?: ReactNode
|
||
}
|
||
|
||
const VARIANTS: Record<NonNullable<ButtonProps['variant']>, 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<NonNullable<ButtonProps['size']>, 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 (
|
||
<button
|
||
className={[
|
||
'inline-flex items-center justify-center font-medium transition disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2',
|
||
VARIANTS[variant],
|
||
SIZES[size],
|
||
className,
|
||
].join(' ')}
|
||
{...rest}
|
||
>
|
||
{children}
|
||
</button>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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 (
|
||
<Tag
|
||
className={[
|
||
'rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] shadow-sm',
|
||
className,
|
||
].join(' ')}
|
||
>
|
||
{children}
|
||
</Tag>
|
||
)
|
||
}
|
||
```
|
||
|
||
`Input.tsx`:
|
||
```tsx
|
||
import { forwardRef, type InputHTMLAttributes } from 'react'
|
||
|
||
const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(
|
||
({ className = '', ...rest }, ref) => (
|
||
<input
|
||
ref={ref}
|
||
className={[
|
||
'h-10 w-full rounded-lg border border-[var(--color-border)] bg-white px-3 text-base text-[var(--color-ink)] placeholder:text-[var(--color-ink-muted)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
|
||
className,
|
||
].join(' ')}
|
||
{...rest}
|
||
/>
|
||
),
|
||
)
|
||
Input.displayName = 'Input'
|
||
export default Input
|
||
```
|
||
|
||
`Label.tsx`:
|
||
```tsx
|
||
import type { LabelHTMLAttributes, ReactNode } from 'react'
|
||
|
||
export default function Label({
|
||
children,
|
||
className = '',
|
||
...rest
|
||
}: LabelHTMLAttributes<HTMLLabelElement> & { children: ReactNode }) {
|
||
return (
|
||
<label
|
||
className={[
|
||
'block text-sm font-medium text-[var(--color-ink)] mb-1',
|
||
className,
|
||
].join(' ')}
|
||
{...rest}
|
||
>
|
||
{children}
|
||
</label>
|
||
)
|
||
}
|
||
```
|
||
|
||
`Textarea.tsx`:
|
||
```tsx
|
||
import { forwardRef, type TextareaHTMLAttributes } from 'react'
|
||
|
||
const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement>>(
|
||
({ className = '', ...rest }, ref) => (
|
||
<textarea
|
||
ref={ref}
|
||
className={[
|
||
'w-full min-h-[96px] rounded-lg border border-[var(--color-border)] bg-white p-3 text-base text-[var(--color-ink)] placeholder:text-[var(--color-ink-muted)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
|
||
className,
|
||
].join(' ')}
|
||
{...rest}
|
||
/>
|
||
),
|
||
)
|
||
Textarea.displayName = 'Textarea'
|
||
export default Textarea
|
||
```
|
||
|
||
`Select.tsx`:
|
||
```tsx
|
||
import { forwardRef, type SelectHTMLAttributes } from 'react'
|
||
|
||
const Select = forwardRef<HTMLSelectElement, SelectHTMLAttributes<HTMLSelectElement>>(
|
||
({ className = '', children, ...rest }, ref) => (
|
||
<select
|
||
ref={ref}
|
||
className={[
|
||
'h-10 w-full rounded-lg border border-[var(--color-border)] bg-white px-3 text-base text-[var(--color-ink)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
|
||
className,
|
||
].join(' ')}
|
||
{...rest}
|
||
>
|
||
{children}
|
||
</select>
|
||
),
|
||
)
|
||
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 (
|
||
<span
|
||
className={`inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium ${map[tone]} ${className}`}
|
||
>
|
||
{children}
|
||
</span>
|
||
)
|
||
}
|
||
```
|
||
|
||
`Chip.tsx`:
|
||
```tsx
|
||
import type { ButtonHTMLAttributes, ReactNode } from 'react'
|
||
|
||
export default function Chip({
|
||
active = false,
|
||
children,
|
||
className = '',
|
||
...rest
|
||
}: ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean; children: ReactNode }) {
|
||
return (
|
||
<button
|
||
type="button"
|
||
aria-pressed={active}
|
||
className={[
|
||
'inline-flex items-center justify-center min-w-[40px] h-10 px-3 rounded-full border text-sm font-medium transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
|
||
active
|
||
? 'bg-[var(--color-accent)] text-white border-[var(--color-accent)]'
|
||
: 'bg-white text-[var(--color-ink)] border-[var(--color-border)] hover:bg-[var(--color-surface)]',
|
||
className,
|
||
].join(' ')}
|
||
{...rest}
|
||
>
|
||
{children}
|
||
</button>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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(
|
||
<Dialog open={false} onClose={() => {}} title="X">
|
||
body
|
||
</Dialog>,
|
||
)
|
||
expect(screen.queryByText('body')).toBeNull()
|
||
})
|
||
|
||
it('renders content when open=true', () => {
|
||
render(
|
||
<Dialog open={true} onClose={() => {}} title="X">
|
||
body
|
||
</Dialog>,
|
||
)
|
||
expect(screen.getByText('body')).toBeInTheDocument()
|
||
})
|
||
|
||
it('calls onClose on backdrop click', async () => {
|
||
const onClose = vi.fn()
|
||
render(
|
||
<Dialog open onClose={onClose} title="X">
|
||
body
|
||
</Dialog>,
|
||
)
|
||
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<NonNullable<DialogProps['size']>, 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 (
|
||
<AnimatePresence>
|
||
{open && (
|
||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||
<motion.div
|
||
data-testid="dialog-backdrop"
|
||
className="absolute inset-0 bg-black/40"
|
||
initial={{ opacity: 0 }}
|
||
animate={{ opacity: 1 }}
|
||
exit={{ opacity: 0 }}
|
||
transition={{ duration: 0.15 }}
|
||
onClick={onClose}
|
||
/>
|
||
<motion.div
|
||
role="dialog"
|
||
aria-modal="true"
|
||
aria-label={title}
|
||
initial={{ opacity: 0, scale: 0.96 }}
|
||
animate={{ opacity: 1, scale: 1 }}
|
||
exit={{ opacity: 0, scale: 0.96 }}
|
||
transition={{ duration: 0.18 }}
|
||
className={`relative w-full ${SIZE[size]} max-h-[90vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
|
||
>
|
||
<header className="flex items-center justify-between px-6 py-4 border-b border-[var(--color-border)]">
|
||
<h2 className="text-lg font-semibold text-[var(--color-ink)]">{title}</h2>
|
||
<button
|
||
type="button"
|
||
aria-label="Fermer"
|
||
onClick={onClose}
|
||
className="rounded-md p-1 text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)]"
|
||
>
|
||
✕
|
||
</button>
|
||
</header>
|
||
<div className="px-6 py-4">{children}</div>
|
||
</motion.div>
|
||
</div>
|
||
)}
|
||
</AnimatePresence>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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 (`<p className="text-sm text-red-700">`). 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(
|
||
<ConfigProvider>
|
||
<Brand />
|
||
</ConfigProvider>,
|
||
)
|
||
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 (
|
||
<span className={`font-serif font-semibold tracking-tight ${cls}`}>
|
||
{cfg.brandName}
|
||
</span>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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(
|
||
`<svg xmlns="http://www.w3.org/2000/svg">
|
||
<circle data-anno-id="epaule" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
|
||
data-anno-category="articulation" class="bone osteo articulation hitbox bone-epaule" />
|
||
<circle data-anno-id="epaule" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
|
||
data-anno-category="articulation" class="bone osteo articulation visible bone-epaule" />
|
||
</svg>`,
|
||
'image/svg+xml',
|
||
)
|
||
return doc.documentElement as unknown as SVGSVGElement
|
||
}),
|
||
}))
|
||
|
||
beforeEach(() => vi.clearAllMocks())
|
||
|
||
describe('AnatomyCanvas', () => {
|
||
it('renders the loaded SVG inline', async () => {
|
||
render(<AnatomyCanvas src="/x.svg" boneStates={new Map()} onZoneClick={() => {}} />)
|
||
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(<AnatomyCanvas src="/x.svg" boneStates={new Map()} onZoneClick={onZoneClick} />)
|
||
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<string, BoneState>
|
||
onZoneClick: (boneId: string) => void
|
||
className?: string
|
||
}
|
||
|
||
export default function AnatomyCanvas({
|
||
src,
|
||
boneStates,
|
||
onZoneClick,
|
||
className = '',
|
||
}: AnatomyCanvasProps) {
|
||
const containerRef = useRef<HTMLDivElement | null>(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<Element>('[data-anno-id]')
|
||
all.forEach((el) => {
|
||
const id = el.getAttribute('data-anno-id') as string
|
||
const state = boneStates.get(id)
|
||
if (state && state !== 'default') el.setAttribute('data-state', state)
|
||
else el.removeAttribute('data-state')
|
||
})
|
||
}, [boneStates])
|
||
|
||
return (
|
||
<div
|
||
data-testid="anatomy-canvas"
|
||
ref={containerRef}
|
||
className={`svg-canvas w-full h-full ${className}`}
|
||
/>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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<string, BoneState>
|
||
onZoneClick: (boneId: string, detailId: string) => void
|
||
}
|
||
|
||
export default function DetailModal({
|
||
open,
|
||
onClose,
|
||
detailSrc,
|
||
detailId,
|
||
title,
|
||
boneStates,
|
||
onZoneClick,
|
||
}: DetailModalProps) {
|
||
return (
|
||
<Dialog open={open} onClose={onClose} title={title} size="xl">
|
||
<div className="aspect-[4/3] w-full">
|
||
<AnatomyCanvas
|
||
src={detailSrc}
|
||
boneStates={boneStates}
|
||
onZoneClick={(id) => onZoneClick(id, detailId)}
|
||
/>
|
||
</div>
|
||
<p className="mt-4 text-sm text-[var(--color-ink-muted)]">
|
||
Cliquez sur les zones pour les ajouter à l'observation en cours.
|
||
</p>
|
||
</Dialog>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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(
|
||
<VertebraPicker
|
||
open
|
||
onClose={() => {}}
|
||
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(
|
||
<VertebraPicker
|
||
open
|
||
onClose={() => {}}
|
||
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<VertebralRegion, string> = {
|
||
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<Vertebra[]>(initial)
|
||
const [activeRegion, setActiveRegion] = useState<VertebralRegion>('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 (
|
||
<Dialog open={open} onClose={onClose} title={title} size="lg">
|
||
<div role="tablist" className="flex flex-wrap gap-2 mb-4">
|
||
{(Object.keys(REGION_LABELS) as VertebralRegion[]).map((r) => (
|
||
<button
|
||
key={r}
|
||
role="tab"
|
||
aria-selected={activeRegion === r}
|
||
onClick={() => setActiveRegion(r)}
|
||
className={[
|
||
'rounded-full px-4 py-1.5 text-sm font-medium border',
|
||
activeRegion === r
|
||
? 'bg-[var(--color-accent)] text-white border-[var(--color-accent)]'
|
||
: 'bg-white text-[var(--color-ink)] border-[var(--color-border)]',
|
||
].join(' ')}
|
||
>
|
||
{REGION_LABELS[r]}
|
||
</button>
|
||
))}
|
||
</div>
|
||
|
||
<div className="flex flex-wrap gap-2 mb-4 max-h-64 overflow-auto">
|
||
{Array.from({ length: count }, (_, k) => k + 1).map((i) => (
|
||
<Chip
|
||
key={i}
|
||
active={has(activeRegion, i)}
|
||
onClick={() => toggle(activeRegion, i)}
|
||
>
|
||
{activeRegion}{i}
|
||
</Chip>
|
||
))}
|
||
</div>
|
||
|
||
<div className="flex flex-wrap items-center gap-2 mb-6">
|
||
<Button variant="ghost" size="sm" onClick={() => all(activeRegion, count)}>Tout cocher</Button>
|
||
<Button variant="ghost" size="sm" onClick={() => none(activeRegion)}>Tout décocher</Button>
|
||
</div>
|
||
|
||
<div className="flex justify-end gap-2">
|
||
<Button variant="ghost" onClick={onClose}>Annuler</Button>
|
||
<Button onClick={() => onConfirm(selected)}>Valider</Button>
|
||
</div>
|
||
</Dialog>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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(
|
||
<PathologyPicker
|
||
pool={POOL}
|
||
speciesId="equine"
|
||
boneIds={['epaule']}
|
||
selected={[]}
|
||
onChange={() => {}}
|
||
/>,
|
||
)
|
||
expect(screen.getByLabelText('Aïe')).toBeInTheDocument()
|
||
expect(screen.queryByLabelText('Aïe-aïe')).toBeNull()
|
||
})
|
||
|
||
it('toggles selection', async () => {
|
||
const onChange = vi.fn()
|
||
render(
|
||
<PathologyPicker
|
||
pool={POOL}
|
||
speciesId="equine"
|
||
boneIds={['epaule']}
|
||
selected={[]}
|
||
onChange={onChange}
|
||
/>,
|
||
)
|
||
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 (
|
||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||
Aucune pathologie de référence pour ces zones. Ajoutez-en une en texte libre ci-dessous.
|
||
</p>
|
||
)
|
||
}
|
||
|
||
return (
|
||
<ul className="space-y-2 max-h-64 overflow-auto pr-1">
|
||
{filtered.map((p) => (
|
||
<li key={p.id}>
|
||
<label className="flex items-start gap-2 cursor-pointer">
|
||
<input
|
||
type="checkbox"
|
||
checked={selected.includes(p.id)}
|
||
onChange={() => toggle(p.id)}
|
||
className="mt-1 accent-[var(--color-accent)]"
|
||
aria-label={p.labelFr}
|
||
/>
|
||
<div>
|
||
<div className="text-sm font-medium text-[var(--color-ink)]">{p.labelFr}</div>
|
||
<div className="text-xs text-[var(--color-ink-muted)]">{p.description}</div>
|
||
</div>
|
||
</label>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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 (
|
||
<div className="space-y-2">
|
||
<div className="flex gap-2">
|
||
<Input
|
||
value={v}
|
||
onChange={(e) => setV(e.target.value)}
|
||
placeholder="Pathologie additionnelle (texte libre)"
|
||
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); add() } }}
|
||
aria-label="Pathologie libre"
|
||
/>
|
||
<Button onClick={add} variant="secondary">Ajouter</Button>
|
||
</div>
|
||
{items.length > 0 && (
|
||
<ul className="flex flex-wrap gap-2">
|
||
{items.map((it, i) => (
|
||
<li key={`${it}-${i}`}>
|
||
<Badge tone="accent" className="gap-1">
|
||
{it}
|
||
<button
|
||
type="button"
|
||
aria-label={`Retirer ${it}`}
|
||
onClick={() => remove(i)}
|
||
className="ml-1 text-[var(--color-accent-strong)] hover:text-[var(--color-danger)]"
|
||
>
|
||
✕
|
||
</button>
|
||
</Badge>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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<Severity, string> = {
|
||
'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 (
|
||
<div role="radiogroup" aria-label="Sévérité" className="flex gap-2">
|
||
{SEVERITIES.map((s) => (
|
||
<button
|
||
key={s}
|
||
role="radio"
|
||
aria-checked={value === s}
|
||
onClick={() => onChange(value === s ? undefined : s)}
|
||
className={[
|
||
'rounded-full border px-3 py-1.5 text-sm font-medium capitalize',
|
||
value === s
|
||
? `bg-white ${COLORS[s]}`
|
||
: 'border-[var(--color-border)] text-[var(--color-ink-muted)]',
|
||
].join(' ')}
|
||
>
|
||
{s}
|
||
</button>
|
||
))}
|
||
</div>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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 (
|
||
<Card
|
||
className={[
|
||
'cursor-pointer p-4 transition',
|
||
active ? 'ring-2 ring-[var(--color-accent)]' : 'hover:bg-[var(--color-surface-strong)]',
|
||
].join(' ')}
|
||
>
|
||
<div className="flex items-start justify-between gap-3">
|
||
<button
|
||
type="button"
|
||
onClick={onSelect}
|
||
className="flex-1 text-left"
|
||
aria-label={`Sélectionner l'observation ${index + 1}`}
|
||
>
|
||
<div className="flex items-center gap-2 mb-2">
|
||
<Badge tone="neutral">Observation #{index + 1}</Badge>
|
||
{observation.severity && (
|
||
<Badge tone={observation.severity === 'sévère' ? 'danger' : observation.severity === 'modérée' ? 'warn' : 'neutral'}>
|
||
{observation.severity}
|
||
</Badge>
|
||
)}
|
||
</div>
|
||
<div className="text-sm text-[var(--color-ink-muted)]">
|
||
{zoneCount} zone{zoneCount > 1 ? 's' : ''} · {patCount} pathologie{patCount > 1 ? 's' : ''}
|
||
</div>
|
||
{observation.comment && (
|
||
<p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]">{observation.comment}</p>
|
||
)}
|
||
</button>
|
||
<div className="flex flex-col gap-1">
|
||
<Button size="sm" variant="ghost" disabled={!canMoveUp} onClick={onMoveUp} aria-label="Monter">↑</Button>
|
||
<Button size="sm" variant="ghost" disabled={!canMoveDown} onClick={onMoveDown} aria-label="Descendre">↓</Button>
|
||
<Button size="sm" variant="ghost" onClick={onDelete} aria-label="Supprimer">🗑</Button>
|
||
</div>
|
||
</div>
|
||
</Card>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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 (
|
||
<div className="space-y-3">
|
||
<div className="flex items-center justify-between">
|
||
<h2 className="font-serif text-xl text-[var(--color-ink)]">Observations</h2>
|
||
<Button size="sm" onClick={onAdd}>+ Nouvelle observation</Button>
|
||
</div>
|
||
{observations.length === 0 ? (
|
||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||
Aucune observation. Cliquez sur "+ Nouvelle observation" puis sur les zones du schéma.
|
||
</p>
|
||
) : (
|
||
<ul className="space-y-2">
|
||
{observations.map((obs, i) => (
|
||
<li key={obs.id}>
|
||
<ObservationCard
|
||
observation={obs}
|
||
index={i}
|
||
active={i === activeIndex}
|
||
onSelect={() => onSelect(i)}
|
||
onDelete={() => onDelete(i)}
|
||
onMoveUp={() => onMoveUp(i)}
|
||
onMoveDown={() => onMoveDown(i)}
|
||
canMoveUp={i > 0}
|
||
canMoveDown={i < observations.length - 1}
|
||
/>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
</div>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **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<string, Bone>
|
||
speciesId: string
|
||
pathologyPool: Pathology[]
|
||
onChange: (next: Observation) => void
|
||
onOpenVertebraPicker: (zoneIndex: number) => void
|
||
onRemoveZone: (zoneIndex: number) => void
|
||
}
|
||
|
||
function describeZone(z: ObservationZone, bones: Map<string, Bone>): 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 (
|
||
<div className="space-y-6">
|
||
<section>
|
||
<Label>Zones sélectionnées</Label>
|
||
{observation.zones.length === 0 ? (
|
||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||
Cliquez sur les zones du schéma pour les ajouter à cette observation.
|
||
</p>
|
||
) : (
|
||
<ul className="flex flex-wrap gap-2">
|
||
{observation.zones.map((z, i) => {
|
||
const b = bones.get(z.boneId)
|
||
const isSpine = b?.category === 'spine-zone'
|
||
return (
|
||
<li key={`${z.boneId}-${i}`}>
|
||
<Badge tone="accent" className="gap-2">
|
||
{describeZone(z, bones)}
|
||
{isSpine && (
|
||
<button
|
||
type="button"
|
||
onClick={() => onOpenVertebraPicker(i)}
|
||
className="underline text-xs text-[var(--color-accent-strong)]"
|
||
>
|
||
Préciser…
|
||
</button>
|
||
)}
|
||
<button
|
||
type="button"
|
||
aria-label={`Retirer ${b?.fr ?? z.boneId}`}
|
||
onClick={() => onRemoveZone(i)}
|
||
className="ml-1 text-[var(--color-accent-strong)]"
|
||
>
|
||
✕
|
||
</button>
|
||
</Badge>
|
||
</li>
|
||
)
|
||
})}
|
||
</ul>
|
||
)}
|
||
</section>
|
||
|
||
<section>
|
||
<Label>Pathologies (référence)</Label>
|
||
<PathologyPicker
|
||
pool={pathologyPool}
|
||
speciesId={speciesId}
|
||
boneIds={zoneBoneIds}
|
||
selected={observation.pathologyIds}
|
||
onChange={(ids) => onChange({ ...observation, pathologyIds: ids })}
|
||
/>
|
||
</section>
|
||
|
||
<section>
|
||
<Label>Pathologies (texte libre)</Label>
|
||
<FreeTextPathologyInput
|
||
items={observation.freeTextPathologies}
|
||
onChange={(items) => onChange({ ...observation, freeTextPathologies: items })}
|
||
/>
|
||
</section>
|
||
|
||
<section>
|
||
<Label>Sévérité</Label>
|
||
<SeveritySelector
|
||
value={observation.severity}
|
||
onChange={(s) => onChange({ ...observation, severity: s })}
|
||
/>
|
||
</section>
|
||
|
||
<section>
|
||
<Label htmlFor="obs-comment">Commentaire</Label>
|
||
<Textarea
|
||
id="obs-comment"
|
||
value={observation.comment}
|
||
onChange={(e) => onChange({ ...observation, comment: e.target.value })}
|
||
placeholder="Notes cliniques détaillées…"
|
||
/>
|
||
</section>
|
||
</div>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/components/observation/ObservationEditor.tsx
|
||
git commit -m "feat(observation): ObservationEditor wires zones + pathologies + severity + comment"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 14 — Report forms
|
||
|
||
### Task 14.1 — PractitionerForm
|
||
|
||
**Files:**
|
||
- Modify: `src/components/report/PractitionerForm.tsx`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```tsx
|
||
import type { Practitioner } from '@/domain/schema/practitioner'
|
||
import Label from '@/components/ui/Label'
|
||
import Input from '@/components/ui/Input'
|
||
|
||
export interface PractitionerFormProps {
|
||
value: Practitioner
|
||
onChange: (next: Practitioner) => void
|
||
}
|
||
|
||
export default function PractitionerForm({ value, onChange }: PractitionerFormProps) {
|
||
const set = (patch: Partial<Practitioner>) => onChange({ ...value, ...patch })
|
||
return (
|
||
<fieldset className="space-y-3">
|
||
<legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">Praticien</legend>
|
||
<div>
|
||
<Label htmlFor="prac-name">Nom complet *</Label>
|
||
<Input id="prac-name" required value={value.name} onChange={(e) => set({ name: e.target.value })} />
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="prac-cabinet">Cabinet / clinique</Label>
|
||
<Input id="prac-cabinet" value={value.cabinet ?? ''} onChange={(e) => set({ cabinet: e.target.value || undefined })} />
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="prac-contact">Contact (téléphone, email…)</Label>
|
||
<Input id="prac-contact" value={value.contact ?? ''} onChange={(e) => set({ contact: e.target.value || undefined })} />
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="prac-siret">SIRET</Label>
|
||
<Input id="prac-siret" value={value.siret ?? ''} onChange={(e) => set({ siret: e.target.value || undefined })} />
|
||
</div>
|
||
</fieldset>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/components/report/PractitionerForm.tsx
|
||
git commit -m "feat(report): PractitionerForm with required name + optional fields"
|
||
```
|
||
|
||
### Task 14.2 — AnimalForm
|
||
|
||
**Files:**
|
||
- Modify: `src/components/report/AnimalForm.tsx`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```tsx
|
||
import type { Animal, Owner } from '@/domain/schema/animal'
|
||
import Label from '@/components/ui/Label'
|
||
import Input from '@/components/ui/Input'
|
||
import Select from '@/components/ui/Select'
|
||
import { getAllSpecies } from '@/domain/species/registry'
|
||
|
||
export interface AnimalFormProps {
|
||
animal: Animal
|
||
owner: Owner
|
||
onChangeAnimal: (next: Animal) => void
|
||
onChangeOwner: (next: Owner) => void
|
||
}
|
||
|
||
export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwner }: AnimalFormProps) {
|
||
const species = getAllSpecies()
|
||
const setA = (patch: Partial<Animal>) => onChangeAnimal({ ...animal, ...patch })
|
||
return (
|
||
<fieldset className="space-y-3">
|
||
<legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">Animal & propriétaire</legend>
|
||
<div>
|
||
<Label htmlFor="an-species">Espèce *</Label>
|
||
<Select
|
||
id="an-species"
|
||
value={animal.speciesId}
|
||
onChange={(e) => setA({ speciesId: e.target.value })}
|
||
>
|
||
{species.map((s) => (
|
||
<option key={s.id} value={s.id}>{s.labelFr}</option>
|
||
))}
|
||
</Select>
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="an-name">Nom de l'animal *</Label>
|
||
<Input id="an-name" required value={animal.name} onChange={(e) => setA({ name: e.target.value })} />
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="an-breed">Race</Label>
|
||
<Input id="an-breed" value={animal.breed ?? ''} onChange={(e) => setA({ breed: e.target.value || undefined })} />
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="an-age">Âge</Label>
|
||
<Input id="an-age" value={animal.age ?? ''} onChange={(e) => setA({ age: e.target.value || undefined })} />
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="own-name">Nom du propriétaire *</Label>
|
||
<Input id="own-name" required value={owner.name} onChange={(e) => onChangeOwner({ name: e.target.value })} />
|
||
</div>
|
||
</fieldset>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/components/report/AnimalForm.tsx
|
||
git commit -m "feat(report): AnimalForm + owner name with species select"
|
||
```
|
||
|
||
### Task 14.3 — ConclusionPanel + NextAppointmentPicker
|
||
|
||
**Files:**
|
||
- Modify: `src/components/report/ConclusionPanel.tsx`
|
||
- Modify: `src/components/report/NextAppointmentPicker.tsx`
|
||
|
||
- [ ] **Step 1:** NextAppointmentPicker
|
||
```tsx
|
||
import type { Report } from '@/domain/schema/report'
|
||
import Input from '@/components/ui/Input'
|
||
import Label from '@/components/ui/Label'
|
||
|
||
export interface NextAppointmentPickerProps {
|
||
value: Report['nextAppointment']
|
||
onChange: (next: Report['nextAppointment']) => void
|
||
}
|
||
|
||
export default function NextAppointmentPicker({ value, onChange }: NextAppointmentPickerProps) {
|
||
const kind = value?.kind ?? 'date'
|
||
return (
|
||
<div className="space-y-2">
|
||
<Label>Prochain rendez-vous</Label>
|
||
<div className="flex gap-2 mb-2">
|
||
<label className="text-sm flex items-center gap-1">
|
||
<input type="radio" checked={kind === 'date'} onChange={() => onChange({ kind: 'date', date: '' })} />
|
||
Date
|
||
</label>
|
||
<label className="text-sm flex items-center gap-1">
|
||
<input type="radio" checked={kind === 'period'} onChange={() => onChange({ kind: 'period', text: '' })} />
|
||
Période libre
|
||
</label>
|
||
<label className="text-sm flex items-center gap-1">
|
||
<input type="radio" checked={value === undefined} onChange={() => onChange(undefined)} />
|
||
Aucun
|
||
</label>
|
||
</div>
|
||
{value?.kind === 'date' && (
|
||
<Input type="date" value={value.date} onChange={(e) => onChange({ kind: 'date', date: e.target.value })} />
|
||
)}
|
||
{value?.kind === 'period' && (
|
||
<Input value={value.text} placeholder="ex. dans 3 semaines" onChange={(e) => onChange({ kind: 'period', text: e.target.value })} />
|
||
)}
|
||
</div>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** ConclusionPanel
|
||
```tsx
|
||
import type { Report } from '@/domain/schema/report'
|
||
import Label from '@/components/ui/Label'
|
||
import Textarea from '@/components/ui/Textarea'
|
||
import NextAppointmentPicker from './NextAppointmentPicker'
|
||
|
||
export interface ConclusionPanelProps {
|
||
conclusion: string
|
||
recommendations: string
|
||
nextAppointment: Report['nextAppointment']
|
||
onChangeConclusion: (s: string) => void
|
||
onChangeRecommendations: (s: string) => void
|
||
onChangeNextAppointment: (n: Report['nextAppointment']) => void
|
||
}
|
||
|
||
export default function ConclusionPanel({
|
||
conclusion,
|
||
recommendations,
|
||
nextAppointment,
|
||
onChangeConclusion,
|
||
onChangeRecommendations,
|
||
onChangeNextAppointment,
|
||
}: ConclusionPanelProps) {
|
||
return (
|
||
<section className="space-y-4">
|
||
<h2 className="font-serif text-xl text-[var(--color-ink)]">Conclusion & recommandations</h2>
|
||
<div>
|
||
<Label htmlFor="conclusion">Conclusion</Label>
|
||
<Textarea id="conclusion" value={conclusion} onChange={(e) => onChangeConclusion(e.target.value)} />
|
||
</div>
|
||
<div>
|
||
<Label htmlFor="recommendations">Recommandations</Label>
|
||
<Textarea id="recommendations" value={recommendations} onChange={(e) => onChangeRecommendations(e.target.value)} />
|
||
</div>
|
||
<NextAppointmentPicker value={nextAppointment} onChange={onChangeNextAppointment} />
|
||
</section>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 3:** Commit
|
||
```bash
|
||
git add src/components/report/ConclusionPanel.tsx src/components/report/NextAppointmentPicker.tsx
|
||
git commit -m "feat(report): ConclusionPanel + NextAppointmentPicker (date | period | none)"
|
||
```
|
||
|
||
### Task 14.4 — ReportHeader
|
||
|
||
**Files:**
|
||
- Modify: `src/components/report/ReportHeader.tsx`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```tsx
|
||
import type { Report } from '@/domain/schema/report'
|
||
import Brand from '@/components/brand/Brand'
|
||
import { formatDateFr } from '@/lib/dates'
|
||
|
||
export interface ReportHeaderProps {
|
||
report: Report
|
||
}
|
||
|
||
export default function ReportHeader({ report }: ReportHeaderProps) {
|
||
return (
|
||
<header className="flex items-center justify-between gap-4 px-6 py-3 border-b border-[var(--color-border)] bg-[var(--color-surface)]">
|
||
<Brand />
|
||
<div className="text-sm text-right text-[var(--color-ink-muted)]">
|
||
<div className="text-[var(--color-ink)] font-medium">
|
||
{report.animal.name} · {report.owner.name}
|
||
</div>
|
||
<div>{formatDateFr(report.date)}</div>
|
||
</div>
|
||
</header>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/components/report/ReportHeader.tsx
|
||
git commit -m "feat(report): ReportHeader with brand + animal/owner/date"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 15 — Routes
|
||
|
||
### Task 15.1 — HomeRoute
|
||
|
||
**Files:**
|
||
- Modify: `src/app/routes/HomeRoute.tsx`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```tsx
|
||
import { useNavigate } from 'react-router-dom'
|
||
import { useRef, useState } from 'react'
|
||
import Brand from '@/components/brand/Brand'
|
||
import Button from '@/components/ui/Button'
|
||
import Card from '@/components/ui/Card'
|
||
import { useConfig } from '@/app/providers/ConfigProvider'
|
||
import { importReportFromPdf, ImportError } from '@/pdf/import'
|
||
import { useReportStore } from '@/state/reportStore'
|
||
|
||
export default function HomeRoute() {
|
||
const navigate = useNavigate()
|
||
const cfg = useConfig()
|
||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||
const hydrate = useReportStore((s) => s.hydrateReport)
|
||
const [error, setError] = useState<string | null>(null)
|
||
const [busy, setBusy] = useState(false)
|
||
|
||
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||
const file = e.target.files?.[0]
|
||
if (!file) return
|
||
setBusy(true)
|
||
setError(null)
|
||
try {
|
||
const bytes = new Uint8Array(await file.arrayBuffer())
|
||
const report = await importReportFromPdf(bytes)
|
||
hydrate(report)
|
||
navigate('/editor')
|
||
} catch (err) {
|
||
setError(err instanceof ImportError ? err.message : "Erreur de lecture du PDF.")
|
||
} finally {
|
||
setBusy(false)
|
||
if (fileRef.current) fileRef.current.value = ''
|
||
}
|
||
}
|
||
|
||
return (
|
||
<main className="min-h-screen flex flex-col">
|
||
<header className="px-6 py-4 border-b border-[var(--color-border)] flex items-center justify-between">
|
||
<Brand size="lg" />
|
||
<span className="text-sm text-[var(--color-ink-muted)]">{cfg.tagline}</span>
|
||
</header>
|
||
<section className="flex-1 grid place-items-center px-6">
|
||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
||
<Card className="p-6 space-y-4">
|
||
<h2 className="font-serif text-2xl">Nouveau bilan</h2>
|
||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||
Démarrer un nouveau bilan d'ostéopathie sur un animal.
|
||
</p>
|
||
<Button onClick={() => navigate('/new')} size="lg">Commencer</Button>
|
||
</Card>
|
||
<Card className="p-6 space-y-4">
|
||
<h2 className="font-serif text-2xl">Importer un PDF</h2>
|
||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||
Reprendre un bilan précédent généré par cette application pour effectuer un suivi.
|
||
</p>
|
||
<input ref={fileRef} type="file" accept="application/pdf,.pdf" className="hidden" onChange={onPickFile} />
|
||
<Button variant="secondary" size="lg" onClick={() => fileRef.current?.click()} disabled={busy}>
|
||
{busy ? 'Lecture…' : 'Choisir un PDF'}
|
||
</Button>
|
||
{error && <p className="text-sm text-red-700">{error}</p>}
|
||
</Card>
|
||
</div>
|
||
</section>
|
||
</main>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/app/routes/HomeRoute.tsx
|
||
git commit -m "feat(home): HomeRoute with new + import PDF flows"
|
||
```
|
||
|
||
### Task 15.2 — NewReportRoute
|
||
|
||
**Files:**
|
||
- Modify: `src/app/routes/NewReportRoute.tsx`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```tsx
|
||
import { useEffect, useState } from 'react'
|
||
import { useNavigate } from 'react-router-dom'
|
||
import PractitionerForm from '@/components/report/PractitionerForm'
|
||
import AnimalForm from '@/components/report/AnimalForm'
|
||
import Brand from '@/components/brand/Brand'
|
||
import Button from '@/components/ui/Button'
|
||
import Input from '@/components/ui/Input'
|
||
import Label from '@/components/ui/Label'
|
||
import { todayIso } from '@/lib/dates'
|
||
import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache'
|
||
import { useReportStore } from '@/state/reportStore'
|
||
|
||
export default function NewReportRoute() {
|
||
const navigate = useNavigate()
|
||
const initReport = useReportStore((s) => s.initReport)
|
||
|
||
const [practitioner, setPractitioner] = useState({ name: '' })
|
||
const [animal, setAnimal] = useState({ speciesId: 'equine', name: '' })
|
||
const [owner, setOwner] = useState({ name: '' })
|
||
const [date, setDate] = useState(todayIso())
|
||
|
||
useEffect(() => {
|
||
const cached = readCachedPractitioner()
|
||
if (cached) setPractitioner(cached)
|
||
}, [])
|
||
|
||
const canSubmit = practitioner.name.trim() && animal.name.trim() && owner.name.trim()
|
||
|
||
function submit() {
|
||
if (!canSubmit) return
|
||
writeCachedPractitioner(practitioner)
|
||
initReport({
|
||
date,
|
||
practitioner,
|
||
animal,
|
||
owner,
|
||
observations: [],
|
||
conclusion: '',
|
||
recommendations: '',
|
||
})
|
||
navigate('/editor')
|
||
}
|
||
|
||
return (
|
||
<main className="min-h-screen">
|
||
<header className="px-6 py-4 border-b border-[var(--color-border)] flex items-center justify-between">
|
||
<Brand />
|
||
<Button variant="ghost" onClick={() => navigate('/')}>← Accueil</Button>
|
||
</header>
|
||
<div className="max-w-3xl mx-auto px-6 py-8 space-y-8">
|
||
<h1 className="font-serif text-3xl">Nouveau bilan</h1>
|
||
<div>
|
||
<Label htmlFor="date">Date du bilan</Label>
|
||
<Input id="date" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
|
||
</div>
|
||
<PractitionerForm value={practitioner} onChange={setPractitioner} />
|
||
<AnimalForm animal={animal} owner={owner} onChangeAnimal={setAnimal} onChangeOwner={setOwner} />
|
||
<div className="flex gap-3 justify-end">
|
||
<Button variant="ghost" onClick={() => navigate('/')}>Annuler</Button>
|
||
<Button disabled={!canSubmit} onClick={submit}>Démarrer le bilan</Button>
|
||
</div>
|
||
</div>
|
||
</main>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/app/routes/NewReportRoute.tsx
|
||
git commit -m "feat(new): NewReportRoute wires forms + practitioner cache"
|
||
```
|
||
|
||
### Task 15.3 — EditorRoute
|
||
|
||
**Files:**
|
||
- Modify: `src/app/routes/EditorRoute.tsx`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```tsx
|
||
import { useEffect, useMemo, useState } from 'react'
|
||
import { useNavigate } from 'react-router-dom'
|
||
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
|
||
import DetailModal from '@/components/canvas/DetailModal'
|
||
import ObservationList from '@/components/observation/ObservationList'
|
||
import ObservationEditor from '@/components/observation/ObservationEditor'
|
||
import VertebraPicker from '@/components/observation/VertebraPicker'
|
||
import ConclusionPanel from '@/components/report/ConclusionPanel'
|
||
import ReportHeader from '@/components/report/ReportHeader'
|
||
import Button from '@/components/ui/Button'
|
||
import { useReportStore } from '@/state/reportStore'
|
||
import { getSpecies } from '@/domain/species/registry'
|
||
import { loadSvg } from '@/anatomy/svgLoader'
|
||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||
import type { Bone, BoneState } from '@/anatomy/types'
|
||
import type { Observation, ObservationZone } from '@/domain/schema/observation'
|
||
import type { Pathology } from '@/domain/schema/pathology'
|
||
import { exportReportToPdf } from '@/pdf/export'
|
||
|
||
export default function EditorRoute() {
|
||
const navigate = useNavigate()
|
||
const report = useReportStore((s) => s.report)
|
||
const activeIndex = useReportStore((s) => s.activeObservationIndex)
|
||
const addObservation = useReportStore((s) => s.addObservation)
|
||
const updateObservation = useReportStore((s) => s.updateObservation)
|
||
const removeObservation = useReportStore((s) => s.removeObservation)
|
||
const moveObservationUp = useReportStore((s) => s.moveObservationUp)
|
||
const moveObservationDown = useReportStore((s) => s.moveObservationDown)
|
||
const setActiveObservation = useReportStore((s) => s.setActiveObservation)
|
||
const setConclusion = useReportStore((s) => s.setConclusion)
|
||
const setRecommendations = useReportStore((s) => s.setRecommendations)
|
||
const setNextAppointment = useReportStore((s) => s.setNextAppointment)
|
||
|
||
const [bones, setBones] = useState<Map<string, Bone>>(new Map())
|
||
const [pathologies, setPathologies] = useState<Pathology[]>([])
|
||
const [detail, setDetail] = useState<{ id: string; src: string; title: string } | null>(null)
|
||
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
|
||
const [exporting, setExporting] = useState(false)
|
||
|
||
useEffect(() => {
|
||
if (!report) navigate('/')
|
||
}, [report, navigate])
|
||
|
||
const species = useMemo(
|
||
() => (report ? getSpecies(report.animal.speciesId) : undefined),
|
||
[report],
|
||
)
|
||
|
||
useEffect(() => {
|
||
if (!species) return
|
||
loadSvg(species.mainSvg).then((root) => setBones(parseSvgBones(root)))
|
||
species.pathologies().then((m) => setPathologies(m.default))
|
||
}, [species])
|
||
|
||
useEffect(() => {
|
||
if (report && report.observations.length === 0) addObservation()
|
||
}, [report?.observations.length, addObservation])
|
||
|
||
const activeObs = report?.observations[activeIndex]
|
||
|
||
const boneStates = useMemo<Map<string, BoneState>>(() => {
|
||
const map = new Map<string, BoneState>()
|
||
if (!report) return map
|
||
report.observations.forEach((obs, i) => {
|
||
obs.zones.forEach((z) => {
|
||
const prev = map.get(z.boneId)
|
||
if (i === activeIndex) {
|
||
map.set(z.boneId, prev === undefined ? 'current' : 'multi')
|
||
} else if (prev === undefined) {
|
||
map.set(z.boneId, 'linked')
|
||
} else {
|
||
map.set(z.boneId, 'multi')
|
||
}
|
||
})
|
||
})
|
||
return map
|
||
}, [report, activeIndex])
|
||
|
||
function onZoneClick(boneId: string, detailSourceId?: string) {
|
||
if (!report || !activeObs) return
|
||
const bone = bones.get(boneId)
|
||
if (!bone) return
|
||
|
||
if (bone.opensDetail && species?.details[bone.opensDetail]) {
|
||
setDetail({
|
||
id: bone.opensDetail,
|
||
src: species.details[bone.opensDetail],
|
||
title: bone.fr,
|
||
})
|
||
return
|
||
}
|
||
|
||
const newZone: ObservationZone = {
|
||
boneId,
|
||
...(detailSourceId ? { detailSourceId } : {}),
|
||
}
|
||
const exists = activeObs.zones.some(
|
||
(z) => z.boneId === boneId && z.detailSourceId === detailSourceId,
|
||
)
|
||
const nextZones = exists
|
||
? activeObs.zones.filter(
|
||
(z) => !(z.boneId === boneId && z.detailSourceId === detailSourceId),
|
||
)
|
||
: [...activeObs.zones, newZone]
|
||
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
|
||
|
||
if (!exists && bone.category === 'spine-zone') {
|
||
setVertebraTarget(nextZones.length - 1)
|
||
}
|
||
}
|
||
|
||
async function onExport() {
|
||
if (!report) return
|
||
setExporting(true)
|
||
try {
|
||
const bytes = await exportReportToPdf(report)
|
||
const blob = new Blob([bytes], { type: 'application/pdf' })
|
||
const url = URL.createObjectURL(blob)
|
||
const a = document.createElement('a')
|
||
a.href = url
|
||
a.download = `bilan-${report.animal.name}-${report.date}.pdf`
|
||
a.click()
|
||
URL.revokeObjectURL(url)
|
||
} finally {
|
||
setExporting(false)
|
||
}
|
||
}
|
||
|
||
if (!report || !species || !activeObs) return null
|
||
|
||
return (
|
||
<main className="min-h-screen flex flex-col">
|
||
<ReportHeader report={report} />
|
||
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-6 p-6">
|
||
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden">
|
||
<AnatomyCanvas
|
||
src={species.mainSvg}
|
||
boneStates={boneStates}
|
||
onZoneClick={(id) => onZoneClick(id)}
|
||
/>
|
||
</section>
|
||
<section className="space-y-6">
|
||
<ObservationList
|
||
observations={report.observations}
|
||
activeIndex={activeIndex}
|
||
onSelect={setActiveObservation}
|
||
onAdd={addObservation}
|
||
onDelete={removeObservation}
|
||
onMoveUp={moveObservationUp}
|
||
onMoveDown={moveObservationDown}
|
||
/>
|
||
<ObservationEditor
|
||
observation={activeObs}
|
||
bones={bones}
|
||
speciesId={species.id}
|
||
pathologyPool={pathologies}
|
||
onChange={(next: Observation) => updateObservation(activeIndex, next)}
|
||
onOpenVertebraPicker={(zoneIndex) => setVertebraTarget(zoneIndex)}
|
||
onRemoveZone={(zoneIndex) => {
|
||
const zones = activeObs.zones.filter((_, i) => i !== zoneIndex)
|
||
updateObservation(activeIndex, { ...activeObs, zones })
|
||
}}
|
||
/>
|
||
<ConclusionPanel
|
||
conclusion={report.conclusion}
|
||
recommendations={report.recommendations}
|
||
nextAppointment={report.nextAppointment}
|
||
onChangeConclusion={setConclusion}
|
||
onChangeRecommendations={setRecommendations}
|
||
onChangeNextAppointment={setNextAppointment}
|
||
/>
|
||
<div className="flex justify-end">
|
||
<Button onClick={onExport} disabled={exporting}>
|
||
{exporting ? 'Génération…' : 'Exporter en PDF'}
|
||
</Button>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
|
||
{detail && (
|
||
<DetailModal
|
||
open
|
||
onClose={() => setDetail(null)}
|
||
detailSrc={detail.src}
|
||
detailId={detail.id}
|
||
title={`Détail — ${detail.title}`}
|
||
boneStates={boneStates}
|
||
onZoneClick={(id, did) => onZoneClick(id, did)}
|
||
/>
|
||
)}
|
||
|
||
{vertebraTarget !== null && activeObs.zones[vertebraTarget] && (
|
||
<VertebraPicker
|
||
open
|
||
onClose={() => setVertebraTarget(null)}
|
||
onConfirm={(vertebrae) => {
|
||
const next = [...activeObs.zones]
|
||
next[vertebraTarget] = { ...next[vertebraTarget], vertebrae }
|
||
updateObservation(activeIndex, { ...activeObs, zones: next })
|
||
setVertebraTarget(null)
|
||
}}
|
||
initial={activeObs.zones[vertebraTarget].vertebrae ?? []}
|
||
formula={species.vertebralFormula}
|
||
title={`Préciser les vertèbres — ${bones.get(activeObs.zones[vertebraTarget].boneId)?.fr ?? ''}`}
|
||
/>
|
||
)}
|
||
</main>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Verify `pnpm typecheck && pnpm build` clean
|
||
|
||
- [ ] **Step 3:** Commit
|
||
```bash
|
||
git add src/app/routes/EditorRoute.tsx
|
||
git commit -m "feat(editor): wire canvas + observation panel + conclusion + export"
|
||
```
|
||
|
||
### Task 15.4 — NotFoundRoute
|
||
|
||
**Files:**
|
||
- Modify: `src/app/routes/NotFoundRoute.tsx`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```tsx
|
||
import { useNavigate } from 'react-router-dom'
|
||
import Button from '@/components/ui/Button'
|
||
|
||
export default function NotFoundRoute() {
|
||
const navigate = useNavigate()
|
||
return (
|
||
<main className="min-h-screen grid place-items-center">
|
||
<div className="text-center space-y-4">
|
||
<h1 className="font-serif text-4xl">Page introuvable</h1>
|
||
<p className="text-[var(--color-ink-muted)]">Le chemin demandé n'existe pas.</p>
|
||
<Button onClick={() => navigate('/')}>Retour à l'accueil</Button>
|
||
</div>
|
||
</main>
|
||
)
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/app/routes/NotFoundRoute.tsx
|
||
git commit -m "feat(app): NotFoundRoute"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 16 — Pathology DB integrity (equine, content deferred)
|
||
|
||
> **Plan-review decision: pathology DB authoring is DEFERRED to post-MVP.**
|
||
> Reason: rigorous source-cited content is best produced by the client osteo
|
||
> (or a future Phase 2 multi-user authoring tool), once the user-account
|
||
> architecture is fixed. v1 ships an empty array. The pathology picker shows
|
||
> the "aucune pathologie de référence" empty-state; praticien adds entries
|
||
> via free-text. The integrity contract is preserved so future entries land
|
||
> cleanly.
|
||
|
||
### Task 16.1 — Lock the integrity contract
|
||
|
||
**Files:**
|
||
- Keep: `src/domain/species/equine/pathologies.ts` exporting `[]` (unchanged).
|
||
- Create: `tests/unit/species.equinePathologies.test.ts`
|
||
|
||
- [ ] **Step 1:** Write the integrity test
|
||
```ts
|
||
import { describe, it, expect } from 'vitest'
|
||
import { PathologySchema } from '@/domain/schema/pathology'
|
||
import EQUINE_PATHOLOGIES from '@/domain/species/equine/pathologies'
|
||
|
||
describe('equine pathologies database', () => {
|
||
it('has between 0 and 100 entries (empty allowed for v1)', () => {
|
||
expect(EQUINE_PATHOLOGIES.length).toBeGreaterThanOrEqual(0)
|
||
expect(EQUINE_PATHOLOGIES.length).toBeLessThanOrEqual(100)
|
||
})
|
||
|
||
it('every entry parses against the schema', () => {
|
||
for (const p of EQUINE_PATHOLOGIES) {
|
||
const r = PathologySchema.safeParse(p)
|
||
if (!r.success) throw new Error(`${p.id}: ${r.error.message}`)
|
||
}
|
||
})
|
||
|
||
it('every entry has at least one source', () => {
|
||
for (const p of EQUINE_PATHOLOGIES) {
|
||
expect(p.sources.length).toBeGreaterThanOrEqual(1)
|
||
}
|
||
})
|
||
|
||
it('every entry is tagged for equine when species-scoped', () => {
|
||
for (const p of EQUINE_PATHOLOGIES) {
|
||
if (p.speciesIds.length > 0) {
|
||
expect(p.speciesIds).toContain('equine')
|
||
}
|
||
}
|
||
})
|
||
|
||
it('every entry has a unique id', () => {
|
||
const ids = new Set<string>()
|
||
for (const p of EQUINE_PATHOLOGIES) {
|
||
expect(ids.has(p.id)).toBe(false)
|
||
ids.add(p.id)
|
||
}
|
||
})
|
||
})
|
||
```
|
||
|
||
- [ ] **Step 2:** Run; expect PASS (DB is empty, all rules vacuously satisfied).
|
||
```bash
|
||
pnpm test:run -- tests/unit/species.equinePathologies.test.ts
|
||
```
|
||
|
||
- [ ] **Step 3:** Commit
|
||
```bash
|
||
git add tests/unit/species.equinePathologies.test.ts
|
||
git commit -m "test(species): pin pathology DB integrity contract (empty allowed in v1)"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 17 — PDF rasterizer
|
||
|
||
### Task 17.1 — `rasterizeSvg` via canvg
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/render/svgToPng.ts`
|
||
- Create: `tests/unit/pdf.svgToPng.test.ts`
|
||
|
||
- [ ] **Step 1:** Test (mock canvg + toBlob)
|
||
```ts
|
||
import { describe, it, expect, vi } from 'vitest'
|
||
import { rasterizeSvg } from '@/pdf/render/svgToPng'
|
||
|
||
vi.mock('canvg', () => ({
|
||
Canvg: { from: vi.fn(async () => ({ render: vi.fn(async () => {}) })) },
|
||
}))
|
||
|
||
describe('rasterizeSvg', () => {
|
||
it('returns a Uint8Array', async () => {
|
||
const canvas = document.createElement('canvas')
|
||
canvas.toBlob = ((cb: BlobCallback) => {
|
||
cb(new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }))
|
||
}) as HTMLCanvasElement['toBlob']
|
||
vi.spyOn(document, 'createElement').mockImplementationOnce(() => canvas)
|
||
|
||
const out = await rasterizeSvg('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"/>', 2)
|
||
expect(out).toBeInstanceOf(Uint8Array)
|
||
expect(out.length).toBeGreaterThan(0)
|
||
})
|
||
})
|
||
```
|
||
|
||
- [ ] **Step 2:** Run; expect FAIL
|
||
|
||
- [ ] **Step 3:** Implement
|
||
```ts
|
||
import { Canvg } from 'canvg'
|
||
|
||
const TARGET_WIDTH = 1200
|
||
|
||
export async function rasterizeSvg(svgString: string, scale: number): Promise<Uint8Array> {
|
||
const tmp = new DOMParser().parseFromString(svgString, 'image/svg+xml')
|
||
const root = tmp.documentElement
|
||
const vb = (root.getAttribute('viewBox') ?? '0 0 1000 600').split(/\s+/).map(Number)
|
||
const widthPx = Math.round(TARGET_WIDTH * Math.max(1, scale) * 0.5)
|
||
const heightPx = Math.round((vb[3] / vb[2]) * widthPx)
|
||
|
||
const canvas = document.createElement('canvas')
|
||
canvas.width = widthPx
|
||
canvas.height = heightPx
|
||
const ctx = canvas.getContext('2d')
|
||
if (!ctx) throw new Error('Canvas 2D context unavailable')
|
||
|
||
const canv = await Canvg.from(ctx, svgString)
|
||
await canv.render()
|
||
|
||
const blob: Blob = await new Promise((resolve, reject) => {
|
||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob returned null'))), 'image/png')
|
||
})
|
||
return new Uint8Array(await blob.arrayBuffer())
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 4:** Re-run; expect PASS
|
||
|
||
- [ ] **Step 5:** Commit
|
||
```bash
|
||
git add src/pdf/render/svgToPng.ts tests/unit/pdf.svgToPng.test.ts
|
||
git commit -m "feat(pdf): rasterize SVG via canvg → PNG bytes"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 18 — PDF fonts
|
||
|
||
### Task 18.1 — Embed standard fonts (MVP)
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/fonts.ts`
|
||
|
||
Use pdf-lib's standard fonts (Helvetica + Helvetica-Bold + Times-Roman as serif fallback). Bundling Inter+Fraunces TTFs is out of scope for MVP. Document as a known limitation in REMAINING.
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```ts
|
||
import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib'
|
||
|
||
export interface EmbeddedFonts {
|
||
bodyRegular: PDFFont
|
||
bodyBold: PDFFont
|
||
headingRegular: PDFFont
|
||
}
|
||
|
||
export async function embedFonts(pdfDoc: PDFDocument): Promise<EmbeddedFonts> {
|
||
const [bodyRegular, bodyBold, headingRegular] = await Promise.all([
|
||
pdfDoc.embedFont(StandardFonts.Helvetica),
|
||
pdfDoc.embedFont(StandardFonts.HelveticaBold),
|
||
pdfDoc.embedFont(StandardFonts.TimesRoman),
|
||
])
|
||
return { bodyRegular, bodyBold, headingRegular }
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/pdf/fonts.ts
|
||
git commit -m "feat(pdf): embed Helvetica + Times-Roman standard fonts (MVP)"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 19 — PDF header + footer
|
||
|
||
### Task 19.1 — drawHeader
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/render/header.ts`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```ts
|
||
import { rgb, type PDFPage } from 'pdf-lib'
|
||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||
import type { Report } from '@/domain/schema/report'
|
||
import { formatDateFr } from '@/lib/dates'
|
||
|
||
const MARGIN_X = 36
|
||
const TOP_Y = 800
|
||
|
||
export function drawHeader(page: PDFPage, report: Report, fonts: EmbeddedFonts): void {
|
||
const { width } = page.getSize()
|
||
const ink = rgb(0.12, 0.11, 0.09)
|
||
const muted = rgb(0.42, 0.39, 0.35)
|
||
|
||
const left = [
|
||
report.practitioner.name,
|
||
report.practitioner.cabinet,
|
||
report.practitioner.contact,
|
||
report.practitioner.siret ? `SIRET ${report.practitioner.siret}` : undefined,
|
||
].filter(Boolean) as string[]
|
||
|
||
let y = TOP_Y
|
||
left.forEach((line, i) => {
|
||
page.drawText(line, {
|
||
x: MARGIN_X,
|
||
y: y - i * 12,
|
||
size: i === 0 ? 11 : 9,
|
||
font: i === 0 ? fonts.bodyBold : fonts.bodyRegular,
|
||
color: i === 0 ? ink : muted,
|
||
})
|
||
})
|
||
|
||
const animalLine = [
|
||
report.animal.name,
|
||
report.animal.breed ? `(${report.animal.breed})` : '',
|
||
report.animal.age ? `· ${report.animal.age}` : '',
|
||
].filter(Boolean).join(' ')
|
||
|
||
const right = [
|
||
animalLine,
|
||
`Propriétaire : ${report.owner.name}`,
|
||
formatDateFr(report.date),
|
||
]
|
||
right.forEach((line, i) => {
|
||
const size = i === 0 ? 11 : 9
|
||
const font = i === 0 ? fonts.bodyBold : fonts.bodyRegular
|
||
const w = font.widthOfTextAtSize(line, size)
|
||
page.drawText(line, {
|
||
x: width - MARGIN_X - w,
|
||
y: y - i * 12,
|
||
size,
|
||
font,
|
||
color: i === 0 ? ink : muted,
|
||
})
|
||
})
|
||
|
||
page.drawLine({
|
||
start: { x: MARGIN_X, y: y - 40 },
|
||
end: { x: width - MARGIN_X, y: y - 40 },
|
||
thickness: 0.5,
|
||
color: muted,
|
||
})
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/pdf/render/header.ts
|
||
git commit -m "feat(pdf): drawHeader with practitioner + animal/owner/date"
|
||
```
|
||
|
||
### Task 19.2 — drawFooter
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/render/footer.ts`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```ts
|
||
import { rgb, type PDFPage } from 'pdf-lib'
|
||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||
import { appConfig } from '@/config/env'
|
||
import { formatDateFr, todayIso } from '@/lib/dates'
|
||
|
||
const MARGIN_X = 36
|
||
const FOOTER_Y = 28
|
||
|
||
export function drawFooter(
|
||
page: PDFPage,
|
||
fonts: EmbeddedFonts,
|
||
pageNumber: number,
|
||
totalPages: number,
|
||
): void {
|
||
const { width } = page.getSize()
|
||
const muted = rgb(0.42, 0.39, 0.35)
|
||
const left = appConfig.footerName
|
||
const center = `Exporté le ${formatDateFr(todayIso())}`
|
||
const right = `${pageNumber} / ${totalPages}`
|
||
|
||
page.drawText(left, { x: MARGIN_X, y: FOOTER_Y, size: 9, font: fonts.bodyRegular, color: muted })
|
||
|
||
const centerW = fonts.bodyRegular.widthOfTextAtSize(center, 9)
|
||
page.drawText(center, { x: (width - centerW) / 2, y: FOOTER_Y, size: 9, font: fonts.bodyRegular, color: muted })
|
||
|
||
const rightW = fonts.bodyRegular.widthOfTextAtSize(right, 9)
|
||
page.drawText(right, { x: width - MARGIN_X - rightW, y: FOOTER_Y, size: 9, font: fonts.bodyRegular, color: muted })
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/pdf/render/footer.ts
|
||
git commit -m "feat(pdf): drawFooter with brand from runtime config"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 20 — Observation page + conclusion page
|
||
|
||
### Task 20.1 — addObservationPage
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/render/observationPage.ts`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```ts
|
||
import { rgb, PageSizes, type PDFDocument } from 'pdf-lib'
|
||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||
import type { Report } from '@/domain/schema/report'
|
||
import type { Observation } from '@/domain/schema/observation'
|
||
import { drawHeader } from './header'
|
||
import { rasterizeSvg } from './svgToPng'
|
||
import { loadSvg } from '@/anatomy/svgLoader'
|
||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||
import { getSpecies } from '@/domain/species/registry'
|
||
|
||
const MARGIN_X = 36
|
||
|
||
async function colorizedSvgString(
|
||
speciesSvgPath: string,
|
||
observation: Observation,
|
||
sourceDetailId: string | undefined,
|
||
): Promise<string> {
|
||
const root = await loadSvg(speciesSvgPath)
|
||
const bones = parseSvgBones(root)
|
||
observation.zones
|
||
.filter((z) => z.detailSourceId === sourceDetailId)
|
||
.forEach((z) => {
|
||
const bone = bones.get(z.boneId)
|
||
if (!bone) return
|
||
bone.visibleEls.forEach((el) => {
|
||
el.setAttribute('fill', '#b85a3f')
|
||
el.setAttribute('fill-opacity', '0.85')
|
||
})
|
||
bone.hitboxEls.forEach((el) => {
|
||
el.setAttribute('fill', '#b85a3f')
|
||
el.setAttribute('fill-opacity', '0.4')
|
||
})
|
||
})
|
||
return new XMLSerializer().serializeToString(root)
|
||
}
|
||
|
||
export async function addObservationPage(
|
||
pdfDoc: PDFDocument,
|
||
report: Report,
|
||
observation: Observation,
|
||
obsIndex: number,
|
||
fonts: EmbeddedFonts,
|
||
zoneLabels: Map<string, string>,
|
||
): Promise<void> {
|
||
const page = pdfDoc.addPage(PageSizes.A4)
|
||
const { width, height } = page.getSize()
|
||
drawHeader(page, report, fonts)
|
||
|
||
const ink = rgb(0.12, 0.11, 0.09)
|
||
page.drawText(`Observation #${obsIndex + 1}`, {
|
||
x: MARGIN_X,
|
||
y: height - 80,
|
||
size: 16,
|
||
font: fonts.headingRegular,
|
||
color: ink,
|
||
})
|
||
|
||
const species = getSpecies(report.animal.speciesId)
|
||
if (!species) return
|
||
|
||
const mainSvgStr = await colorizedSvgString(species.mainSvg, observation, undefined)
|
||
const mainPng = await rasterizeSvg(mainSvgStr, 2)
|
||
const mainImg = await pdfDoc.embedPng(mainPng)
|
||
const imgW = width - MARGIN_X * 2
|
||
const imgH = imgW * (mainImg.height / mainImg.width)
|
||
page.drawImage(mainImg, {
|
||
x: MARGIN_X,
|
||
y: height - 100 - imgH,
|
||
width: imgW,
|
||
height: imgH,
|
||
})
|
||
|
||
let cursorY = height - 110 - imgH
|
||
|
||
const detailIds = Array.from(
|
||
new Set(observation.zones.map((z) => z.detailSourceId).filter(Boolean) as string[]),
|
||
)
|
||
for (const detailId of detailIds) {
|
||
const detailPath = species.details[detailId]
|
||
if (!detailPath) continue
|
||
const detailSvg = await colorizedSvgString(detailPath, observation, detailId)
|
||
const detailPng = await rasterizeSvg(detailSvg, 2)
|
||
const dImg = await pdfDoc.embedPng(detailPng)
|
||
const dW = (width - MARGIN_X * 2) / 2
|
||
const dH = dW * (dImg.height / dImg.width)
|
||
page.drawImage(dImg, { x: MARGIN_X, y: cursorY - dH, width: dW, height: dH })
|
||
cursorY -= dH + 10
|
||
}
|
||
|
||
cursorY -= 8
|
||
|
||
const zonesText = observation.zones
|
||
.map((z) => {
|
||
const label = zoneLabels.get(z.boneId) ?? z.boneId
|
||
const v = z.vertebrae?.length
|
||
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
|
||
: ''
|
||
return `${label}${v}`
|
||
})
|
||
.join(' · ')
|
||
|
||
const lines: string[] = [`Zones : ${zonesText}`]
|
||
if (observation.pathologyIds.length || observation.freeTextPathologies.length) {
|
||
lines.push(
|
||
`Pathologies : ${[...observation.pathologyIds, ...observation.freeTextPathologies].join(' · ')}`,
|
||
)
|
||
}
|
||
if (observation.severity) lines.push(`Sévérité : ${observation.severity}`)
|
||
if (observation.comment.trim()) lines.push(`Commentaire : ${observation.comment.trim()}`)
|
||
|
||
lines.forEach((line, i) => {
|
||
page.drawText(line, {
|
||
x: MARGIN_X,
|
||
y: cursorY - i * 14,
|
||
size: 10,
|
||
font: fonts.bodyRegular,
|
||
color: ink,
|
||
maxWidth: width - MARGIN_X * 2,
|
||
})
|
||
})
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/pdf/render/observationPage.ts
|
||
git commit -m "feat(pdf): addObservationPage with rasterized colorized SVG + summary"
|
||
```
|
||
|
||
### Task 20.2 — addConclusionPage
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/render/conclusionPage.ts`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```ts
|
||
import { rgb, PageSizes, type PDFDocument, type PDFFont } from 'pdf-lib'
|
||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||
import type { Report } from '@/domain/schema/report'
|
||
import { drawHeader } from './header'
|
||
import { formatDateFr } from '@/lib/dates'
|
||
|
||
const MARGIN_X = 36
|
||
|
||
function wrap(text: string, font: PDFFont, size: number, max: number): string[] {
|
||
const words = text.split(/\s+/)
|
||
const lines: string[] = []
|
||
let line = ''
|
||
for (const w of words) {
|
||
const test = line ? `${line} ${w}` : w
|
||
if (font.widthOfTextAtSize(test, size) > max && line) {
|
||
lines.push(line)
|
||
line = w
|
||
} else {
|
||
line = test
|
||
}
|
||
}
|
||
if (line) lines.push(line)
|
||
return lines
|
||
}
|
||
|
||
export async function addConclusionPage(
|
||
pdfDoc: PDFDocument,
|
||
report: Report,
|
||
fonts: EmbeddedFonts,
|
||
): Promise<void> {
|
||
const page = pdfDoc.addPage(PageSizes.A4)
|
||
const { width, height } = page.getSize()
|
||
drawHeader(page, report, fonts)
|
||
|
||
const ink = rgb(0.12, 0.11, 0.09)
|
||
const muted = rgb(0.42, 0.39, 0.35)
|
||
const max = width - MARGIN_X * 2
|
||
|
||
let y = height - 80
|
||
page.drawText('Conclusion', { x: MARGIN_X, y, size: 16, font: fonts.headingRegular, color: ink })
|
||
y -= 20
|
||
wrap(report.conclusion || '—', fonts.bodyRegular, 11, max).forEach((line) => {
|
||
page.drawText(line, { x: MARGIN_X, y, size: 11, font: fonts.bodyRegular, color: ink })
|
||
y -= 14
|
||
})
|
||
|
||
y -= 12
|
||
page.drawText('Recommandations', { x: MARGIN_X, y, size: 14, font: fonts.headingRegular, color: ink })
|
||
y -= 18
|
||
wrap(report.recommendations || '—', fonts.bodyRegular, 11, max).forEach((line) => {
|
||
page.drawText(line, { x: MARGIN_X, y, size: 11, font: fonts.bodyRegular, color: ink })
|
||
y -= 14
|
||
})
|
||
|
||
if (report.nextAppointment) {
|
||
y -= 12
|
||
page.drawText('Prochain rendez-vous', { x: MARGIN_X, y, size: 14, font: fonts.headingRegular, color: ink })
|
||
y -= 18
|
||
const txt =
|
||
report.nextAppointment.kind === 'date'
|
||
? formatDateFr(report.nextAppointment.date)
|
||
: report.nextAppointment.text
|
||
page.drawText(txt || '—', { x: MARGIN_X, y, size: 11, font: fonts.bodyRegular, color: muted })
|
||
}
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add src/pdf/render/conclusionPage.ts
|
||
git commit -m "feat(pdf): addConclusionPage with wrapped conclusion + recommendations + next RDV"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 21 — PDF attachment + export + import
|
||
|
||
### Task 21.1 — attachReportJson + extractReportJson
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/attachment.ts`
|
||
- Create: `tests/unit/pdf.attachment.test.ts`
|
||
|
||
- [ ] **Step 1:** Test
|
||
```ts
|
||
import { describe, it, expect } from 'vitest'
|
||
import { PDFDocument } from 'pdf-lib'
|
||
import { attachReportJson, extractReportJson } from '@/pdf/attachment'
|
||
import type { Report } from '@/domain/schema/report'
|
||
|
||
const report: Report = {
|
||
version: 1,
|
||
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: 'tout va bien',
|
||
recommendations: 'continuer',
|
||
}
|
||
|
||
describe('PDF attachment roundtrip', () => {
|
||
it('attaches and extracts the report JSON', async () => {
|
||
const doc = await PDFDocument.create()
|
||
doc.addPage()
|
||
await attachReportJson(doc, report)
|
||
const bytes = await doc.save()
|
||
|
||
const reopened = await PDFDocument.load(bytes)
|
||
const out = await extractReportJson(reopened)
|
||
expect(out.conclusion).toBe('tout va bien')
|
||
expect(out.animal.name).toBe('Mistral')
|
||
expect(out.version).toBe(1)
|
||
})
|
||
|
||
it('throws on PDFs without the attachment', async () => {
|
||
const doc = await PDFDocument.create()
|
||
doc.addPage()
|
||
const bytes = await doc.save()
|
||
const reopened = await PDFDocument.load(bytes)
|
||
await expect(extractReportJson(reopened)).rejects.toThrow()
|
||
})
|
||
})
|
||
```
|
||
|
||
- [ ] **Step 2:** Run; expect FAIL
|
||
|
||
- [ ] **Step 3:** Implement
|
||
```ts
|
||
import type { PDFDocument } from 'pdf-lib'
|
||
import { ReportSchema, type Report } from '@/domain/schema/report'
|
||
|
||
const FILENAME = 'osteo-report.json'
|
||
|
||
export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise<void> {
|
||
const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2))
|
||
await pdfDoc.attach(bytes, FILENAME, {
|
||
mimeType: 'application/json',
|
||
description: 'Osteo Report state v1',
|
||
creationDate: new Date(),
|
||
modificationDate: new Date(),
|
||
afRelationship: 'Data',
|
||
})
|
||
}
|
||
|
||
export async function extractReportJson(pdfDoc: PDFDocument): Promise<Report> {
|
||
const maybeApi = pdfDoc as unknown as { getAttachments?: () => Array<{ name: string; data: Uint8Array }> }
|
||
if (typeof maybeApi.getAttachments === 'function') {
|
||
const list = maybeApi.getAttachments()
|
||
if (list && list.length) {
|
||
const hit = list.find((a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json')) ?? list[0]
|
||
return parseAttachment(hit.data)
|
||
}
|
||
}
|
||
const fallback = traverseForJsonAttachment(pdfDoc)
|
||
if (!fallback) throw new Error('No osteo-report attachment found')
|
||
return parseAttachment(fallback)
|
||
}
|
||
|
||
function parseAttachment(bytes: Uint8Array): Report {
|
||
const text = new TextDecoder().decode(bytes)
|
||
const data = JSON.parse(text)
|
||
return ReportSchema.parse(data)
|
||
}
|
||
|
||
interface RawObj {
|
||
contents?: Uint8Array
|
||
dict?: Map<unknown, unknown>
|
||
}
|
||
|
||
function traverseForJsonAttachment(pdfDoc: PDFDocument): Uint8Array | null {
|
||
const ctx = (pdfDoc as unknown as { context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> } }).context
|
||
for (const [, obj] of ctx.enumerateIndirectObjects()) {
|
||
if (!obj || typeof obj !== 'object') continue
|
||
if (!(obj.contents instanceof Uint8Array)) continue
|
||
let isJson = false
|
||
obj.dict?.forEach((v, k) => {
|
||
const ks = String(k)
|
||
const vs = String(v)
|
||
if (ks.includes('Subtype') && vs.includes('application/json')) isJson = true
|
||
if ((ks.includes('UF') || ks.includes('F')) && vs.includes('osteo-report')) isJson = true
|
||
})
|
||
if (isJson) return obj.contents
|
||
}
|
||
return null
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 4:** Re-run; expect PASS
|
||
|
||
- [ ] **Step 5:** Commit
|
||
```bash
|
||
git add src/pdf/attachment.ts tests/unit/pdf.attachment.test.ts
|
||
git commit -m "feat(pdf): attach + extract report JSON via pdf-lib (with fallback traversal)"
|
||
```
|
||
|
||
### Task 21.2 — exportReportToPdf
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/export.ts`
|
||
|
||
- [ ] **Step 1:** Implement
|
||
```ts
|
||
import { PDFDocument } from 'pdf-lib'
|
||
import type { Report } from '@/domain/schema/report'
|
||
import { embedFonts } from './fonts'
|
||
import { addObservationPage } from './render/observationPage'
|
||
import { addConclusionPage } from './render/conclusionPage'
|
||
import { attachReportJson } from './attachment'
|
||
import { drawFooter } from './render/footer'
|
||
import { loadSvg } from '@/anatomy/svgLoader'
|
||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||
import { getSpecies } from '@/domain/species/registry'
|
||
|
||
async function buildZoneLabels(report: Report): Promise<Map<string, string>> {
|
||
const labels = new Map<string, string>()
|
||
const species = getSpecies(report.animal.speciesId)
|
||
if (!species) return labels
|
||
const mainRoot = await loadSvg(species.mainSvg)
|
||
parseSvgBones(mainRoot).forEach((b, id) => labels.set(id, b.fr))
|
||
for (const detailPath of Object.values(species.details)) {
|
||
const detailRoot = await loadSvg(detailPath)
|
||
parseSvgBones(detailRoot).forEach((b, id) => labels.set(id, b.fr))
|
||
}
|
||
return labels
|
||
}
|
||
|
||
export async function exportReportToPdf(report: Report): Promise<Uint8Array> {
|
||
const pdfDoc = await PDFDocument.create()
|
||
pdfDoc.setTitle(`Bilan ostéo — ${report.animal.name}`)
|
||
pdfDoc.setAuthor(report.practitioner.name)
|
||
pdfDoc.setSubject("Bilan d'ostéopathie animalière")
|
||
pdfDoc.setCreationDate(new Date())
|
||
pdfDoc.setModificationDate(new Date())
|
||
|
||
const fonts = await embedFonts(pdfDoc)
|
||
const zoneLabels = await buildZoneLabels(report)
|
||
|
||
for (let i = 0; i < report.observations.length; i += 1) {
|
||
await addObservationPage(pdfDoc, report, report.observations[i], i, fonts, zoneLabels)
|
||
}
|
||
await addConclusionPage(pdfDoc, report, fonts)
|
||
|
||
const pages = pdfDoc.getPages()
|
||
pages.forEach((page, idx) => drawFooter(page, fonts, idx + 1, pages.length))
|
||
|
||
await attachReportJson(pdfDoc, report)
|
||
return pdfDoc.save()
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2:** Verify build clean
|
||
|
||
- [ ] **Step 3:** Commit
|
||
```bash
|
||
git add src/pdf/export.ts
|
||
git commit -m "feat(pdf): exportReportToPdf orchestrator with finalized page numbering"
|
||
```
|
||
|
||
### Task 21.3 — importReportFromPdf
|
||
|
||
**Files:**
|
||
- Modify: `src/pdf/import.ts`
|
||
- Create: `tests/unit/pdf.roundtrip.test.ts`
|
||
|
||
- [ ] **Step 1:** Test
|
||
```ts
|
||
import { describe, it, expect, vi } from 'vitest'
|
||
import { exportReportToPdf } from '@/pdf/export'
|
||
import { importReportFromPdf, ImportError } from '@/pdf/import'
|
||
import type { Report } from '@/domain/schema/report'
|
||
|
||
vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: async () => new Uint8Array([137, 80, 78, 71]) }))
|
||
|
||
const report: Report = {
|
||
version: 1,
|
||
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: 'ok',
|
||
recommendations: '',
|
||
}
|
||
|
||
describe('PDF roundtrip', () => {
|
||
it('rejects unrelated PDF bytes with ImportError', async () => {
|
||
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10, 37, 226, 227, 207, 211, 10])
|
||
await expect(importReportFromPdf(fake)).rejects.toThrow(ImportError)
|
||
})
|
||
|
||
it('roundtrips a minimal report (no observations)', async () => {
|
||
const bytes = await exportReportToPdf(report)
|
||
const imported = await importReportFromPdf(bytes)
|
||
expect(imported.animal.name).toBe('Mistral')
|
||
})
|
||
})
|
||
```
|
||
|
||
- [ ] **Step 2:** Implement
|
||
```ts
|
||
import { PDFDocument } from 'pdf-lib'
|
||
import { extractReportJson } from './attachment'
|
||
import type { Report } from '@/domain/schema/report'
|
||
|
||
export class ImportError extends Error {
|
||
constructor() {
|
||
super("Ce PDF n'a pas été généré par Osteo Report (pas de données détectées).")
|
||
this.name = 'ImportError'
|
||
}
|
||
}
|
||
|
||
export async function importReportFromPdf(pdfBytes: Uint8Array): Promise<Report> {
|
||
let pdfDoc: PDFDocument
|
||
try {
|
||
pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
|
||
} catch {
|
||
throw new ImportError()
|
||
}
|
||
try {
|
||
return await extractReportJson(pdfDoc)
|
||
} catch {
|
||
throw new ImportError()
|
||
}
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 3:** Run; expect PASS on both cases
|
||
```bash
|
||
pnpm test:run -- tests/unit/pdf.roundtrip.test.ts
|
||
```
|
||
|
||
- [ ] **Step 4:** Commit
|
||
```bash
|
||
git add src/pdf/import.ts tests/unit/pdf.roundtrip.test.ts
|
||
git commit -m "feat(pdf): importReportFromPdf with ImportError on non-osteo PDFs"
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 22 — Docker runtime env injection
|
||
|
||
### Task 22.1 — Verify entrypoint + index.html
|
||
|
||
**Files:**
|
||
- Modify (if needed): `docker/entrypoint.sh`
|
||
- Modify (if needed): `index.html`
|
||
|
||
- [ ] **Step 1:** Read both files. Confirm:
|
||
- `docker/entrypoint.sh` writes `/usr/share/nginx/html/env.js` of the form
|
||
`window.__APP_CONFIG__ = { siteName: "...", brandName: "...", footerName: "...", tagline: "..." };`
|
||
populated from `$APP_SITE_NAME`, `$APP_BRAND_NAME`, `$APP_FOOTER_NAME`, `$APP_TAGLINE`.
|
||
- `index.html` includes `<script src="/env.js"></script>` BEFORE the Vite bundle script tag.
|
||
Patch if missing.
|
||
|
||
- [ ] **Step 2:** Commit if patched
|
||
```bash
|
||
git add docker/entrypoint.sh index.html
|
||
git commit -m "fix(docker): write env.js from APP_* env vars at container start"
|
||
```
|
||
|
||
- [ ] **Step 3:** Build the Docker image (skip if Docker daemon unavailable)
|
||
```bash
|
||
docker build -t osteo-report:dev .
|
||
```
|
||
|
||
---
|
||
|
||
## Phase 23 — Final checks
|
||
|
||
### Task 23.1 — Full suite + lint + build
|
||
|
||
- [ ] **Step 1:**
|
||
```bash
|
||
pnpm lint && pnpm typecheck && pnpm test:run && pnpm build
|
||
```
|
||
Expected: all clean.
|
||
|
||
- [ ] **Step 2:** Fix root causes if anything fails; commit fixes.
|
||
|
||
### Task 23.2 — Manual QA log
|
||
|
||
**Files:**
|
||
- Create: `.claude/audits/MVP-QA.md`
|
||
|
||
- [ ] **Step 1:** Run `pnpm dev` and walk through:
|
||
- Home shows brand + tagline + both CTAs.
|
||
- "Nouveau bilan" → form prefilled if cache; submit → `/editor`.
|
||
- Editor loads Horse.svg; zones clickable.
|
||
- Click a non-spine zone: visible state changes to "current".
|
||
- Click a spine-zone: also opens vertebra picker; valider stores precise vertebrae.
|
||
- Click the head zone: DetailModal opens; click inside adds detail zones.
|
||
- Add a second observation: previously-selected zones now show "linked" state on main canvas.
|
||
- PathologyPicker shows only zone-matched entries; FreeTextPathologyInput adds chips.
|
||
- Severity + comment editable.
|
||
- Conclusion + recommendations + next-RDV editable.
|
||
- "Exporter en PDF" downloads `bilan-<name>-<date>.pdf`. Open it; confirm header, observation pages, conclusion, footer with brand.
|
||
- On Home, "Importer un PDF" → pick that file → editor reopens with state restored.
|
||
- Import a random PDF → French ImportError shown.
|
||
|
||
- [ ] **Step 2:** Write findings (✅ / ⚠️ / ❌) to `.claude/audits/MVP-QA.md`.
|
||
|
||
- [ ] **Step 3:** Commit
|
||
```bash
|
||
git add .claude/audits/MVP-QA.md
|
||
git commit -m "test(qa): document MVP manual QA checklist outcome"
|
||
```
|
||
|
||
### Task 23.2b — Flesh out `docs/ADDING-A-SPECIES.md`
|
||
|
||
**Files:**
|
||
- Modify: `docs/ADDING-A-SPECIES.md`
|
||
|
||
- [ ] **Step 1:** Rewrite from the placeholder, covering:
|
||
1. SVG convention (refer to `docs/ANATOMY-SVG-CONVENTION.md`): `data-anno-id`, `data-anno-name-fr`, `data-anno-name-en`, `data-anno-category`, optional `data-anno-opens-detail`.
|
||
2. Where to drop the SVG: `public/species/<id>/<Main>.svg` + any detail SVGs.
|
||
3. Create the species manifest at `src/domain/species/<id>/index.ts` with `id`, `labelFr`, `mainSvg`, `details`, `vertebralFormula`, and a `pathologies` lazy import.
|
||
4. Wire the manifest into `src/domain/species/registry.ts`.
|
||
5. Provide a vertebral formula file (`vertebrae.ts`).
|
||
6. Provide a pathologies seed file (`pathologies.ts`); empty `[]` is acceptable per v1 contract.
|
||
7. Add a registry test and a real-SVG parse test mirroring the equine ones.
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add docs/ADDING-A-SPECIES.md
|
||
git commit -m "docs(species): document how to add a new species end-to-end"
|
||
```
|
||
|
||
### Task 23.3 — Memory journal entry
|
||
|
||
**Files:**
|
||
- Modify: `.claude/memory/journal.md`
|
||
|
||
- [ ] **Step 1:** Append one line (English, caveman) under today's heading:
|
||
```
|
||
- MVP scaffold+impl done. Editor flow works. PDF roundtrip green. Real SVG assets in repo.
|
||
```
|
||
|
||
- [ ] **Step 2:** Commit
|
||
```bash
|
||
git add .claude/memory/journal.md
|
||
git commit -m "chore(memory): log MVP delivery in journal"
|
||
```
|
||
|
||
---
|
||
|
||
## Self-review
|
||
|
||
- All schemas covered by parse+reject tests. ✅ (Phase 2)
|
||
- Anatomy parser covered on synthetic + real SVG. ✅ (Phase 4)
|
||
- Store covered on init/reset/CRUD/move/mirror. ✅ (Phase 5)
|
||
- Practitioner cache covered. ✅ (Phase 6)
|
||
- VertebraPicker, PathologyPicker covered; ObservationEditor wired in editor flow. ✅ (Phases 11–13)
|
||
- PDF attachment roundtrip covered. ✅ (Phase 21)
|
||
- Import error path covered. ✅ (Phase 21)
|
||
- No placeholder strings shipped (`'not implemented'`).
|
||
- `pnpm lint && pnpm typecheck && pnpm test:run && pnpm build` all clean before declaring done.
|