chore: purge transient planning artifacts (BDR-065)

This commit is contained in:
bchanot committed 2026-10-08 21:41:51 +02:00
1 parent e9047a99d2
commit 8f217d8103
9 files changed
-8577

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,738 +0,0 @@
# Laterality Support 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:** Add bilateral/unpaired laterality to anatomical zones so practitioners can specify left/right side on bilateral structures.
**Architecture:** New `data-anno-lateral` SVG attribute parsed into `Bone.lateral`. New `side` field on `ObservationZone` schema. LateralityPicker modal triggered on bilateral zone clicks. Side displayed in zone badges and PDF output. SVG editor gets a laterality dropdown.
**Tech Stack:** React 19, TypeScript strict, Zustand 5, Zod 3, Tailwind v4, pdf-lib, vitest
---
### Task 1: Schema + Bone Type — Add `side` to ObservationZone and `lateral` to Bone
**Files:**
- Modify: `src/domain/schema/observation.ts`
- Modify: `src/anatomy/types.ts`
- Test: `tests/unit/schema.observation.test.ts`
- [ ] **Step 1: Write failing tests for LateralSideSchema and side field**
Add to `tests/unit/schema.observation.test.ts`:
```ts
import {
ObservationSchema,
ObservationZoneSchema,
LateralSideSchema,
VertebraSchema,
SeveritySchema,
FindingSchema,
} from '@/domain/schema/observation'
describe('LateralSideSchema', () => {
it('accepts left and right', () => {
expect(LateralSideSchema.parse('left')).toBe('left')
expect(LateralSideSchema.parse('right')).toBe('right')
})
it('rejects unknown side', () => {
expect(() => LateralSideSchema.parse('both')).toThrow()
expect(() => LateralSideSchema.parse('')).toThrow()
})
})
describe('ObservationZoneSchema with side', () => {
it('accepts a zone without side (unpaired)', () => {
expect(() => ObservationZoneSchema.parse({ boneId: 'sternum' })).not.toThrow()
})
it('accepts a zone with side left', () => {
const parsed = ObservationZoneSchema.parse({ boneId: 'knee', side: 'left' })
expect(parsed.side).toBe('left')
})
it('accepts a zone with side right', () => {
const parsed = ObservationZoneSchema.parse({ boneId: 'knee', side: 'right' })
expect(parsed.side).toBe('right')
})
it('accepts two zones with same boneId but different sides', () => {
const obs = {
id: 'obs-1',
zones: [
{ boneId: 'knee', side: 'left' },
{ boneId: 'knee', side: 'right' },
],
findings: [],
freeTextFindings: [],
comment: '',
}
expect(() => ObservationSchema.parse(obs)).not.toThrow()
})
})
```
- [ ] **Step 2: Run tests to verify they fail**
Run: `pnpm test:run -- tests/unit/schema.observation.test.ts`
Expected: FAIL — `LateralSideSchema` is not exported
- [ ] **Step 3: Add LateralSideSchema and side field to observation.ts**
In `src/domain/schema/observation.ts`, add after the `VertebraSchema` definition:
```ts
export const LateralSideSchema = z.enum(['left', 'right'])
export type LateralSide = z.infer<typeof LateralSideSchema>
```
Add `side` to `ObservationZoneSchema`:
```ts
export const ObservationZoneSchema = z.object({
boneId: z.string().min(1),
detailSourceId: z.string().optional(),
vertebrae: z.array(VertebraSchema).optional(),
side: LateralSideSchema.optional(),
})
```
- [ ] **Step 4: Add `lateral` field to Bone interface**
In `src/anatomy/types.ts`, add to `Bone` interface after `special?`:
```ts
lateral?: 'bilateral' | 'unpaired'
```
- [ ] **Step 5: Run tests to verify they pass**
Run: `pnpm test:run -- tests/unit/schema.observation.test.ts`
Expected: ALL PASS
- [ ] **Step 6: Run full typecheck**
Run: `pnpm typecheck`
Expected: No errors
- [ ] **Step 7: Commit**
```bash
git add src/domain/schema/observation.ts src/anatomy/types.ts tests/unit/schema.observation.test.ts
git commit -m "feat(schema): add LateralSideSchema and Bone.lateral for laterality support"
```
---
### Task 2: SVG Parser — Read `data-anno-lateral` attribute
**Files:**
- Modify: `src/anatomy/svgConvention.ts`
- Test: `tests/unit/anatomy.svgConvention.test.ts`
- [ ] **Step 1: Write failing tests for lateral parsing**
Add to `tests/unit/anatomy.svgConvention.test.ts`, update the `FIXTURE` and add tests:
Update `FIXTURE` — add a bilateral element:
```xml
<circle data-anno-id="point-knee" data-anno-name-fr="Genou" data-anno-name-en="Knee"
data-anno-category="articulations" data-anno-lateral="bilateral" />
```
Add tests:
```ts
it('captures data-anno-lateral when present', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('point-knee')?.lateral).toBe('bilateral')
})
it('leaves lateral undefined when attribute absent', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('point-shoulder')?.lateral).toBeUndefined()
})
```
- [ ] **Step 2: Run tests to verify they fail**
Run: `pnpm test:run -- tests/unit/anatomy.svgConvention.test.ts`
Expected: FAIL — `lateral` is undefined for knee
- [ ] **Step 3: Update parseSvgBones to read data-anno-lateral**
In `src/anatomy/svgConvention.ts`, in `parseSvgBones()`, add after the `special` read:
```ts
const lateral = el.getAttribute('data-anno-lateral') as
| 'bilateral'
| 'unpaired'
| undefined ?? undefined
```
In the `else` branch (new Bone creation), add `lateral` to the object:
```ts
map.set(id, {
id,
fr,
en,
category,
opensDetail,
special,
lateral,
els: [el],
})
```
In the `existing` merge branch, add:
```ts
if (lateral && !existing.lateral) {
existing.lateral = lateral
}
```
- [ ] **Step 4: Run tests to verify they pass**
Run: `pnpm test:run -- tests/unit/anatomy.svgConvention.test.ts`
Expected: ALL PASS
- [ ] **Step 5: Commit**
```bash
git add src/anatomy/svgConvention.ts tests/unit/anatomy.svgConvention.test.ts
git commit -m "feat(anatomy): parse data-anno-lateral attribute from SVG"
```
---
### Task 3: i18n — Add laterality translation keys
**Files:**
- Modify: `src/i18n/fr.ts`
- Modify: `src/i18n/en.ts`
- Test: `tests/unit/i18n.dicts.test.ts` (existing test verifies key parity)
- [ ] **Step 1: Add keys to fr.ts**
Add after the vertebra section in `src/i18n/fr.ts`:
```ts
// laterality
'lateral.which_side': 'Quel côté ?',
'lateral.left': 'Gauche',
'lateral.right': 'Droite',
'lateral.both': 'Les deux',
'lateral.left_short': 'G',
'lateral.right_short': 'D',
'lateral.bilateral': 'Bilatéral',
'lateral.unpaired': 'Impair',
```
- [ ] **Step 2: Add keys to en.ts**
Add after the vertebra section in `src/i18n/en.ts`:
```ts
// laterality
'lateral.which_side': 'Which side?',
'lateral.left': 'Left',
'lateral.right': 'Right',
'lateral.both': 'Both',
'lateral.left_short': 'L',
'lateral.right_short': 'R',
'lateral.bilateral': 'Bilateral',
'lateral.unpaired': 'Unpaired',
```
- [ ] **Step 3: Run i18n key parity test**
Run: `pnpm test:run -- tests/unit/i18n.dicts.test.ts`
Expected: PASS (both dicts have same keys)
- [ ] **Step 4: Commit**
```bash
git add src/i18n/fr.ts src/i18n/en.ts
git commit -m "feat(i18n): add laterality translation keys (FR/EN)"
```
---
### Task 4: LateralityPicker Component
**Files:**
- Create: `src/components/observation/LateralityPicker.tsx`
- [ ] **Step 1: Create LateralityPicker component**
Create `src/components/observation/LateralityPicker.tsx`:
```tsx
import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button'
import type { LateralSide } from '@/domain/schema/observation'
import { useT } from '@/i18n/useT'
export interface LateralityPickerProps {
open: boolean
onClose: () => void
onSelect: (sides: LateralSide[]) => void
title: string
/** Sides already present in the active observation for this boneId. */
existingSides: LateralSide[]
}
export default function LateralityPicker({
open,
onClose,
onSelect,
title,
existingSides,
}: LateralityPickerProps) {
const t = useT()
const hasLeft = existingSides.includes('left')
const hasRight = existingSides.includes('right')
return (
<Dialog open={open} onClose={onClose} title={title} size="sm">
<div className="space-y-4">
<p className="text-sm text-[var(--color-ink-muted)]">
{t('lateral.which_side')}
</p>
<div className="flex gap-3 justify-center">
<Button
variant={hasLeft ? 'ghost' : 'default'}
disabled={hasLeft}
onClick={() => onSelect(['left'])}
>
{t('lateral.left')}
</Button>
<Button
variant={hasRight ? 'ghost' : 'default'}
disabled={hasRight}
onClick={() => onSelect(['right'])}
>
{t('lateral.right')}
</Button>
<Button
variant={hasLeft && hasRight ? 'ghost' : 'default'}
disabled={hasLeft && hasRight}
onClick={() => {
const sides: LateralSide[] = []
if (!hasLeft) sides.push('left')
if (!hasRight) sides.push('right')
onSelect(sides)
}}
>
{t('lateral.both')}
</Button>
</div>
</div>
</Dialog>
)
}
```
- [ ] **Step 2: Run typecheck**
Run: `pnpm typecheck`
Expected: No errors
- [ ] **Step 3: Commit**
```bash
git add src/components/observation/LateralityPicker.tsx
git commit -m "feat(ui): add LateralityPicker modal component"
```
---
### Task 5: EditorRoute — Integrate LateralityPicker into zone click flow
**Files:**
- Modify: `src/app/routes/EditorRoute.tsx`
- [ ] **Step 1: Add laterality state and imports**
Add imports at top of `EditorRoute.tsx`:
```ts
import LateralityPicker from '@/components/observation/LateralityPicker'
import type { LateralSide } from '@/domain/schema/observation'
```
Add state after `vertebraTarget` state:
```ts
const [lateralTarget, setLateralTarget] = useState<{
boneId: string
detailSourceId?: string
} | null>(null)
```
- [ ] **Step 2: Modify onZoneClick to handle bilateral zones**
In `onZoneClick()`, after the `vertebral-precision` block and before the unpaired toggle logic, add:
```ts
if (bone.lateral === 'bilateral') {
setLateralTarget({
boneId,
...(detailSourceId ? { detailSourceId } : {}),
})
return
}
```
- [ ] **Step 3: Add LateralityPicker to JSX**
Add before the closing `</main>` tag, after the VertebraPicker block:
```tsx
{lateralTarget && activeObs && (
<LateralityPicker
open
onClose={() => setLateralTarget(null)}
title={boneLabel(
allBones.get(lateralTarget.boneId),
locale,
lateralTarget.boneId,
)}
existingSides={
activeObs.zones
.filter(
(z) =>
z.boneId === lateralTarget.boneId &&
z.detailSourceId === lateralTarget.detailSourceId &&
z.side,
)
.map((z) => z.side!) as LateralSide[]
}
onSelect={(sides) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (!fresh) {
setLateralTarget(null)
return
}
let nextZones = [...fresh.zones]
for (const side of sides) {
const exists = nextZones.some(
(z) =>
z.boneId === lateralTarget.boneId &&
z.detailSourceId === lateralTarget.detailSourceId &&
z.side === side,
)
if (!exists) {
nextZones.push({
boneId: lateralTarget.boneId,
...(lateralTarget.detailSourceId
? { detailSourceId: lateralTarget.detailSourceId }
: {}),
side,
})
}
}
updateObservation(activeIndex, { ...fresh, zones: nextZones })
setLateralTarget(null)
}}
/>
)}
```
- [ ] **Step 4: Handle re-click toggle for bilateral zones**
The current flow in `onZoneClick` for the bilateral case:
- If both sides already exist → remove both (toggle off)
- If one or zero sides → open picker
Update the bilateral block:
```ts
if (bone.lateral === 'bilateral') {
const sidesPresent = activeObs.zones
.filter(
(z) =>
z.boneId === boneId &&
z.detailSourceId === detailSourceId,
)
.map((z) => z.side)
.filter(Boolean) as LateralSide[]
if (sidesPresent.includes('left') && sidesPresent.includes('right')) {
const nextZones = activeObs.zones.filter(
(z) =>
!(z.boneId === boneId && z.detailSourceId === detailSourceId),
)
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
return
}
setLateralTarget({
boneId,
...(detailSourceId ? { detailSourceId } : {}),
})
return
}
```
- [ ] **Step 5: Run typecheck**
Run: `pnpm typecheck`
Expected: No errors
- [ ] **Step 6: Commit**
```bash
git add src/app/routes/EditorRoute.tsx
git commit -m "feat(editor): integrate LateralityPicker in zone click flow"
```
---
### Task 6: ObservationCard — Display side in zone badges
**Files:**
- Modify: `src/components/observation/ObservationCard.tsx`
- [ ] **Step 1: Update describeZone to show side suffix**
In `ObservationCard.tsx`, update the `describeZone` function:
```ts
function describeZone(
z: ObservationZone,
bones: Map<string, Bone>,
locale: Locale,
t: (key: string) => string,
): string {
const label = boneLabel(bones.get(z.boneId), locale, z.boneId)
if (z.vertebrae?.length) {
const vs = z.vertebrae
.map((v: Vertebra) => `${v.region}${v.index}`)
.join(', ')
return `${label} (${vs})`
}
if (z.side) {
const sideLabel = t(
z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short',
)
return `${label} (${sideLabel})`
}
return label
}
```
- [ ] **Step 2: Update describeZone call sites to pass t**
In the JSX, update the two places `describeZone` is called:
In the zone badges list:
```tsx
{describeZone(z, bones, locale, t)}
```
- [ ] **Step 3: Run typecheck**
Run: `pnpm typecheck`
Expected: No errors
- [ ] **Step 4: Commit**
```bash
git add src/components/observation/ObservationCard.tsx
git commit -m "feat(ui): display laterality side in zone badges"
```
---
### Task 7: PDF Output — Include side in zone labels
**Files:**
- Modify: `src/pdf/render/observationPage.ts`
- [ ] **Step 1: Update zone label rendering**
In `addObservationPage()`, find the `zonesText` construction (around line 369-379). Update to include side:
```ts
const zonesText = observation.zones
.map((z) => {
const pair = zoneLabels.get(z.boneId)
const label = pair
? (locale === 'en' ? pair.en || pair.fr : pair.fr || pair.en) || z.boneId
: z.boneId
const v = z.vertebrae?.length
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
: ''
const side = z.side
? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})`
: ''
return `${label}${v}${side}`
})
.join(' · ')
```
- [ ] **Step 2: Run typecheck**
Run: `pnpm typecheck`
Expected: No errors
- [ ] **Step 3: Commit**
```bash
git add src/pdf/render/observationPage.ts
git commit -m "feat(pdf): include laterality side in zone labels"
```
---
### Task 8: SVG Editor — Add laterality dropdown
**Files:**
- Modify: `src/app/routes/SvgEditorRoute.tsx`
- Modify: `src/i18n/fr.ts`
- Modify: `src/i18n/en.ts`
- [ ] **Step 1: Add SVG editor i18n keys**
In `src/i18n/fr.ts`, add:
```ts
'svg_editor.lateral': 'Latéralité',
'svg_editor.lateral_unpaired': 'Impair (pas de côté)',
'svg_editor.lateral_bilateral': 'Bilatéral (gauche / droite)',
```
In `src/i18n/en.ts`, add:
```ts
'svg_editor.lateral': 'Laterality',
'svg_editor.lateral_unpaired': 'Unpaired (no side)',
'svg_editor.lateral_bilateral': 'Bilateral (left / right)',
```
- [ ] **Step 2: Add dropdown to SvgEditorRoute JSX**
In `SvgEditorRoute.tsx`, inside the `svg-editor-osteo-fields` div, after the category `<select>`, add:
```tsx
<label>{t('svg_editor.lateral')}</label>
<select id="svg-editor-edit-lateral">
<option value="">{t('svg_editor.lateral_unpaired')}</option>
<option value="bilateral">{t('svg_editor.lateral_bilateral')}</option>
</select>
```
- [ ] **Step 3: Wire up event listener in initSvgEditor**
In `setupGlobalListeners()`, add the lateral select to the change listener array:
```ts
;['svg-editor-edit-fr', 'svg-editor-edit-en', 'svg-editor-edit-category', 'svg-editor-edit-lateral'].forEach(
(id) => {
getEl(id).addEventListener('change', applyEdit, sig)
},
)
```
- [ ] **Step 4: Read lateral in showEditPanel**
In `showEditPanel()`, after reading category, add:
```ts
;(getEl('svg-editor-edit-lateral') as HTMLSelectElement).value =
svgEl.getAttribute('data-anno-lateral') || ''
```
- [ ] **Step 5: Write lateral in applyEdit**
In `applyEdit()`, after reading `cat`, add:
```ts
const lateral = (getEl('svg-editor-edit-lateral') as HTMLSelectElement).value
```
In the siblings loop, inside the non-opens-detail branch (where `data-anno-name-fr` etc. are set), add after the special attribute logic:
```ts
if (lateral) {
s.setAttribute('data-anno-lateral', lateral)
} else {
s.removeAttribute('data-anno-lateral')
}
```
- [ ] **Step 6: Propagate lateral when creating new elements**
In `addCircleAt()`, after setting `data-anno-special` on both `hit` and `vis`, add for each:
```ts
if (CATEGORIES[cat]?.lateral) hit.setAttribute('data-anno-lateral', CATEGORIES[cat].lateral!)
```
Wait — categories don't carry lateral. Lateral is per-element, not per-category. New elements start as unpaired (no attribute). The user sets it via the edit panel. No change needed for addCircleAt/finalizePolygon.
- [ ] **Step 7: Run typecheck and i18n test**
Run: `pnpm typecheck && pnpm test:run -- tests/unit/i18n.dicts.test.ts`
Expected: No errors, i18n parity PASS
- [ ] **Step 8: Commit**
```bash
git add src/app/routes/SvgEditorRoute.tsx src/i18n/fr.ts src/i18n/en.ts
git commit -m "feat(editor): add laterality dropdown to SVG editor"
```
---
### Task 9: Documentation — Update ANATOMY-SVG-CONVENTION.md
**Files:**
- Modify: `docs/ANATOMY-SVG-CONVENTION.md`
- [ ] **Step 1: Add data-anno-lateral to optional attributes table**
In the "Optional data attributes" table, add a row:
```markdown
| `data-anno-lateral` | `string` | Laterality hint: `bilateral` (zone has left/right instances, e.g. knee) or `unpaired` (no laterality). Default when absent: `unpaired`. Used by the report editor to prompt side selection on bilateral zones. |
```
- [ ] **Step 2: Commit**
```bash
git add docs/ANATOMY-SVG-CONVENTION.md
git commit -m "docs(anatomy): document data-anno-lateral attribute"
```
---
### Task 10: Full Verification
- [ ] **Step 1: Run full test suite**
Run: `pnpm test:run`
Expected: ALL PASS
- [ ] **Step 2: Run typecheck**
Run: `pnpm typecheck`
Expected: No errors
- [ ] **Step 3: Run lint**
Run: `pnpm lint`
Expected: No errors
- [ ] **Step 4: Build**
Run: `pnpm build`
Expected: Build succeeds
@@ -1,760 +0,0 @@
# Responsive Mobile Fixes — 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:** Make Faunosteo SPA fully usable on phone screens (375px+) and polished on tablets (768px+) via surgical CSS/className-only changes.
**Architecture:** No behavior changes — pure Tailwind class and CSS media query updates across ~12 files. No store, schema, or PDF changes. Existing tests must stay green since only visual layout changes.
**Tech Stack:** Tailwind CSS v4 (CSS-first), React 19, existing component library
---
### Task 1: Dialog viewport clamping
**Files:**
- Modify: `src/components/ui/Dialog.tsx`
- [ ] **Step 1: Update Dialog SIZE map and container classes**
In `src/components/ui/Dialog.tsx`, replace the SIZE constant and the dialog container/content classes:
```tsx
const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
sm: 'max-w-sm',
md: 'max-w-md',
lg: 'max-w-2xl',
xl: 'max-w-4xl',
}
```
with:
```tsx
const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
sm: 'max-w-sm max-w-[calc(100vw-2rem)]',
md: 'max-w-md max-w-[calc(100vw-2rem)]',
lg: 'max-w-2xl max-w-[calc(100vw-2rem)]',
xl: 'max-w-4xl max-w-[calc(100vw-2rem)]',
}
```
Note: Tailwind applies the last matching utility — `max-w-[calc(100vw-2rem)]` wins on small screens where the named max-width exceeds viewport, and the named max-width wins on large screens where it's smaller. Actually, this won't work — Tailwind just uses specificity/order. Need a different approach.
Instead, add the viewport clamp directly on the motion.div alongside the SIZE class. Change:
```tsx
className={`relative w-full ${SIZE[size]} max-h-[90vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
```
to:
```tsx
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
```
And change the outer container padding from:
```tsx
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
```
to:
```tsx
<div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4">
```
And change the dialog header padding from:
```tsx
<header className="flex items-center justify-between px-6 py-4 border-b border-[var(--color-border)]">
```
to:
```tsx
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
```
And change the dialog body padding from:
```tsx
<div className="px-6 py-4">{children}</div>
```
to:
```tsx
<div className="px-4 sm:px-6 py-3 sm:py-4">{children}</div>
```
The key fix: since all sizes already use `w-full` with `max-w-*`, the dialog box naturally fills available width minus padding. Reducing container padding from `p-4` to `p-3` on small screens gives 6px more breathing room per side. The `max-w-sm` (384px) fits within 375px - 24px = 351px viewport on phones (it doesn't — 384 > 351). The real fix is that `w-full` makes the dialog width = container width = viewport - 2*padding, so the max-w-* values are upper caps that only kick in when there's room.
Wait — `w-full` with `max-w-md` means the dialog takes min(100%, 448px). On a 375px phone with p-3 (12px each side), available width = 375 - 24 = 351px. `w-full` = 351px which is < 448px, so dialog = 351px. This already works correctly. No extra `max-w-[calc(...)]` needed. The existing `w-full` + `max-w-*` pattern is responsive by design.
So the actual changes are: tighten padding for mobile comfort + reduce max-h for better mobile viewport fit.
- [ ] **Step 2: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass (no behavior change)
- [ ] **Step 3: Run typecheck**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm typecheck`
Expected: No errors
- [ ] **Step 4: Commit**
```bash
git add src/components/ui/Dialog.tsx
git commit -m "fix(ui): responsive dialog — tighter mobile padding and max-height"
```
---
### Task 2: Button touch targets
**Files:**
- Modify: `src/components/ui/Button.tsx`
- [ ] **Step 1: Update SIZES to ensure mobile-friendly touch targets**
In `src/components/ui/Button.tsx`, change the SIZES constant from:
```tsx
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',
}
```
to:
```tsx
const SIZES: Record<NonNullable<ButtonProps['size']>, string> = {
sm: 'h-9 px-3 text-sm rounded-md',
md: 'h-10 px-4 text-sm sm:text-base rounded-lg',
lg: 'h-12 px-5 sm:px-6 text-base rounded-lg',
}
```
Changes:
- `sm`: `h-8` → `h-9` (36px, closer to 44px minimum)
- `md`: add responsive text `text-sm sm:text-base`
- `lg`: tighter padding on mobile `px-5 sm:px-6`
- [ ] **Step 2: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass
- [ ] **Step 3: Commit**
```bash
git add src/components/ui/Button.tsx
git commit -m "fix(ui): increase button sm touch target to 36px, responsive text sizing"
```
---
### Task 3: VertebraPicker touch targets
**Files:**
- Modify: `src/components/observation/VertebraPicker.tsx`
- [ ] **Step 1: Increase region tab touch targets**
In `src/components/observation/VertebraPicker.tsx`, change the region tab button className from:
```tsx
'rounded-full px-4 py-1.5 text-sm font-medium border',
```
to:
```tsx
'rounded-full px-4 py-2.5 sm:py-1.5 text-sm font-medium border min-h-[2.75rem]',
```
This ensures 44px minimum height on mobile (py-2.5 = 10px top+bottom + text ≈ 44px), drops back to denser on desktop.
- [ ] **Step 2: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass
- [ ] **Step 3: Commit**
```bash
git add src/components/observation/VertebraPicker.tsx
git commit -m "fix(ui): vertebra picker region tabs — 44px touch target on mobile"
```
---
### Task 4: SVG editor sidebar responsive stacking
**Files:**
- Modify: `src/styles/svg-editor.css`
- [ ] **Step 1: Add media query for sidebar stacking**
In `src/styles/svg-editor.css`, change the `.svg-editor-root` rule from:
```css
.svg-editor-root {
display: flex;
flex: 1;
min-height: 0;
overflow: hidden;
font-family: var(--font-sans);
color: var(--color-ink);
background: var(--color-bg);
}
```
to:
```css
.svg-editor-root {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
font-family: var(--font-sans);
color: var(--color-ink);
background: var(--color-bg);
}
@media (min-width: 768px) {
.svg-editor-root {
flex-direction: row;
}
}
```
Then change the `.svg-editor-sidebar` rule from:
```css
.svg-editor-sidebar {
width: 380px;
background: var(--color-surface);
border-left: 1px solid var(--color-border);
display: flex;
flex-direction: column;
overflow: hidden;
}
```
to:
```css
.svg-editor-sidebar {
width: 100%;
background: var(--color-surface);
border-top: 1px solid var(--color-border);
display: flex;
flex-direction: column;
overflow: hidden;
max-height: 50vh;
}
@media (min-width: 768px) {
.svg-editor-sidebar {
width: 380px;
max-height: none;
border-top: none;
border-left: 1px solid var(--color-border);
}
}
```
Also update `.svg-editor-canvas` to ensure minimum usable height on mobile by changing:
```css
.svg-editor-canvas {
flex: 1;
position: relative;
background: var(--color-surface);
overflow: hidden;
padding: 10px;
}
```
to:
```css
.svg-editor-canvas {
flex: 1;
position: relative;
background: var(--color-surface);
overflow: hidden;
padding: 10px;
min-height: 40vh;
}
@media (min-width: 768px) {
.svg-editor-canvas {
min-height: 0;
}
}
```
Also update the zoom controls for mobile — make buttons bigger:
```css
.svg-editor-zoom-controls button {
width: 32px;
height: 32px;
padding: 0;
margin: 0;
font-size: 16px;
display: flex;
align-items: center;
justify-content: center;
}
```
to:
```css
.svg-editor-zoom-controls button {
width: 40px;
height: 40px;
padding: 0;
margin: 0;
font-size: 18px;
display: flex;
align-items: center;
justify-content: center;
}
@media (min-width: 768px) {
.svg-editor-zoom-controls button {
width: 32px;
height: 32px;
font-size: 16px;
}
}
```
- [ ] **Step 2: Run typecheck and build**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm typecheck && ~/.local/share/pnpm/bin/pnpm build`
Expected: Clean
- [ ] **Step 3: Commit**
```bash
git add src/styles/svg-editor.css
git commit -m "fix(ui): SVG editor sidebar stacks below canvas on mobile (<768px)"
```
---
### Task 5: AnatomyCanvas height constraint + EditorRoute responsive
**Files:**
- Modify: `src/components/canvas/AnatomyCanvas.tsx`
- Modify: `src/app/routes/EditorRoute.tsx`
- [ ] **Step 1: Add responsive classes to AnatomyCanvas wrapper**
In `src/components/canvas/AnatomyCanvas.tsx`, change the wrapper div from:
```tsx
<div
data-testid="anatomy-canvas"
ref={wrapperRef}
className={`svg-canvas relative w-full h-full ${className}`}
>
<div ref={svgRef} className="w-full h-full" />
```
to:
```tsx
<div
data-testid="anatomy-canvas"
ref={wrapperRef}
className={`svg-canvas relative w-full h-full ${className}`}
>
<div ref={svgRef} className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto" />
```
This ensures the SVG inside doesn't overflow and centers horizontally.
- [ ] **Step 2: Update EditorRoute grid layout for mobile**
In `src/app/routes/EditorRoute.tsx`, change the main grid container from:
```tsx
<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">
```
to:
```tsx
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none">
```
The `max-h-[55vh] lg:max-h-none` constrains the SVG canvas on mobile/tablet (single-column) so the observation list is visible without scrolling past the entire SVG. On desktop (lg+, two-column), it fills naturally.
Also change the observations section from:
```tsx
<section className="space-y-6">
```
to:
```tsx
<section className="space-y-4 sm:space-y-6">
```
- [ ] **Step 3: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass
- [ ] **Step 4: Run typecheck**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm typecheck`
Expected: No errors
- [ ] **Step 5: Commit**
```bash
git add src/components/canvas/AnatomyCanvas.tsx src/app/routes/EditorRoute.tsx
git commit -m "fix(ui): constrain anatomy canvas height on mobile, responsive editor spacing"
```
---
### Task 6: Responsive typography and padding — HomeRoute + EditorsRoute
**Files:**
- Modify: `src/app/routes/HomeRoute.tsx`
- Modify: `src/app/routes/EditorsRoute.tsx`
- [ ] **Step 1: Update HomeRoute**
In `src/app/routes/HomeRoute.tsx`, change:
```tsx
<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">{t('home.new_report.title')}</h2>
```
to:
```tsx
<section className="flex-1 grid place-items-center px-4 sm:px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">{t('home.new_report.title')}</h2>
```
And the second card heading too:
```tsx
<Card className="p-6 space-y-4">
<h2 className="font-serif text-2xl">{t('home.import.title')}</h2>
```
to:
```tsx
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">{t('home.import.title')}</h2>
```
- [ ] **Step 2: Update EditorsRoute**
In `src/app/routes/EditorsRoute.tsx`, change:
```tsx
<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">{t('editors.svg.title')}</h2>
```
to:
```tsx
<section className="flex-1 grid place-items-center px-4 sm:px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">{t('editors.svg.title')}</h2>
```
And the second card:
```tsx
<Card className="p-6 space-y-4">
<h2 className="font-serif text-2xl">{t('editors.pathology.title')}</h2>
```
to:
```tsx
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">{t('editors.pathology.title')}</h2>
```
- [ ] **Step 3: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass
- [ ] **Step 4: Commit**
```bash
git add src/app/routes/HomeRoute.tsx src/app/routes/EditorsRoute.tsx
git commit -m "fix(ui): responsive padding and typography on home and editors pages"
```
---
### Task 7: Responsive typography and padding — NewReportRoute
**Files:**
- Modify: `src/app/routes/NewReportRoute.tsx`
- [ ] **Step 1: Update NewReportRoute responsive classes**
In `src/app/routes/NewReportRoute.tsx`, change:
```tsx
<div className="max-w-3xl mx-auto px-6 py-8 space-y-8">
<h1 className="font-serif text-3xl">{t('new_report.title')}</h1>
```
to:
```tsx
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8">
<h1 className="font-serif text-2xl sm:text-3xl">{t('new_report.title')}</h1>
```
- [ ] **Step 2: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass
- [ ] **Step 3: Commit**
```bash
git add src/app/routes/NewReportRoute.tsx
git commit -m "fix(ui): responsive padding and typography on new report page"
```
---
### Task 8: Responsive typography — ObservationList + ConclusionPanel
**Files:**
- Modify: `src/components/observation/ObservationList.tsx`
- Modify: `src/components/report/ConclusionPanel.tsx`
- [ ] **Step 1: Update ObservationList heading**
In `src/components/observation/ObservationList.tsx`, change:
```tsx
<h2 className="font-serif text-xl text-[var(--color-ink)]">
```
to:
```tsx
<h2 className="font-serif text-lg sm:text-xl text-[var(--color-ink)]">
```
- [ ] **Step 2: Update ConclusionPanel heading**
In `src/components/report/ConclusionPanel.tsx`, change:
```tsx
<h2 className="font-serif text-xl text-[var(--color-ink)]">
```
to:
```tsx
<h2 className="font-serif text-lg sm:text-xl text-[var(--color-ink)]">
```
- [ ] **Step 3: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass
- [ ] **Step 4: Commit**
```bash
git add src/components/observation/ObservationList.tsx src/components/report/ConclusionPanel.tsx
git commit -m "fix(ui): responsive typography for observation and conclusion headings"
```
---
### Task 9: Footer and AppHeader mobile polish
**Files:**
- Modify: `src/components/brand/Footer.tsx`
- Modify: `src/components/brand/AppHeader.tsx`
- [ ] **Step 1: Update Footer spacing**
In `src/components/brand/Footer.tsx`, change:
```tsx
<footer className="mt-12 border-t border-neutral-200 bg-neutral-50 py-6 text-center text-sm text-neutral-600">
```
to:
```tsx
<footer className="mt-8 sm:mt-12 border-t border-neutral-200 bg-neutral-50 py-4 sm:py-6 text-center text-xs sm:text-sm text-neutral-600">
```
And the flex container from:
```tsx
<div className="flex flex-wrap items-center justify-center gap-4">
```
to:
```tsx
<div className="flex flex-wrap items-center justify-center gap-2 sm:gap-4">
```
- [ ] **Step 2: Update AppHeader padding**
In `src/components/brand/AppHeader.tsx`, change:
```tsx
<header className="px-6 py-3 border-b border-[var(--color-border)] flex items-center justify-between bg-[var(--color-surface)]">
```
to:
```tsx
<header className="px-3 sm:px-6 py-2 sm:py-3 border-b border-[var(--color-border)] flex items-center justify-between bg-[var(--color-surface)]">
```
And the right-side gap from:
```tsx
<div className="flex items-center gap-4">
```
to:
```tsx
<div className="flex items-center gap-2 sm:gap-4">
```
- [ ] **Step 3: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass
- [ ] **Step 4: Commit**
```bash
git add src/components/brand/Footer.tsx src/components/brand/AppHeader.tsx
git commit -m "fix(ui): responsive footer and header spacing for mobile"
```
---
### Task 10: ReportHeader mobile polish
**Files:**
- Modify: `src/components/report/ReportHeader.tsx`
- [ ] **Step 1: Make report info responsive on mobile**
In `src/components/report/ReportHeader.tsx`, change:
```tsx
<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>{formatDate(report.date, locale)}</div>
</div>
```
to:
```tsx
<div className="text-xs sm:text-sm text-right text-[var(--color-ink-muted)]">
<div className="text-[var(--color-ink)] font-medium truncate max-w-[10rem] sm:max-w-none">
{report.animal.name} · {report.owner.name}
</div>
<div className="hidden sm:block">{formatDate(report.date, locale)}</div>
</div>
```
Changes:
- Smaller text on mobile (`text-xs sm:text-sm`)
- Truncate long names on narrow screens (`truncate max-w-[10rem]`)
- Hide date on very small screens (header is already tight)
- [ ] **Step 2: Run tests**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm test:run`
Expected: All tests pass
- [ ] **Step 3: Commit**
```bash
git add src/components/report/ReportHeader.tsx
git commit -m "fix(ui): responsive report header — compact on mobile"
```
---
### Task 11: Final verification
- [ ] **Step 1: Run full verification suite**
Run:
```bash
cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm typecheck && ~/.local/share/pnpm/bin/pnpm test:run && ~/.local/share/pnpm/bin/pnpm lint && ~/.local/share/pnpm/bin/pnpm build
```
Expected: All clean — typecheck, tests, lint (0 warnings), build success.
- [ ] **Step 2: Dev server visual check**
Run: `cd /home/bchanot-ubuntu/Documents/osteo && ~/.local/share/pnpm/bin/pnpm dev`
Open in browser, test at:
- 375px width (iPhone SE): all pages, editor, dialogs
- 768px width (iPad): editor two-panel, SVG editor with sidebar
- 1280px width (desktop): no regressions
Check:
- No horizontal overflow on any page at 375px
- Dialogs fit within viewport
- SVG editor sidebar stacks below canvas at <768px
- AnatomyCanvas constrained in height on single-column layout
- All buttons tappable (no tiny targets)
- Typography scales appropriately
- Footer wraps cleanly
- [ ] **Step 3: Stop dev server**
@@ -1,378 +0,0 @@
# Osteo Report — MVP Architecture Spec
Date: 2026-05-18
Status: Approved at validation gate #1.
## Purpose
Web app for veterinary osteopaths — any praticien who wants to use it — to
write session bilans on animal anatomy. The praticien selects a species,
clicks anatomical zones on an SVG schematic to build clinical observations
(groups of zones sharing one problem), attaches pathologies (curated DB +
free-text) and severity per observation, writes a conclusion +
recommendations + next RDV, and exports the whole report as a self-contained
A4 PDF whose JSON state is carried as a native PDF attachment. Re-importing
the PDF restores the state for a follow-up.
Multi-species by architecture. v1 ships data for the **horse** (équin) only.
Adding **dog, cat, goat, cow, pig, rabbit, donkey, sheep** later is a pure
data drop: convention-compliant SVG + manifest entry + (eventually)
pathology file under `src/domain/species/<id>/`. No code changes required.
Static SPA, no backend, no auth, no analytics in v1 — the PDF is the only
durable artifact. Deployed as a Docker image serving nginx behind a host
nginx reverse proxy on Scaleway VPS. Identity strings (site name, brand,
footer) come from env vars, never hardcoded. Open-source (MIT).
v1 data set: equine. v1.1+ data sets: chien, chat, chèvre, vache, cochon,
lapin, âne, mouton. Phase 2 also adds multi-praticien accounts +
server-side persistence on the same data contract.
## Stack
| Concern | Choice | Why |
|---|---|---|
| Build | Vite 7 + @vitejs/plugin-react-swc | Fast HMR, ESM-native, no Webpack tax. |
| UI | React 19 + TypeScript 5 strict | Editor complexity warrants components; React 19's automatic memo + concurrent rendering. |
| Styling | Tailwind v4 (CSS-first config) + design tokens in CSS | No PostCSS config, design tokens via @theme. |
| State | Zustand 5 | Lighter than Redux, simpler than Context for editor; selectors avoid re-render storms. |
| Validation | Zod 3 | Mirrors persisted JSON schema, gives import-time errors. |
| PDF | pdf-lib 1.17 | Pure-JS, supports native PDF attachments via `attach()`. |
| SVG raster | canvg 4 → canvas → PNG → `embedPng` | A4 print quality at 2× scale. |
| Animation | motion 11 | Modal transitions, toasts, observation cards. |
| Tests | vitest 3 + happy-dom + RTL | Unit-first; no e2e for MVP. |
| Tooling | ESLint 9 flat config, Prettier, pnpm 9, Node 20 | Modern defaults. |
| Deploy | Multi-stage Docker → nginx:alpine | Static dist served; entrypoint injects env into runtime config. |
## Folder tree
```
osteo/
├─ public/species/equine/{Horse,Horse_head}.svg
├─ src/
│ ├─ app/{App,routes/{Home,NewReport,Editor,NotFound}Route,providers/ConfigProvider}.tsx
│ ├─ config/env.ts
│ ├─ domain/
│ │ ├─ schema/{report,observation,practitioner,animal,pathology}.ts
│ │ └─ species/{registry,types,equine/{index,vertebrae,pathologies}}.ts
│ ├─ state/{reportStore,practitionerCache}.ts
│ ├─ anatomy/{svgLoader,svgConvention,types}.ts
│ ├─ components/
│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip,Toast}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal,ZoneTooltip}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,ObservationEditor,PathologyPicker,VertebraPicker,SeveritySelector,FreeTextPathologyInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,ConclusionPanel,NextAppointmentPicker}.tsx
│ │ └─ brand/Brand.tsx
│ ├─ pdf/{export,import,attachment,fonts}.ts + pdf/render/{header,footer,observationPage,conclusionPage,svgToPng}.ts
│ ├─ lib/{dates,id,assert}.ts
│ ├─ styles/{index,tokens}.css
│ └─ main.tsx
├─ tests/unit/*.test.ts + tests/setup.ts
├─ docs/{ANATOMY-SVG-CONVENTION,ADDING-A-SPECIES,PDF-FORMAT}.md + docs/superpowers/specs/
├─ .claude/{tasks/TODO.md,memory/{decisions,learnings,blockers,journal,evals}.md,audits/.gitkeep}
├─ Dockerfile, docker-compose.yml, nginx.conf
├─ .env.example, .editorconfig, .nvmrc, .prettierrc.json, .gitignore, .dockerignore
├─ eslint.config.js, index.html, package.json, tsconfig*.json, vite.config.ts, vitest.config.ts
└─ CLAUDE.md, README.md, LICENSE (MIT)
```
## Data model
```ts
type Severity = 'légère' | 'modérée' | 'sévère';
type Vertebra = { region: 'C' | 'T' | 'L' | 'S' | 'Cd'; index: number };
type ObservationZone = {
boneId: string; // matches data-anno-id from SVG
detailSourceId?: string; // when this zone came from a detail pop-up SVG
vertebrae?: Vertebra[]; // when boneId is a spine-zone
};
type Observation = {
id: string;
zones: ObservationZone[];
pathologyIds: string[];
freeTextPathologies: string[];
severity?: Severity;
comment: string;
};
type Report = {
version: 1;
id: string;
createdAt: string; // ISO
date: string; // clinical date (ISO)
practitioner: { name: string; cabinet?: string; contact?: string; siret?: string };
animal: { speciesId: string; name: string; breed?: string; age?: string };
owner: { name: string };
observations: Observation[];
conclusion: string;
recommendations: string;
nextAppointment?:
| { kind: 'date'; date: string }
| { kind: 'period'; text: string };
};
type PathologyCategory =
| 'osseux' | 'articulaire' | 'musculaire' | 'tendino-ligamentaire'
| 'fascial' | 'visceral' | 'cranio-sacre' | 'nerveux' | 'autre';
type PathologyRef = {
type: 'manual' | 'journal' | 'database' | 'web';
citation: string; // human-readable
url?: string;
};
type Pathology = {
id: string; // stable kebab-case
labelFr: string;
description: string;
category: PathologyCategory;
speciesIds: string[]; // [] = applicable to all species
boneIds: string[]; // [] = applicable to all zones
sources: PathologyRef[]; // 1+
};
```
All JSON carries `version: 1`. Future migrations bump the version.
## SVG convention (source of truth)
A clickable zone is any element carrying `data-anno-id`. Required data
attributes: `data-anno-id`, `data-anno-name-fr`, `data-anno-name-en`, `data-anno-category`.
Optional: `data-anno-opens-detail="<id>"`.
Categories: `articulation` · `charniere` · `spine-zone` · `os` · `os-overlay`
· `head` · `cadran-crane`.
Two rendering patterns are tolerated in the SVG:
1. **hitbox + visible twin** (articulation, charniere, os-overlay, head):
two elements share the same `data-anno-id`. One has `class*="hitbox"`,
transparent fill, `pointer-events: all`. The other has `class*="visible"`,
colored fill, `pointer-events: none`.
2. **single element** (spine-zone, head zone): one polygon carries everything;
`pointer-events: all` and `cursor: pointer` directly.
Parser strategy (`src/anatomy/svgConvention.ts`):
- Walk all elements with `data-anno-id`.
- Group by `data-anno-id` → one logical `Bone`.
- Bone fields: `id`, `fr`, `en`, `category`, `opensDetail?`, `hitboxEls[]`,
`visibleEls[]`.
- Validate: must have `data-anno-name-fr`, `data-anno-name-en`, `data-anno-category` (in
the allowed enum). Throws structured `SvgConventionError` on missing
attributes.
Click handling: a single delegated listener on the root `<svg>` walks up
from `event.target` to the nearest element with `data-anno-id`. If
`data-anno-opens-detail` is present → open the detail modal mapped via the
species manifest. If the bone's category is `spine-zone` → open the
vertebra picker. Otherwise add the bone to the current observation.
Colorization: when the current observation contains a bone, all elements
matching that `data-anno-id` get a `data-state` attribute toggled by JS:
`current` (solid accent), `linked` (faded dashed border, "in another
observation"), `multi` (striped pattern, "in ≥2 observations").
> MVP scope cut: hover tooltip listing the owning observations is deferred.
> Visual state classes alone communicate participation in v1.
## Detail-popup mechanism
The mapping `detailId → SVG path` is held in the species manifest:
```ts
// src/domain/species/equine/index.ts
export const equine = {
id: 'equine',
mainSvg: '/species/equine/Horse.svg',
details: { head: '/species/equine/Horse_head.svg' },
vertebralFormula: { C: 7, T: 18, L: 6, S: 5, Cd: 18 }, // approx Cd cap
pathologies: () => import('./pathologies'),
};
```
When a zone with `data-anno-opens-detail="head"` is clicked, the canvas
emits a `requestDetail({id: 'head'})` event handled by `DetailModal`, which
loads `/species/equine/Horse_head.svg` and renders it inline. Clicks inside
the modal add zones with `detailSourceId: 'head'` to the current
observation. The "entry" zone (e.g. the head polygon itself) is never
persisted in the report.
## Vertebra picker
Triggered when a clicked bone has `data-anno-category="spine-zone"`. Modal with
region tabs (Cervicales C1–C7, Thoraciques T1–T18, Lombaires L1–L6,
Sacrales S1–S5, Caudales Cd1–Cd18). Each region renders chips in a grid;
multi-select; ≥40 px touch targets; per-region "Tout cocher / décocher".
Stored as `vertebrae: Vertebra[]` on the `ObservationZone` (replaces the
global zone semantically: PDF prints precise vertebrae rather than the
bloc).
If a praticien clicks an individual vertebra (rendered under the same
`bone-id` as the bloc), it is treated identically to clicking the
spine-zone — opens the picker. Avoids duplicate UI paths.
## Multi-observation zone overlay
A bone may belong to several observations. Visual states (`data-state`
attribute on matching SVG elements, styled via `src/styles/index.css`):
- `current` — bone is in the active observation. Solid accent fill.
- `linked` — bone is in another observation (not current). Dashed border,
faded accent fill.
- `multi` — bone is in ≥2 observations. Same fill + heavier stroke to
signal sharing.
> MVP scope cut: per-observation HSL accent cycling (6 clinical-warm tones)
> deferred to v1.1. v1 uses a single accent color across all states; PDF
> renders per-observation pages, so colour ambiguity does not bleed into
> the printed report.
## PDF format
A4 portrait (595.28 × 841.89 pt). One pdf-lib document per export. Pages
share a header drawer (praticien left block, animal+owner+date right) and a
footer drawer (env-driven brand name, export date, page x/y).
Per observation: one page with
- the full main SVG rasterized at 2× scale with that observation's zones
colored (canvg writes to canvas → PNG → `embedPng`);
- if the observation includes detail-sourced zones (e.g. head): a second
rasterization of the detail SVG with those zones colored, placed beside
or below the main raster;
- a structured block beneath the schematic: zones (with precise vertebrae
formatted as "T12, T15"), pathologies (selected + free-text), severity,
comment.
> MVP scope cut: source citations under each cited pathology are deferred
> to post-MVP. Pathology IDs/labels render without their `sources[]` block.
Final page: conclusion, recommendations, next appointment.
JSON attachment: the full `Report` object is serialized and attached via
`pdfDoc.attach(bytes, 'osteo-report.json', { mimeType: 'application/json',
description: 'Osteo Report state v1', creationDate, modificationDate,
afRelationship: 'Data' })`. Bytes are pretty-printed JSON (UTF-8).
MVP fonts: pdf-lib standard Helvetica + Helvetica-Bold (body) + Times-Roman
(headings). Inter Sans + Fraunces TTF bundling deferred to v1.1 to avoid
shipping ~600KB of font assets in the initial Docker image.
## PDF import
`pdf-lib loadDocument()` → walk catalog `Names → EmbeddedFiles` tree → find
an attachment whose filename starts with `osteo-report` and whose mime is
`application/json` (or, fallback, parse-then-validate). Extract the stream,
flate-decompress if needed (pako), parse JSON, validate with Zod. On
success: hydrate the store and route to `/editor`. On failure: throw
`ImportError` with the French message
"Ce PDF n'a pas été généré par Osteo Report (pas de données détectées)." and
show a toast.
## Configurable identity
Env vars consumed at runtime:
| Name | Default | Use |
|---|---|---|
| `PORT` | `8080` | nginx listen port. |
| `APP_SITE_NAME` | `Osteo Report` | `<title>`. |
| `APP_BRAND_NAME` | `Osteo Report` | UI header, hero. |
| `APP_FOOTER_NAME` | `Osteo Report` | PDF footer. |
| `APP_TAGLINE` | `Bilans d'ostéopathie animalière` | Home tagline. |
Mechanism: Docker entrypoint templates `index.html` to inject a
`<script>window.__APP_CONFIG__ = {...}</script>` tag using container env
vars. `src/config/env.ts` reads `window.__APP_CONFIG__` first, falls back
to `import.meta.env.VITE_APP_*` build-time values, then to defaults.
`ConfigProvider` exposes the resolved config via React context. No identity
string is hardcoded in any component.
## Routes
- `/` — Home. Two CTAs ("Nouveau bilan", "Importer un PDF"). Quick-resume
card if a sessionStorage draft exists.
- `/new` — New report form. Species select (equine only for MVP),
praticien fields (prefilled from `osteo:lastPractitioner`), animal
(name + optional race/age), owner name, date (default today).
- `/editor` — Editor. Split layout: anatomy canvas + observation panel.
Bottom bar: export button.
- `*` — NotFoundRoute.
## State persistence
- Zustand store in memory.
- sessionStorage mirror (`osteo:draft`) auto-restored on `/editor` if the
user reloads accidentally; cleared after export.
- localStorage (`osteo:lastPractitioner`) caches the praticien block to
prefill next "Nouveau bilan".
- No long-term storage. PDF is the only durable artifact.
## Test strategy
- vitest + happy-dom.
- TDD-first for: schema (Zod parse + reject malformed), store actions, id
generator, anatomy convention parser (valid SVG → bones; bad SVG →
structured error), pathology DB integrity (every entry validates + has
≥1 source), pdf attachment write+extract roundtrip on a fixture file.
- UI smoke test: AnatomyCanvas mounts a fixture SVG and emits click for a
known bone.
- No e2e (no gstack plugin); manual QA in browser before commit.
## Docker / deploy
Multi-stage Dockerfile:
1. **builder** — `node:20-alpine`. `corepack enable && pnpm i --frozen-lockfile && pnpm build`.
2. **runner** — `nginx:alpine`. Copy `dist/` to `/usr/share/nginx/html`,
custom `nginx.conf` listening on `${PORT:-8080}`, `entrypoint.sh` writes
`/usr/share/nginx/html/env.js` from `APP_*` env vars, then runs nginx.
`docker-compose.yml` exposes `${PORT}:${PORT}` and passes `APP_*` env vars
through `env_file`. The host nginx reverse-proxies any subdomain to that
port.
## Open decisions resolved
| Decision | Resolution |
|---|---|
| SVG injection | Fetch text → DOMParser → inline render (consistent + CSS-controllable + sandboxing irrelevant since assets are local). |
| Vertebra picker UX | Region tabs + chip grid, multi-select, ≥40 px touch targets. |
| Multi-obs zone overlay | current / linked / multi states; striped pattern + tooltip. |
| Detail SVG trigger | `data-anno-opens-detail` → modal with inline detail SVG, clicks add to current obs. |
| SVG → PDF | canvg → canvas @ 2× → PNG → `embedPng`. |
| Pathology sources in PDF | Abbreviated citation list below each obs, no raw URLs. |
| Brand env vars | Runtime `window.__APP_CONFIG__` + Vite-define fallback. |
| MVP scope | Equine only. |
| Drag-reorder obs | ↑/↓ buttons, no DnD. |
| Practitioner default | localStorage cache. |
| State persistence | sessionStorage mirror + PDF for long-term. |
| Animation lib | motion 11. |
| License | MIT. |
## Prerequisites / REMAINING
- Real anatomical SVGs delivered by user at repo root: `Horse.svg` +
`Horse_head.svg`. Moved into `public/species/equine/` by the scaffolder.
- **Pathology DB authoring — deferred to post-MVP.** v1 ships with an
empty `EQUINE_PATHOLOGIES = []` and a relaxed integrity test (length
0..100). Pathology picker shows the "aucune pathologie de référence"
empty-state; praticien adds entries via free-text. Client osteo (or a
Phase 2 multi-user authoring tool) will populate the curated DB once
the long-term account architecture is decided.
- **Source citations in PDF — deferred to v1.1.** Once the DB exists,
re-enable the abbreviated-citation block on each observation page.
- **Hover tooltip on canvas — deferred to v1.1.** Visual state classes
alone in v1.
- **Per-observation HSL accent cycling — deferred to v1.1.** Single
accent in v1.
- **Inter + Fraunces TTF bundling — deferred to v1.1.** PDF uses standard
Helvetica + Times-Roman in v1.
- **`docs/ADDING-A-SPECIES.md` — content to be authored** from the
observed SVG convention + species manifest pattern (placeholder file
exists today).
- Final brand name, domain, identity strings.
- Phase 2 (out of MVP): user accounts, server persistence, animal history,
and curated pathology DB authoring tooling.
@@ -1,115 +0,0 @@
# B3 — i18n FR/EN (site + PDF) — Design
**Date:** 2026-05-20
**Branch:** `feat/findings-tree-v2`
**Status:** Approved → implementation
**Cross-refs:** TODO.md Phase B B3; BDR-010 (snapshot labels at selection); BDR-009 (snake_case JSON fields preserved); LRN-012 (sessionStorage once-per-session modal)
---
## 1. Goal
Add bilingual French / English UI and PDF export to Osteo Report. Practitioner picks the locale; all interface strings and PDF static labels render in that locale. Finding leaf names render via the dual snapshot already stored on each `Finding` (`labelFrSnapshot` / `labelEnSnapshot`).
Out of scope for this iteration: catalog `description_fr` (vet-expert authoring required) and `scope_disclaimer` (vet legal review). They stay FR-only until an expert provides EN copy.
## 2. Architecture
```
localeStore (Zustand, persist key osteo:locale)
↓ subscribe
useT() hook → (key: string) => string // resolves against active dict
↓
Components/routes import useT, replace hardcoded FR with t('key.path')
↓
LanguageSwitcher in ReportHeader calls localeStore.setLocale(...)
formatDate(iso, locale) // src/lib/dates.ts — replaces formatDateFr
exportReportToPdf(report, { locale }) // explicit, no default
→ static eyebrows/labels via dict snapshot at call time
→ findings rendered via labelFrSnapshot or labelEnSnapshot per locale
→ header date via formatDate(iso, locale)
```
## 3. File plan
### New files (`src/`)
- `src/state/localeStore.ts` — Zustand store `{ locale: Locale, setLocale(l: Locale) }`, persists to `localStorage.osteo:locale`. Default `'fr'` if unset.
- `src/i18n/types.ts` — `export type Locale = 'fr' | 'en'`; `export type Dict = Record<string, string>`.
- `src/i18n/fr.ts` — FR dict (~60 keys, flat snake_case namespaces e.g. `editor.add_observation`).
- `src/i18n/en.ts` — EN equivalents, same keys.
- `src/i18n/index.ts` — `export const dicts: Record<Locale, Dict> = { fr, en }`; `export function getDict(locale: Locale): Dict`.
- `src/i18n/useT.ts` — `useT(): (key: string) => string`. Subscribes to localeStore. Missing key → returns key literal + `console.warn` (dev only).
- `src/components/brand/LanguageSwitcher.tsx` — segmented `FR | EN` toggle, `aria-pressed` per button, calls `setLocale`.
### Edited files (`src/`)
- `src/lib/dates.ts` — add `formatDate(iso: string, locale: Locale): string`; remove `formatDateFr` (callers migrate).
- `src/components/report/ReportHeader.tsx` — render `<LanguageSwitcher/>` next to Brand.
- `src/app/routes/{Home,NewReport,Editor,NotFound}Route.tsx` — strings via `t()`.
- `src/components/observation/{FindingsTreePicker,ObservationCard,FreeTextFindingInput,VertebraPicker,SeveritySelector}.tsx` — strings via `t()`; finding leaf label = `locale === 'en' ? labelEnSnapshot : labelFrSnapshot`. The picker tree itself reads `name_fr`/`name_en` from the catalog by current locale.
- `src/components/report/{PractitionerForm,AnimalForm,ConclusionPanel,NextAppointmentPicker}.tsx` — strings via `t()`.
- `src/pdf/export.ts` — signature changes to `exportReportToPdf(report: Report, opts: { locale: Locale })`. All callers updated.
- `src/pdf/render/{header,footer,observationPage,conclusionPage}.ts` — accept `locale` argument; static labels (eyebrows, section titles, "Sévérité", "Conclusion", date prefix, page numbers if any) read from dict; finding labels via correct snapshot; date via `formatDate(_, locale)`.
### Test files (`tests/unit/`)
- `state.localeStore.test.ts` (NEW) — 3 tests: default fr, setLocale updates state, persists to localStorage on change.
- `i18n.useT.test.tsx` (NEW) — 2 tests: returns dict value for active locale, missing key returns key + warns.
- `components.LanguageSwitcher.test.tsx` (NEW) — 2 tests: click toggles store, aria-pressed reflects active locale.
- `lib.dates.test.ts` (EDIT) — replace `formatDateFr` cases; cover `formatDate('2026-05-20', 'fr')` → `'20 mai 2026'`; `formatDate(..., 'en')` → `'May 20, 2026'`.
- `pdf.export.test.ts` (EDIT) — add roundtrip per locale: export `{ locale: 'fr' }` and `{ locale: 'en' }`, re-import both, assert JSON attachment intact; assert returned PDF bytes differ; minimal byte presence check is unreliable for subset fonts (LRN-016) so cover via the imported JSON only.
## 4. Dict key conventions
- Flat namespace `<area>.<key>` (e.g. `editor.add_observation`, `pdf.eyebrow_observation`).
- Keys are snake_case English.
- Values are the human string.
- Both dicts have the **same set of keys** — verify via a single unit test that compares `Object.keys(fr).sort()` to `Object.keys(en).sort()`.
## 5. Locale resolution rules
| Source | Behavior |
|---|---|
| `localStorage.osteo:locale` present and valid | use it |
| Missing or invalid | default `'fr'`, do not write back yet |
| `setLocale(l)` | update store + write `localStorage.osteo:locale = l` |
| `localStorage` write fails | swallow, in-memory only, no user error |
PDF export does **not** default a locale — caller must pass it. Route layer reads the store at the export call site.
## 6. Out of scope (explicit)
- Catalog `description_fr` and `scope_disclaimer` translation (vet-expert / legal pass needed).
- Native `input[type=date]` widget labels (browser/OS).
- Brand identity strings (env-driven via `useConfig()`).
- Zod schema error messages emitted to console (dev-only).
## 7. Acceptance criteria
- Switching the locale updates every visible UI string at the next render.
- Locale persists across reload (verifiable in QA via DevTools localStorage).
- Re-importing a PDF does NOT change the active locale — the imported report uses whatever the store currently holds for next export.
- PDF exports in `'fr'` and `'en'` have different static eyebrow / section / date strings; the embedded JSON is byte-identical between the two locales for the same `Report` (locale lives outside the report).
- 139 existing tests + 11 new tests = 150+ pass. Lint clean. Typecheck clean. Vite build OK.
## 8. Risks / open questions
- **Risk**: forgotten hardcoded FR strings. Mitigation: grep-pass over `src/` after migration for `'É'`, `'è'`, `'à'`, `' du '`, `'pour'` etc. as a heuristic + verify in QA.
- **Risk**: changing `formatDateFr` → `formatDate` breaks PDF render. Mitigation: TypeScript will flag every caller; covered by typecheck.
- **Open**: should the dict be lazily loaded per locale? Decision: NO — both dicts are tiny (~3KB each), eager import in `i18n/index.ts` keeps the bundle simple. Revisit if dict grows past 50KB.
## 9. Verification plan
```bash
pnpm typecheck
pnpm lint
pnpm test:run # 150+ tests green
pnpm build # bundle still <1MB main
```
Manual QA after build:
1. `pnpm dev` → switch locale → all visible strings update.
2. Create a report → export FR PDF → re-import → re-export EN PDF → diff strings.
3. Reload → locale persists.
@@ -1,387 +0,0 @@
# Pathology Editor — Design Spec
**Date**: 2026-05-22
**Status**: Draft
**Scope**: Standalone HTML tool for editing species pathology JSON via SVG-based zone selection
---
## 1. Overview
Single-file standalone HTML tool (`pathology-editor.html` at project root) that lets users visually select anatomical zones on an SVG and edit the corresponding pathology tree in the species JSON. Same architectural pattern as `editor.html` (SVG editor): vanilla JS/CSS, no build step, no dependencies.
The tool never modifies source files. It works on an in-memory copy and exports a downloadable JSON file.
---
## 2. Layout
Two-panel horizontal layout, identical to SVG editor:
| Panel | Width | Content |
|-------|-------|---------|
| Left (canvas) | flex: 1 | SVG display, click-to-select zones |
| Right (sidebar) | 380px | Source picker → zone info → tree editor → export |
Sidebar is scrollable. Canvas contains the SVG with auto-viewBox (same logic as `editor.html`).
---
## 3. Source Selection
On launch, sidebar shows source picker with two modes:
### 3a. Pre-wired list
Two-step selection:
1. **Species dropdown** — lists registered species (MVP: "Cheval" only)
2. **View dropdown** — lists available SVGs for selected species
Hardcoded config (easily extensible):
```javascript
const SPECIES_CONFIG = [
{
id: 'equine',
label: 'Cheval',
jsonPath: '/species/equine/pathologies.json',
views: [
{ label: 'Corps complet', svgPath: '/species/equine/Horse.svg' },
{ label: 'Tête (détail)', svgPath: '/species/equine/Horse_head.svg' },
],
},
];
```
**Pre-requisite**: `pathologies.json` must be copied (or symlinked) to `public/species/equine/pathologies.json` so it's accessible via HTTP when served statically. The source of truth remains `src/domain/species/equine/pathologies.json` — the public copy is read-only for the editor.
"Charger" button fetches both files. If either fetch fails, show error with HTTP status.
All views of a species share the same JSON. Switching view reloads SVG only, keeps JSON state.
### 3b. Manual upload
Two file inputs:
- "Fichier SVG" — accepts `.svg`
- "Fichier JSON" — accepts `.json`
Both required. If only one provided, "Charger" button disabled with message: "Les deux fichiers (SVG et JSON) sont obligatoires."
Files read via `FileReader` as UTF-8 text.
### Source switch
After loading, sidebar transitions to editing mode. A "Changer de source" link at the top returns to the source picker. Switching source discards current edits (with confirmation if modifications exist).
---
## 4. SVG Display
### Loading
Parse SVG text, inject into canvas container as inline SVG. Auto-viewBox: if `viewBox` attribute missing, compute from SVG `width`/`height` or `getBBox()` and set it (same as `editor.html` pattern).
### Zone detection
Walk all SVG elements. An element is a clickable zone if it has `data-anno-id` AND at least one of `data-anno-name-fr` or `data-anno-name-en`.
### Interaction
- **Hover**: subtle opacity/highlight change on annotated elements
- **Click**: select zone (see section 5)
- **Selected state**: distinct highlight color (blue outline or fill overlay), persists until another zone clicked
No editing of SVG content. SVG is read-only visual selector.
---
## 5. Zone Selection Logic
When user clicks an annotated SVG element:
### Step 1 — Read SVG attributes
Extract from clicked element (walk up DOM to find `data-anno-id` parent if needed):
- `data-anno-id`
- `data-anno-name-fr`
- `data-anno-name-en`
- `data-anno-opens-detail` (if present)
- `data-anno-special` (if present)
### Step 2 — Special attribute handling
| Attribute | Behavior |
|-----------|----------|
| `data-anno-opens-detail` present | Show info message: "Zone de navigation vers un SVG de détail — non éditable ici. Chargez le SVG de détail pour éditer ses zones." Do NOT open tree editor. |
| `data-anno-special` present (e.g., `vertebral-precision`) | Treat as normal editable zone. `special` attribute is irrelevant to pathology editing. |
### Step 3 — Fuzzy match to JSON zone
Match SVG `name_fr`/`name_en` against `zones[*].name_fr`/`name_en` in loaded JSON.
Matching algorithm (port from `src/lib/zoneMatch.ts`):
1. Normalize both strings: `str.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]/g, '')`
2. Score pairs (SVG label vs JSON zone label):
- Exact match → score 0
- Substring containment → score 1
- Levenshtein distance ≤ 25% of max length (min 2 edits) → score 2 + distance
3. Priority: EN-on-EN first, FR-on-FR second, cross-language last
4. Take lowest score. If no candidate below threshold → no match.
### Step 4 — Result
| Result | Sidebar action |
|--------|---------------|
| Match found | Select zone, show tree editor for matched zone |
| No match | Show "Aucune zone correspondante dans le JSON" + "Créer cette zone" button |
### Creating a new zone
"Créer cette zone" pre-fills:
- `id`: generated from `name_en` (fallback `name_fr`) → kebab-case (see section 7 for ID generation)
- `name_fr`: from SVG `data-anno-name-fr`
- `name_en`: from SVG `data-anno-name-en`
- `categories`: empty array `[]`
Zone added to in-memory JSON `zones` object immediately.
---
## 6. Pathology Tree Editor
### Zone header
When a zone is selected, sidebar shows:
- Zone name: `name_fr` / `name_en` (read-only display, not editable — zone names come from SVG)
- Zone ID: displayed as badge (read-only)
- Zone stats: count of categories, total node count
### Tree display
Recursive collapsible tree rendering all `categories` and their nested `children`:
```
📁 Dysfonctions ostéopathiques [+ Ajouter enfant] [✏️] [🗑️]
📁 Lésions de mobilité [+ Ajouter enfant] [✏️] [🗑️]
🔹 En flexion (rotation externe) [✏️] [🗑️]
🔹 En extension (rotation interne) [✏️] [🗑️]
📁 Lésions intra-osseuses [+ Ajouter enfant] [✏️] [🗑️]
🔹 Compression intra-osseuse [✏️] [🗑️]
📁 Observations / motifs de consultation [+ Ajouter enfant] [✏️] [🗑️]
...
```
Visual conventions:
- 📁 = node with `children` (category/intermediate) — collapsible
- 🔹 = leaf node (no `children` or empty `children`) — selectable by practitioner in main app
- Indentation: 20px per level
- Collapse state: all collapsed by default, expand on click
### Node operations
#### Edit node (✏️)
Click edit icon → inline form expands below the node:
| Field | Type | Required |
|-------|------|----------|
| `name_fr` | text input | yes |
| `name_en` | text input | yes |
| `description_fr` | textarea | no |
| `description_en` | textarea | no |
| `requires_vet_referral` | checkbox | no (default false) |
| Sources | repeatable row group | no |
Each source row:
- `type`: select dropdown (`manual`, `journal`, `database`, `web`)
- `citation`: text input
- `url`: text input (optional)
- [Remove source] button
[Add source] button below sources list.
"Enregistrer" saves changes to in-memory JSON. "Annuler" discards form.
When saving, `id` is NOT editable — it was set at creation and remains stable.
#### Add child node (+ Ajouter enfant)
Available on any node. Opens inline form (same as edit) for the new child.
On save:
- New node inserted as last child of parent
- `id` auto-generated from `name_en` (see section 7)
- If parent was a leaf (no `children`), it becomes a category (gets `children` array)
#### Add root category (+ Ajouter catégorie)
Button at bottom of zone's tree. Creates new top-level category in `categories` array.
#### Delete node (🗑️)
Click delete → confirmation dialog: "Supprimer « {name_fr} » et tous ses enfants ({N} nœuds) ?"
On confirm: remove node and entire subtree from parent's `children` (or from zone's `categories` if root-level).
### No reordering
Drag-and-drop reordering excluded from this version. Node order matches JSON array order.
---
## 7. ID Generation
Auto-generate `id` for new nodes and zones:
```javascript
function generateId(nameEn, nameFr, existingSiblingIds) {
const source = (nameEn || nameFr || 'node').trim();
let slug = source
.normalize('NFD')
.replace(/[̀-ͯ]/g, '') // strip accents
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-') // non-alnum → hyphen
.replace(/^-|-$/g, ''); // trim leading/trailing hyphens
if (!slug) slug = 'node';
// Ensure uniqueness among siblings
let candidate = slug;
let counter = 2;
while (existingSiblingIds.includes(candidate)) {
candidate = `${slug}-${counter}`;
counter++;
}
return candidate;
}
```
---
## 8. JSON Export
### Trigger
"Télécharger JSON" button — always visible in sidebar header area, enabled once source is loaded.
### Output
- Full JSON object with all root fields preserved: `schema_version`, `scope_disclaimer`, `species`, `zones`
- ALL zones included (modified + unmodified)
- UTF-8 encoding, 2-space indentation
- Filename: `pathologies-{speciesId}-{YYYYMMDD-HHmmss}.json` (or `pathologies-custom-{timestamp}.json` for manual uploads)
### Implementation
```javascript
const blob = new Blob(
[JSON.stringify(jsonData, null, 2)],
{ type: 'application/json;charset=utf-8' }
);
const url = URL.createObjectURL(blob);
// trigger download via <a> element
```
### Integrity rules
- Never drop fields from nodes (even if empty/optional — omit only if truly absent)
- Never reorder zone keys (use insertion order from original parse)
- `schema_version` preserved as-is (no auto-bump)
- Empty `children: []` on a leaf is valid and preserved if originally present
---
## 9. Unsaved Changes Protection
Track modification state (dirty flag). When user attempts to:
- Switch source → confirm dialog: "Des modifications non enregistrées seront perdues. Continuer ?"
- Close/navigate away → `beforeunload` event handler
---
## 10. Error Handling
| Scenario | Behavior |
|----------|----------|
| SVG fetch fails (pre-wired) | Show error: "Impossible de charger le SVG: {status}" |
| JSON fetch fails (pre-wired) | Show error: "Impossible de charger le JSON: {status}" |
| JSON parse error | Show error: "Le fichier JSON est invalide: {error.message}" |
| JSON missing required root fields | Show error: "Structure JSON invalide: champ '{field}' manquant" |
| SVG has no annotated elements | Show warning: "Aucun élément annoté (data-anno-*) trouvé dans ce SVG" |
| Uploaded file too large (>10MB) | Show error: "Fichier trop volumineux (max 10 Mo)" |
---
## 11. Styling
Consistent with `editor.html` aesthetic:
- Dark header bar with tool title
- White sidebar background, light gray canvas background
- System font stack: `-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`
- Buttons: solid background (blue primary, red destructive, gray secondary)
- Inputs: bordered, rounded, consistent padding
- Tree nodes: hover highlight, selected state with left border accent
- Responsive: min-width 900px, below that show a "use larger screen" message
---
## 12. File Structure
Single file: `pathology-editor.html` at project root (same level as `editor.html`).
No external dependencies. All CSS inline in `<style>`. All JS inline in `<script>`.
Approximate structure:
```html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex,nofollow">
<title>Faunosteo — Éditeur de pathologies</title>
<style>/* all styles */</style>
</head>
<body>
<header><!-- title bar --></header>
<main>
<div id="canvas"><!-- SVG container --></div>
<aside id="sidebar"><!-- source picker / tree editor --></aside>
</main>
<script>/* all logic */</script>
</body>
</html>
```
---
## 13. Out of Scope
- Node drag-and-drop reordering
- Undo/redo history
- Multi-zone selection
- Zone name editing (names come from SVG, not JSON)
- SVG modification or export
- Schema version auto-bumping
- Diff/merge between JSON versions
- Integration as React route (standalone only)
---
## 14. Acceptance Criteria
1. Pre-wired source loads SVG + JSON from local paths, displays SVG with clickable zones
2. Manual upload accepts SVG + JSON files, rejects incomplete uploads
3. Clicking annotated SVG zone matches to JSON zone via fuzzy matching
4. Clicking `data-anno-opens-detail` zone shows navigation info, not tree editor
5. Tree editor displays full recursive hierarchy for selected zone
6. Can add node at any level (root category, intermediate, leaf)
7. Can edit all node fields (name_fr, name_en, descriptions, vet referral, sources)
8. Can delete node with confirmation, removes entire subtree
9. New node IDs auto-generated as unique kebab-case slugs
10. "Créer cette zone" works for SVG zones with no JSON match
11. Downloaded JSON contains all zones (modified + unmodified) with root fields preserved
12. Downloaded JSON is valid UTF-8 with 2-space indentation
13. Unsaved changes trigger confirmation on source switch and page close
14. All error scenarios show user-facing French messages
@@ -1,234 +0,0 @@
# Laterality Support — Design Spec
**Date**: 2026-05-23
**Status**: Approved
**Approach**: A — per-zone SVG attribute + inline side picker + separate observation entries
---
## Problem
Anatomical zones have no laterality concept. A practitioner clicking "Genou" (knee) creates one observation zone without specifying left or right. Bilateral structures (knee, hip, shoulder) need side differentiation; midline/unpaired structures (spine, sternum) do not.
## Solution Overview
Three layers:
1. **SVG convention** — new `data-anno-lateral` attribute marks zones as bilateral or unpaired
2. **Report schema** — new `side` field on `ObservationZone` records which side
3. **UI** — LateralityPicker modal when clicking bilateral zones; badge display shows side
Backward-compatible: missing attribute = unpaired, `side` field is optional.
---
## 1. SVG Convention
New optional attribute on annotated elements:
| Attribute | Values | Default when absent |
|---|---|---|
| `data-anno-lateral` | `bilateral` \| `unpaired` | `unpaired` |
- `bilateral`: zone has left and right instances (e.g. knee, hip, shoulder)
- `unpaired`: zone has no laterality (e.g. sternum, sacrum) or laterality is not relevant
The parser reads and forwards this attribute like `data-anno-special` — optional, opaque string. The `Bone` interface gains a `lateral` field.
### Validation
- If present, value must be `bilateral` or `unpaired`. Any other value → `SvgConventionError`.
- If absent → treated as `unpaired` at the application level (not by the parser — parser sets `undefined`, app code defaults).
### Doc update
`docs/ANATOMY-SVG-CONVENTION.md` gains a row in the optional attributes table.
---
## 2. Schema Changes
### ObservationZone
```ts
export const LateralSideSchema = z.enum(['left', 'right'])
export type LateralSide = z.infer<typeof LateralSideSchema>
export const ObservationZoneSchema = z.object({
boneId: z.string().min(1),
detailSourceId: z.string().optional(),
vertebrae: z.array(VertebraSchema).optional(),
side: LateralSideSchema.optional(),
})
```
Rules:
- `side` is present only when the bone is bilateral
- Unpaired zones never carry `side`
- Two zones with same `boneId` but different `side` values are valid (left knee + right knee in same observation)
- No schema version bump — `side` is additive and optional; old reports parse cleanly
### Bone interface
```ts
export interface Bone {
id: string
fr: string
en: string
category: BoneCategory
opensDetail?: string
special?: string
lateral?: 'bilateral' | 'unpaired' // NEW
els: Element[]
}
```
---
## 3. SVG Parser Changes
`parseSvgBones()` reads `data-anno-lateral` from SVG elements and sets `Bone.lateral`:
```ts
const lateral = el.getAttribute('data-anno-lateral') ?? undefined
```
Merging logic (multiple elements sharing same `data-anno-id`): first non-undefined `lateral` value wins, same pattern as `special` and `opensDetail`.
No validation of the value in the parser — validation happens at the convention level if desired. The parser is permissive (accepts any string); the application layer checks for known values.
---
## 4. UX Flow — LateralityPicker
### Trigger
When practitioner clicks a bilateral zone (`bone.lateral === 'bilateral'`):
1. **LateralityPicker** modal opens with three options:
- Gauche / Left
- Droite / Right
- Les deux / Both
2. Selection behavior:
- "Left" → adds `ObservationZone { boneId, side: 'left' }`
- "Right" → adds `ObservationZone { boneId, side: 'right' }`
- "Both" → adds two entries: `{ boneId, side: 'left' }` + `{ boneId, side: 'right' }`
3. Duplicate prevention: if a zone with the same `boneId + side + detailSourceId` already exists in the active observation, skip silently.
4. Re-click behavior: if the zone already has one or both sides in the observation, the picker opens again so the user can add the missing side. If both sides already exist, clicking removes both (toggle off — matching current toggle behavior for unpaired zones).
### Component
`src/components/observation/LateralityPicker.tsx`
- Reuses `Dialog` component for modal shell
- Three `Button` components for the choices
- Receives `onSelect(sides: LateralSide[])` callback
- Small, focused modal — not a full-screen overlay
### Integration point
`EditorRoute.onZoneClick()` — after the `opensDetail` check and `vertebral-precision` check, before the toggle logic:
```
if bone.lateral === 'bilateral' → open LateralityPicker
→ onSelect callback adds zone(s) with side
else → existing toggle logic (unpaired zone)
```
---
## 5. Zone Badge Display
In `ObservationCard`, the `describeZone()` function appends a side suffix for bilateral zones:
- FR: `Genou (G)` for left, `Genou (D)` for right
- EN: `Knee (L)` for left, `Knee (R)` for right
The short labels come from i18n keys `lateral.left_short` / `lateral.right_short`.
Format: `{zoneName} ({sideShort})`
---
## 6. SVG Editor Changes
In the edit panel (`svg-editor-osteo-fields`), a new select dropdown after the category select:
```html
<label>Latéralité / Laterality</label>
<select id="svg-editor-edit-lateral">
<option value="">Impair / Unpaired</option>
<option value="bilateral">Bilatéral / Bilateral</option>
</select>
```
Behavior:
- Reads `data-anno-lateral` from selected element on select
- Writes `data-anno-lateral` attribute on change (removes attribute if "unpaired" selected)
- Propagates to sibling elements sharing same `data-anno-id` (same pattern as category/name propagation)
- Exported SVG includes the attribute
### Backward compatibility
Existing SVGs loaded in the editor: zones without `data-anno-lateral` show "Impair" (default). User can change to "Bilatéral" and re-export.
---
## 7. PDF Output
Zone labels in PDF include side when present:
- FR: `Genou (Gauche)`, `Genou (Droit)`
- EN: `Knee (Left)`, `Knee (Right)`
Uses full side name (not abbreviation) for PDF clarity.
The `describeZone()` helper used in PDF rendering checks `zone.side` and appends the localized label.
---
## 8. i18n Keys
New keys in `src/i18n/fr.ts` and `src/i18n/en.ts`:
| Key | FR | EN |
|---|---|---|
| `lateral.which_side` | Quel côté ? | Which side? |
| `lateral.left` | Gauche | Left |
| `lateral.right` | Droite | Right |
| `lateral.both` | Les deux | Both |
| `lateral.left_short` | G | L |
| `lateral.right_short` | D | R |
| `lateral.bilateral` | Bilatéral | Bilateral |
| `lateral.unpaired` | Impair | Unpaired |
---
## 9. Scope Exclusions
- No changes to findings tree — findings are zone-level, same pathologies apply to both sides
- No SVG visual differentiation between left/right — same zone highlights for both sides
- No auto-detection of laterality from zone names
- No report schema version bump — additive optional field
- No changes to PDF attachment format — JSON includes `side` field naturally
---
## 10. Files Touched
| File | Change |
|---|---|
| `src/anatomy/types.ts` | Add `lateral` to `Bone` interface |
| `src/anatomy/svgConvention.ts` | Read `data-anno-lateral` in parser |
| `src/domain/schema/observation.ts` | Add `LateralSideSchema`, `side` field |
| `src/components/observation/LateralityPicker.tsx` | NEW — modal component |
| `src/components/observation/ObservationCard.tsx` | Update `describeZone()` |
| `src/app/routes/EditorRoute.tsx` | Integrate LateralityPicker in click flow |
| `src/app/routes/SvgEditorRoute.tsx` | Add lateral dropdown in edit panel |
| `src/i18n/fr.ts` | Add lateral keys |
| `src/i18n/en.ts` | Add lateral keys |
| `src/pdf/render/observationPage.ts` | Update zone label rendering |
| `docs/ANATOMY-SVG-CONVENTION.md` | Document `data-anno-lateral` |
| `tests/unit/observation.test.ts` | Test side field parsing |
@@ -1,98 +0,0 @@
# Responsive / Mobile-First — Surgical Fixes
**Date**: 2026-05-23
**Approach**: A — surgical fixes, no layout redesign
**Target**: phone-first (375px+), tablet perfect (768px+)
**Baseline score**: 40/100 responsive readiness
**Target score**: 80+/100
---
## Scope
Pure CSS/className changes. Zero store, schema, or PDF impact. ~12-15 files.
---
## 1. Dialog viewport clamping
**File**: `src/components/ui/Dialog.tsx`
- All size variants get `max-w-[calc(100vw-2rem)]` so dialogs never exceed viewport
- Backdrop padding: `p-4` → `p-2 sm:p-4`
- Dialog content padding responsive where needed
## 2. SVG Editor sidebar — stack on mobile
**File**: `src/styles/svg-editor.css`
- Below `md` (768px): sidebar stacks below canvas via `flex-direction: column`
- Sidebar width: `380px` → `w-full` on mobile, `380px` on `md+`
- Canvas gets min-height to stay usable when stacked
## 3. AnatomyCanvas — height constraint + touch
**Files**: `src/components/canvas/AnatomyCanvas.tsx`, `src/app/routes/EditorRoute.tsx`
- Mobile: `max-h-[60vh]` on canvas wrapper so observations panel stays visible
- `overflow-hidden` on wrapper
- CSS `touch-action: pan-x pan-y` for native scroll compatibility
## 4. Touch targets — minimum 40px
**Files**: `src/components/ui/Button.tsx`, `src/components/observation/VertebraPicker.tsx`, `src/components/ui/Chip.tsx`
- Button `sm` size: `h-8` → `h-9 sm:h-8` (36px mobile, 32px desktop) — compromise between touch and density
- VertebraPicker region tabs: add `min-h-[2.75rem]` (44px)
- Any interactive Chip: ensure `min-h-[2.5rem]`
## 5. Responsive typography
**Files**: all route components, `ObservationList.tsx`, `ConclusionPanel.tsx`
Pattern:
- Page headings: `text-xl sm:text-2xl md:text-3xl`
- Section headings: `text-lg sm:text-xl`
- Form legends: `text-lg sm:text-xl`
## 6. Padding normalization
**Files**: all route components
- Route containers: `px-4 sm:px-6`
- Gaps: `gap-4 sm:gap-6`
- Consistent tightening on phone
## 7. Editor layout mobile polish
**File**: `src/app/routes/EditorRoute.tsx`
- Single-column below `lg`: SVG canvas explicit height cap
- Observations section scrollable independently
- Sticky observation header on mobile for context
## 8. Footer + Header
**Files**: `src/components/brand/Footer.tsx`, `src/components/brand/AppHeader.tsx`
- Footer: `gap-2 sm:gap-4`
- Header: already responsive (tagline hidden <sm) — minimal tweaks if needed
---
## Out of scope
- No layout redesign (tab-based editor, bottom sheets, etc.)
- No feature gating per viewport
- No pinch-zoom gestures on canvas
- No SVG editor feature disabling on phone
- No PDF or schema changes
## Success criteria
- All routes usable on 375px viewport (iPhone SE)
- All interactive elements ≥ 40px touch target
- No horizontal overflow on any page
- Dialogs fit within viewport on all sizes
- SVG editor usable (stacked) on tablet
- Tests still pass (no behavior changes)