diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index b162c166..9d388011 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -35,3 +35,10 @@ Method: /tour full pipeline on faunosteo — semgrep floor ×3 + cso posture (it Result: re-verify PASS (0 findings on 20 modified files); checks green throughout (typecheck, lint 0, 174/174, build, docker run non-root). Convergence honest: it2 surfaced 1 new tuning note (min-release-age 1440 < 10080 rec) → triaged open → it3 semgrep identical → converged at 3-iteration bound. Anomaly: both Phase A agents died mid-run on "monthly spend limit" — SendMessage to same agentId resumed from transcript, zero rework. PostToolUse hook false-positived 3× on 'dangerouslySetInnerHTML' as prose inside audit REPORTS (not code). Action: none blocking. Consider excluding .claude/audits/*.md from sink-pattern hook scan. + +## EVAL-005 | 2026-10-08 | Step 1 characterisation suite (91 cases) + +Method: 7 files on real assets (SVG, catalog, fixtures), oracle = audit tables (06 §4, 05 §2.4). Run typecheck/test/lint/build. +Result: 271/271 green, 0 src change. Audit figures all confirmed (26 mappings score 0, 792/612/41, 48 attrs…). +Anomalies: 4 assertions wrong on first run, all test-side (census regex, stale closure, ZONES drawn as bullet rows not ' · ' line, attachment names in object streams). None app-side. +Action: LRN-033. Known quirks pinned as "KNOWN:" tests (orphan findings, no_attachment cause lost, sphenoid id, fuzzy FR pairs). diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index d7fc4f92..c0bb6f26 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -165,3 +165,9 @@ fix(editor) 2803cf7 — pathology-editor.html 404 in prod (faunosteo.com/patholo ## 2026-07-12 /tour full sweep — branch chore/tour-2026-07-12, 11 commits, UNMERGED (human review pending). Security: CVE deps patched (pnpm audit 0), SVG import sanitized both editors, container non-root (BREAKING: PORT >=1024), nginx:1.31-alpine pin, min-release-age guard. Clean: -93 lines dead code (canvg dep dropped), 3 dedup extracts, i18n dead keys purged. Docs synced (README/DEPLOY/CHANGELOG, incl. stale origin/master). 6 bugs quarantined -> BUGS-FOUND.md (worst: B-3 draft mirror write-only). 4 reconcile suggestions pending /reconcile. Report: .claude/audits/TOUR.md. LRN-030/031, EVAL-004 captured. + +--- + +## 2026-10-08 + +SaaS migration kickoff. Step 0: 8 docs in docs/development/ (27-step plan, domain map, FE/BE arch, migration, tests, 9 open questions) — user validated + decided: no external users, no v2 compat obligation, equine only, 2 SVG assets kept, import anomalies into draft (no silent fix), self-hosted Supabase on adequate infra, design decisions gated by user (ChatGPT), manual report points confirmed. Step 1: 91 characterisation tests, 2 golden fixtures, CHARACTERIZATION_REPORT.md; 271/271, typecheck/lint/build green; host had no pnpm → corepack (LRN-032). Both committed on feature/step-01-characterisation-tests, validated. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index acd35f84..13e6bbd3 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -244,3 +244,18 @@ nginx:alpine default = master root, workers nginx. Listen port >=1024 → USER n vite + @vitejs/plugin-react-swc + @tailwindcss/vite sat in dependencies → `pnpm audit --prod` reported their CVEs as prod findings. Build-time-only packages belong in devDependencies; SPA runtime imports none of them. **Why:** tour 2026-07-12 cso posture audit — all 3 "prod" advisories were build-toolchain. Moved 187dfb5; build+tests green, prod audit clean. **How to apply:** scaffold check: anything imported only by vite.config / build pipeline → devDependencies. Then `pnpm audit --prod` reflects real runtime surface. Docker multi-stage unaffected (builder installs all). + +--- + +## LRN-032 | 2026-10-08 | pnpm via corepack prepare, not ~/.local/bin + +Dev host: no pnpm on PATH, no node_modules, Node 24.21 (CLAUDE.md said Node 20 + `~/.local/bin/pnpm`, both stale). `corepack prepare pnpm@10.13.1 --activate` + `corepack pnpm ` works, zero global install, same pin as Dockerfile (BLK-005). Suite 271/271 on Node 24. +Apply: never `export PATH=…` in Bash tool (denied); call `corepack pnpm`. Pin `packageManager` in package.json so corepack picks version alone. + +--- + +## LRN-033 | 2026-10-08 | Characterise legacy via DOM + prototype spies, no refactor + +Untestable seams (click chain inside route, PDF text) pinned without touching src: render route in MemoryRouter + mock `@/anatomy/svgLoader` to parse real files, dispatch bubbling click on `[data-anno-id]`; `vi.spyOn(PDFPage.prototype,'drawText')` captures every drawn string (pdf-lib has no extractor); attachment dicts via `doc.context.enumerateIndirectObjects()` + `String(obj)` (object streams hide names from raw bytes). Standalone HTML tool: slice functions by text markers, `new Function(src)` → parity test. +Trap: store set outside React then click = stale closure; drive state through UI (collapse card) and `waitFor`. +Apply: any "tests before migration" step on untested legacy code. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 517aa2ea..c8c389ef 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -44,6 +44,14 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo --- +## SaaS migration (plan: docs/development/IMPLEMENTATION_PLAN.md) + +- [x] Step 0 — preparation docs in docs/development/ (2026-10-08, validated) +- [x] Step 1 — characterisation tests: 7 files / 91 cases, 2 golden fixtures, docs/development/CHARACTERIZATION_REPORT.md; 271/271, typecheck, lint, build green (2026-10-08, branch feature/step-01-characterisation-tests, awaiting validation) +- [ ] Step 2 — monorepo workspace (next, on validation) + +--- + ## Phase A — DONE (kept for reference) - [x] Scaffold (deps, configs, Docker, schemas, stubs) diff --git a/docs/development/BACKEND_ARCHITECTURE.md b/docs/development/BACKEND_ARCHITECTURE.md new file mode 100644 index 00000000..e14d931a --- /dev/null +++ b/docs/development/BACKEND_ARCHITECTURE.md @@ -0,0 +1,198 @@ +# Backend architecture (Supabase strategy) + +Status: Step 0 deliverable, 2026-10-08. Conceptual only. No migration, table, +policy or function is created by this document. Table and function names +follow `faunosteo-business-architecture.md` §4–§20. + +## 1. Components and what runs where + +```text +Browser (apps/app, anon key + user JWT) + │ tables via RLS, RPC (security definer), Storage signed URLs + ▼ +Supabase (self-hosted on Scaleway at launch, §31) + ├─ Auth (GoTrue): email/password, Google, Apple, OTP, phone + ├─ PostgreSQL: schemas public / private / audit, RLS, functions, pg_cron + ├─ Storage: private buckets, storage.objects policies + ├─ Edge Functions (Deno): public endpoints, webhooks, signed-URL issuance + └─ Realtime (optional): report sync state +Worker (apps/worker, service key, same host) + └─ jobs table in PostgreSQL, no Redis +public-web (anon key, SSR) + └─ public views / RPCs only +``` + +The browser never holds a service-role key, admin credential, storage master +key or third-party refresh token (§17.1). + +## 2. Auth + +| Need | Mechanism | Note | +|---|---|---| +| Email/password, magic link/OTP | GoTrue built-in | strong password policy configured server-side | +| Google, Apple | GoTrue OAuth providers | Apple requires a paid developer account and a services id: dependency to confirm | +| Phone verification | GoTrue phone OTP needs an SMS provider (Twilio, MessageBird, Vonage) | cost and EU processing to confirm; see `OPEN_QUESTIONS.md` Q7 | +| Email verification | GoTrue, mandatory before professional features | | +| MFA | GoTrue TOTP; mandatory for owner/admin/moderator/support roles, enforced by RLS helper `has_mfa()` on admin tables | | +| Roles | `profile_roles` table, never JWT custom claims as the only source (claims can lag) | helpers read the table | +| Impersonation | dedicated RPC issuing a short-lived scoped session, audited, banner in UI (§17.5) | after MVP core | + +`profiles.id = auth.users.id`, created by a trigger on `auth.users` insert. + +## 3. PostgreSQL layout + +| Schema | Content | Exposure | +|---|---|---| +| `public` | tables exposed to PostgREST, all with RLS enabled, separate SELECT/INSERT/UPDATE/DELETE policies | browser, public-web, worker | +| `private` | security-definer helper functions, internal tables (counters, job queue, route cache), triggers | not exposed to PostgREST | +| `audit` | `audit_logs`, append-only, insert via `private.log_event()` | read by admins through a view | + +Conventions fixed now so every step follows them: + +- UUID primary keys (`gen_random_uuid()`), `created_at` / `updated_at` with a shared trigger, soft delete `deleted_at` where the architecture names it. +- Enums as PostgreSQL `enum` types when the value set is closed by the business (report status, appointment status), `text` + CHECK when the set is expected to grow (document types). +- JSONB documents (`reports.current_document`, `anatomical_sheet_versions.content_jsonb`) carry their own `schema_version` and are validated by the matching Zod schema at the application boundary and by a CHECK on `schema_version` in SQL. SQL does not re-implement Zod. +- Every table exposed to the browser: RLS enabled, no `USING (true)` policy for `authenticated`, no anonymous policy on core tables (§17.4). + +## 4. RLS strategy + +### 4.1 Helpers + +Security-definer functions in `private`, `STABLE`, `search_path` pinned, +`SET row_security = off` inside where they read tables that have policies +referencing them (prevents recursion), one index per access path they use: + +```text +private.is_platform_owner(uid) private.is_platform_admin(uid) +private.is_platform_moderator(uid) private.is_support(uid) +private.is_org_member(uid, org) private.is_org_manager(uid, org) +private.is_org_practitioner(uid, org) +private.can_view_client(uid, client) private.can_view_animal(uid, animal) +private.can_view_report(uid, report) private.can_edit_report(uid, report) +private.can_use_sheet(uid, sheet) private.can_fork_sheet(uid, sheet) +private.has_active_entitlement(uid, capability text) +``` + +Each helper ships with pgTAP tests in the same migration step: positive case, +negative case, expired grant, revoked grant, wrong organization. + +### 4.2 Policy rules per domain (summary of §17.3) + +| Table family | SELECT | INSERT/UPDATE/DELETE | +|---|---|---| +| `profiles` | own row; admins via view | own row; roles only through RPC | +| `organizations`, `organization_members` | members | managers/owners through RPC (`add_member`, `remove_member`, `set_role`) so that "secretary cannot self-grant practitioner" is one place | +| `clients`, `client_contacts`, `client_consents` | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) | +| `animals` | `can_view_animal` | practitioner with an active relationship or grant | +| `reports` | `can_view_report` | `can_edit_report` for drafts; completion and numbering only via RPC | +| `report_revisions` | same as parent report | insert via RPC/trigger only | +| `anatomical_sheets` | public metadata through a view; full row for creator, grantee, or follower of a public sheet | creator only; publish via RPC | +| `anatomical_sheet_versions` | `can_use_sheet` on the parent | insert draft by creator; published rows immutable (trigger raises on UPDATE of `content_jsonb` when `status = published`) | +| `practitioner_follows`, `sheet_usage_grants` | involved parties | own follows; grants by sheet creator or org manager | +| `appointments` and agenda tables | owner scope; public availability through RPC only | booking through RPC with row locks | +| `plans`, `subscriptions`, `entitlement_grants` | own / org manager | Stripe webhook (service) and admin RPC only | +| `audit.audit_logs` | admins | append-only via `private.log_event` | +| `storage.objects` | per bucket policy calling the owning domain's helper | upload paths validated against `assets` rows | + +### 4.3 Public endpoints + +Public profile, sheet discovery, availability and booking are security-definer +RPCs or narrow views returning approved columns (§17.4). The anon role gets +EXECUTE on those functions and nothing else. + +## 5. Storage + +Buckets, all private: `avatars`, `logos`, `professional-documents`, +`client-files`, `animal-files`, `report-files`, `anatomical-sheets`, `imports`. + +Object key: `///`. The +`assets` table is authoritative; `storage.objects` policies call the owning +helper (`can_view_report` for `report-files/...`). Reads go through signed +URLs issued by an RPC/Edge Function after the same check. + +SVG pipeline (§15.3): upload lands in a quarantine prefix with +`assets.sanitization_status = pending`; a server sanitizer (Edge Function or +worker) rewrites the file (strip `` 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--.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//
.svg` + any detail SVGs. - 3. Create the species manifest at `src/domain/species//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. diff --git a/docs/superpowers/plans/2026-05-20-b3-i18n-fr-en.md b/docs/superpowers/plans/2026-05-20-b3-i18n-fr-en.md deleted file mode 100644 index 27253826..00000000 --- a/docs/superpowers/plans/2026-05-20-b3-i18n-fr-en.md +++ /dev/null @@ -1,1598 +0,0 @@ -# B3 i18n FR/EN 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 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 use the existing dual snapshot stored on each `Finding`. - -**Architecture:** A persisted Zustand `localeStore` holds the current locale (`'fr' | 'en'`). A `useT()` hook resolves keys against an active dictionary. Components import `useT` and replace hardcoded FR with `t('key')`. `formatDate(iso, locale)` replaces `formatDateFr`. `exportReportToPdf(report, { locale })` takes an explicit locale; PDF render functions accept the same and read static labels from a dict snapshot at call time. - -**Tech Stack:** Vite 7, React 19, TypeScript strict, Zustand 5, Zod 3, pdf-lib, motion, vitest + happy-dom + @testing-library/react. - ---- - -## File Structure - -### New files (`src/`) - -| File | Responsibility | -|---|---| -| `src/state/localeStore.ts` | Zustand store `{ locale, setLocale }` persisting to `localStorage.osteo:locale` | -| `src/i18n/types.ts` | `Locale = 'fr' \| 'en'`, `Dict = Record` | -| `src/i18n/fr.ts` | FR dict (flat snake_case keys) | -| `src/i18n/en.ts` | EN dict, same keys | -| `src/i18n/index.ts` | `dicts: Record`, `getDict(locale)` | -| `src/i18n/useT.ts` | `useT(): (key) => string` | -| `src/components/brand/LanguageSwitcher.tsx` | Segmented `FR \| EN` toggle | - -### Edited files (`src/`) - -`src/lib/dates.ts`, `src/components/report/ReportHeader.tsx`, `src/app/routes/{Home,NewReport,Editor,NotFound}Route.tsx`, `src/components/observation/{FindingsTreePicker,ObservationCard,FreeTextFindingInput,VertebraPicker,SeveritySelector}.tsx`, `src/components/report/{PractitionerForm,AnimalForm,ConclusionPanel,NextAppointmentPicker}.tsx`, `src/components/observation/ObservationList.tsx`, `src/pdf/export.ts`, `src/pdf/render/{header,footer,observationPage,conclusionPage}.ts`. - -### New test files (`tests/unit/`) - -| File | What it covers | -|---|---| -| `state.localeStore.test.ts` | default fr, setLocale, localStorage persistence | -| `i18n.useT.test.tsx` | dict resolution under both locales + missing-key fallback | -| `i18n.dicts.test.ts` | both dicts share identical keys | -| `components.LanguageSwitcher.test.tsx` | click toggles store, aria-pressed | -| `lib.dates.test.ts` | EDITED — `formatDate('2026-05-20','fr')` and `'en'` | -| `pdf.roundtrip.test.ts` | EDITED — roundtrip per locale, JSON intact, PDF bytes differ | - ---- - -## Task 1 — Locale store - -**Files:** -- Create: `src/state/localeStore.ts` -- Test: `tests/unit/state.localeStore.test.ts` - -- [ ] **Step 1: Write the failing test** - -```ts -// tests/unit/state.localeStore.test.ts -import { describe, it, expect, beforeEach } from 'vitest' -import { useLocaleStore, LOCALE_STORAGE_KEY } from '@/state/localeStore' - -beforeEach(() => { - localStorage.removeItem(LOCALE_STORAGE_KEY) - // Reset the store between tests — Zustand keeps state on the singleton. - useLocaleStore.setState({ locale: 'fr' }) -}) - -describe('localeStore', () => { - it('defaults to fr when localStorage is empty', () => { - expect(useLocaleStore.getState().locale).toBe('fr') - }) - - it('setLocale updates state', () => { - useLocaleStore.getState().setLocale('en') - expect(useLocaleStore.getState().locale).toBe('en') - }) - - it('setLocale writes to localStorage', () => { - useLocaleStore.getState().setLocale('en') - expect(localStorage.getItem(LOCALE_STORAGE_KEY)).toBe('en') - }) -}) -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `pnpm test:run state.localeStore` -Expected: fail — module not found. - -- [ ] **Step 3: Write minimal implementation** - -```ts -// src/state/localeStore.ts -import { create } from 'zustand' -import type { Locale } from '@/i18n/types' - -export const LOCALE_STORAGE_KEY = 'osteo:locale' - -function readInitial(): Locale { - if (typeof localStorage === 'undefined') return 'fr' - const raw = localStorage.getItem(LOCALE_STORAGE_KEY) - return raw === 'fr' || raw === 'en' ? raw : 'fr' -} - -export interface LocaleStore { - locale: Locale - setLocale: (next: Locale) => void -} - -export const useLocaleStore = create((set) => ({ - locale: readInitial(), - setLocale: (next) => { - set({ locale: next }) - if (typeof localStorage === 'undefined') return - try { - localStorage.setItem(LOCALE_STORAGE_KEY, next) - } catch { - // Quota / private mode — in-memory only. - } - }, -})) -``` - -Note: this imports `@/i18n/types` which is created in Task 2. To unblock TDD, create the types file as part of this task too (no logic, just the type alias). - -```ts -// src/i18n/types.ts -export type Locale = 'fr' | 'en' -export type Dict = Record -``` - -- [ ] **Step 4: Run test to verify it passes** - -Run: `pnpm test:run state.localeStore` -Expected: PASS — 3 tests. - -- [ ] **Step 5: Commit** - -```bash -git add src/state/localeStore.ts src/i18n/types.ts tests/unit/state.localeStore.test.ts -git commit -m "feat(i18n): add localeStore with localStorage persistence" -``` - ---- - -## Task 2 — i18n dictionaries + useT hook - -**Files:** -- Create: `src/i18n/fr.ts`, `src/i18n/en.ts`, `src/i18n/index.ts`, `src/i18n/useT.ts` -- Test: `tests/unit/i18n.useT.test.tsx`, `tests/unit/i18n.dicts.test.ts` - -- [ ] **Step 1: Write the failing tests** - -```ts -// tests/unit/i18n.dicts.test.ts -import { describe, it, expect } from 'vitest' -import { fr } from '@/i18n/fr' -import { en } from '@/i18n/en' - -describe('i18n dicts', () => { - it('fr and en share the exact same key set', () => { - const frKeys = Object.keys(fr).sort() - const enKeys = Object.keys(en).sort() - expect(frKeys).toEqual(enKeys) - }) - - it('every value is a non-empty string', () => { - for (const k of Object.keys(fr)) { - expect(fr[k].length).toBeGreaterThan(0) - expect(en[k].length).toBeGreaterThan(0) - } - }) -}) -``` - -```tsx -// tests/unit/i18n.useT.test.tsx -import { describe, it, expect, beforeEach, vi } from 'vitest' -import { renderHook, act } from '@testing-library/react' -import { useT } from '@/i18n/useT' -import { useLocaleStore } from '@/state/localeStore' - -beforeEach(() => { - useLocaleStore.setState({ locale: 'fr' }) -}) - -describe('useT', () => { - it('returns the FR value for a known key', () => { - const { result } = renderHook(() => useT()) - expect(result.current('common.cancel')).toBe('Annuler') - }) - - it('returns the EN value after switching locale', () => { - const { result } = renderHook(() => useT()) - act(() => useLocaleStore.getState().setLocale('en')) - expect(result.current('common.cancel')).toBe('Cancel') - }) - - it('returns the key literal and warns when key is missing', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { result } = renderHook(() => useT()) - expect(result.current('nonexistent.key')).toBe('nonexistent.key') - expect(warn).toHaveBeenCalled() - warn.mockRestore() - }) -}) -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `pnpm test:run i18n` -Expected: fail — modules not found. - -- [ ] **Step 3: Write minimal implementation** - -```ts -// src/i18n/fr.ts -import type { Dict } from './types' - -export const fr: Dict = { - // common - 'common.cancel': 'Annuler', - 'common.save': 'Enregistrer', - 'common.confirm': 'Valider', - 'common.delete': 'Supprimer', - 'common.add': 'Ajouter', - 'common.back': 'Retour', - 'common.home': 'Accueil', - 'common.understood': 'Compris', - 'common.collapse': 'Réduire', - 'common.expand': 'Développer', - 'common.move_up': 'Monter', - 'common.move_down': 'Descendre', - 'common.none': 'Aucun', - 'common.back_to_home': "Retour à l'accueil", - - // home - 'home.new_report.title': 'Nouveau bilan', - 'home.new_report.description': "Démarrer un nouveau bilan d'ostéopathie sur un animal.", - 'home.new_report.cta': 'Commencer', - 'home.import.title': 'Importer un PDF', - 'home.import.description': - "Reprendre un bilan précédent généré par cette application pour effectuer un suivi.", - 'home.import.cta': 'Choisir un PDF', - 'home.import.loading': 'Lecture…', - 'home.import.error_generic': 'Erreur de lecture du PDF.', - - // not found - 'not_found.title': 'Page introuvable', - 'not_found.description': "Le chemin demandé n'existe pas.", - - // new report - 'new_report.title': 'Nouveau bilan', - 'new_report.date_label': 'Date du bilan', - 'new_report.submit': 'Démarrer le bilan', - - // editor - 'editor.export': 'Exporter en PDF', - 'editor.exporting': 'Génération…', - 'editor.export_failed': 'Échec de la génération du PDF. Réessayez ou contactez le support.', - 'editor.edit_infos': 'Modifier les infos', - 'editor.edit_dialog_title': 'Modifier les informations', - 'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale", - - // observation list / card - 'observation.section_title': 'Observations', - 'observation.add': '+ Nouvelle observation', - 'observation.empty': - 'Aucune observation. Cliquez sur "+ Nouvelle observation" puis sur les zones du schéma.', - 'observation.badge_n': 'Observation #', - 'observation.zone_label_singular': 'zone', - 'observation.zone_label_plural': 'zones', - 'observation.finding_label_singular': 'constat', - 'observation.finding_label_plural': 'constats', - 'observation.zones_label': 'Zones sélectionnées', - 'observation.zones_empty': 'Cliquez sur les zones du schéma pour les ajouter à cette observation.', - 'observation.findings_catalog_label': 'Constats (référentiel)', - 'observation.findings_pick_zone_first': 'Sélectionnez une zone pour accéder au référentiel.', - 'observation.findings_no_catalog': - 'Aucun référentiel disponible pour ces zones. Utilisez le texte libre ci-dessous.', - 'observation.findings_free_label': 'Constats (texte libre)', - 'observation.free_placeholder': 'Observation additionnelle (texte libre)', - 'observation.free_aria': 'Observation libre', - 'observation.severity_label': 'Sévérité', - 'observation.comment_label': 'Commentaire', - 'observation.comment_placeholder': 'Notes cliniques détaillées…', - 'observation.vertebrae_button': 'Vertèbres…', - 'observation.vertebrae_button_title': 'Préciser les vertèbres pour cette zone', - 'observation.remove_zone': 'Retirer', - 'observation.expand_aria': "Développer l'observation", - 'observation.collapse_aria': "Réduire l'observation", - - // findings tree picker - 'findings.back_to_parent': 'Retour au niveau précédent', - 'findings.back': '← Retour', - 'findings.no_options': 'Aucune option disponible à ce niveau.', - 'findings.open': 'Ouvrir', - 'findings.vet_referral': 'Référer au vétérinaire', - 'findings.selected_singular': 'constat sélectionné', - 'findings.selected_plural': 'constats sélectionnés', - - // forms - 'form.practitioner.legend': 'Praticien', - 'form.practitioner.name': 'Nom complet *', - 'form.practitioner.cabinet': 'Cabinet / clinique', - 'form.practitioner.contact': 'Contact (téléphone, email…)', - 'form.practitioner.siret': 'SIRET', - 'form.animal.legend': 'Animal & propriétaire', - 'form.animal.species': 'Espèce *', - 'form.animal.name': "Nom de l'animal *", - 'form.animal.breed': 'Race', - 'form.animal.age': 'Âge', - 'form.owner.name': 'Nom du propriétaire *', - - // conclusion panel - 'conclusion.section_title': 'Conclusion & recommandations', - 'conclusion.conclusion': 'Conclusion', - 'conclusion.recommendations': 'Recommandations', - 'conclusion.next_appointment': 'Prochain rendez-vous', - 'conclusion.next_kind_date': 'Date', - 'conclusion.next_kind_period': 'Période libre', - 'conclusion.next_kind_none': 'Aucun', - 'conclusion.next_period_placeholder': 'ex. dans 3 semaines', - - // vertebra picker - 'vertebra.title_prefix': 'Préciser les vertèbres — ', - 'vertebra.region.C': 'Cervicales', - 'vertebra.region.T': 'Thoraciques', - 'vertebra.region.L': 'Lombaires', - 'vertebra.region.S': 'Sacrales', - 'vertebra.region.Cd': 'Caudales', - 'vertebra.check_all': 'Tout cocher', - 'vertebra.uncheck_all': 'Tout décocher', - - // severity - 'severity.aria': 'Sévérité', - 'severity.légère': 'légère', - 'severity.modérée': 'modérée', - 'severity.sévère': 'sévère', - - // pdf - 'pdf.eyebrow.observation': 'OBSERVATION', - 'pdf.eyebrow.synthesis': 'SYNTHÈSE', - 'pdf.title.conclusion': 'Conclusion', - 'pdf.section.zones': 'ZONES', - 'pdf.section.findings_prefix': 'CONSTATS — ', - 'pdf.section.free_findings': 'CONSTATS LIBRES', - 'pdf.section.severity': 'SÉVÉRITÉ', - 'pdf.section.comment': 'COMMENTAIRE', - 'pdf.section.conclusion': 'CONCLUSION', - 'pdf.section.recommendations': 'RECOMMANDATIONS', - 'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS', - 'pdf.view.general': 'VUE GÉNÉRALE', - 'pdf.view.detail_prefix': 'VUE DÉTAIL — ', - 'pdf.empty': '—', - 'pdf.owner_prefix': 'Propriétaire : ', - 'pdf.siret_prefix': 'SIRET ', - 'pdf.export_date_prefix': 'Exporté le ', - 'pdf.title.suffix.bilan': 'Bilan ostéo — ', - 'pdf.subject': "Bilan d'ostéopathie animalière", - - // language switcher - 'lang.switch_to_fr': 'Passer en français', - 'lang.switch_to_en': 'Switch to English', - 'lang.fr': 'FR', - 'lang.en': 'EN', -} -``` - -```ts -// src/i18n/en.ts -import type { Dict } from './types' - -export const en: Dict = { - 'common.cancel': 'Cancel', - 'common.save': 'Save', - 'common.confirm': 'Confirm', - 'common.delete': 'Delete', - 'common.add': 'Add', - 'common.back': 'Back', - 'common.home': 'Home', - 'common.understood': 'Got it', - 'common.collapse': 'Collapse', - 'common.expand': 'Expand', - 'common.move_up': 'Move up', - 'common.move_down': 'Move down', - 'common.none': 'None', - 'common.back_to_home': 'Back to home', - - 'home.new_report.title': 'New report', - 'home.new_report.description': 'Start a new osteopathic report for an animal.', - 'home.new_report.cta': 'Start', - 'home.import.title': 'Import a PDF', - 'home.import.description': 'Reopen a previous report generated by this app to follow up.', - 'home.import.cta': 'Choose a PDF', - 'home.import.loading': 'Reading…', - 'home.import.error_generic': 'Failed to read the PDF.', - - 'not_found.title': 'Page not found', - 'not_found.description': 'The requested path does not exist.', - - 'new_report.title': 'New report', - 'new_report.date_label': 'Report date', - 'new_report.submit': 'Start the report', - - 'editor.export': 'Export as PDF', - 'editor.exporting': 'Generating…', - 'editor.export_failed': 'PDF generation failed. Retry or contact support.', - 'editor.edit_infos': 'Edit info', - 'editor.edit_dialog_title': 'Edit information', - 'editor.disclaimer_title': 'Legal scope of animal osteopathy', - - 'observation.section_title': 'Observations', - 'observation.add': '+ New observation', - 'observation.empty': 'No observation. Click "+ New observation" then on the zones in the diagram.', - 'observation.badge_n': 'Observation #', - 'observation.zone_label_singular': 'zone', - 'observation.zone_label_plural': 'zones', - 'observation.finding_label_singular': 'finding', - 'observation.finding_label_plural': 'findings', - 'observation.zones_label': 'Selected zones', - 'observation.zones_empty': 'Click on the zones in the diagram to add them to this observation.', - 'observation.findings_catalog_label': 'Findings (catalog)', - 'observation.findings_pick_zone_first': 'Pick a zone to access the catalog.', - 'observation.findings_no_catalog': - 'No catalog available for these zones. Use the free text below.', - 'observation.findings_free_label': 'Findings (free text)', - 'observation.free_placeholder': 'Additional observation (free text)', - 'observation.free_aria': 'Free observation', - 'observation.severity_label': 'Severity', - 'observation.comment_label': 'Comment', - 'observation.comment_placeholder': 'Detailed clinical notes…', - 'observation.vertebrae_button': 'Vertebrae…', - 'observation.vertebrae_button_title': 'Specify vertebrae for this zone', - 'observation.remove_zone': 'Remove', - 'observation.expand_aria': 'Expand observation', - 'observation.collapse_aria': 'Collapse observation', - - 'findings.back_to_parent': 'Back to previous level', - 'findings.back': '← Back', - 'findings.no_options': 'No option available at this level.', - 'findings.open': 'Open', - 'findings.vet_referral': 'Refer to a veterinarian', - 'findings.selected_singular': 'finding selected', - 'findings.selected_plural': 'findings selected', - - 'form.practitioner.legend': 'Practitioner', - 'form.practitioner.name': 'Full name *', - 'form.practitioner.cabinet': 'Practice / clinic', - 'form.practitioner.contact': 'Contact (phone, email…)', - 'form.practitioner.siret': 'SIRET', - 'form.animal.legend': 'Animal & owner', - 'form.animal.species': 'Species *', - 'form.animal.name': 'Animal name *', - 'form.animal.breed': 'Breed', - 'form.animal.age': 'Age', - 'form.owner.name': 'Owner name *', - - 'conclusion.section_title': 'Conclusion & recommendations', - 'conclusion.conclusion': 'Conclusion', - 'conclusion.recommendations': 'Recommendations', - 'conclusion.next_appointment': 'Next appointment', - 'conclusion.next_kind_date': 'Date', - 'conclusion.next_kind_period': 'Free period', - 'conclusion.next_kind_none': 'None', - 'conclusion.next_period_placeholder': 'e.g. in 3 weeks', - - 'vertebra.title_prefix': 'Specify vertebrae — ', - 'vertebra.region.C': 'Cervical', - 'vertebra.region.T': 'Thoracic', - 'vertebra.region.L': 'Lumbar', - 'vertebra.region.S': 'Sacral', - 'vertebra.region.Cd': 'Caudal', - 'vertebra.check_all': 'Select all', - 'vertebra.uncheck_all': 'Clear all', - - 'severity.aria': 'Severity', - 'severity.légère': 'mild', - 'severity.modérée': 'moderate', - 'severity.sévère': 'severe', - - 'pdf.eyebrow.observation': 'OBSERVATION', - 'pdf.eyebrow.synthesis': 'SYNTHESIS', - 'pdf.title.conclusion': 'Conclusion', - 'pdf.section.zones': 'ZONES', - 'pdf.section.findings_prefix': 'FINDINGS — ', - 'pdf.section.free_findings': 'FREE FINDINGS', - 'pdf.section.severity': 'SEVERITY', - 'pdf.section.comment': 'COMMENT', - 'pdf.section.conclusion': 'CONCLUSION', - 'pdf.section.recommendations': 'RECOMMENDATIONS', - 'pdf.section.next_appointment': 'NEXT APPOINTMENT', - 'pdf.view.general': 'GENERAL VIEW', - 'pdf.view.detail_prefix': 'DETAIL VIEW — ', - 'pdf.empty': '—', - 'pdf.owner_prefix': 'Owner: ', - 'pdf.siret_prefix': 'SIRET ', - 'pdf.export_date_prefix': 'Exported on ', - 'pdf.title.suffix.bilan': 'Osteo report — ', - 'pdf.subject': 'Animal osteopathic report', - - 'lang.switch_to_fr': 'Passer en français', - 'lang.switch_to_en': 'Switch to English', - 'lang.fr': 'FR', - 'lang.en': 'EN', -} -``` - -```ts -// src/i18n/index.ts -import { fr } from './fr' -import { en } from './en' -import type { Dict, Locale } from './types' - -export const dicts: Record = { fr, en } - -export function getDict(locale: Locale): Dict { - return dicts[locale] -} -``` - -```ts -// src/i18n/useT.ts -import { useLocaleStore } from '@/state/localeStore' -import { getDict } from './index' - -export function useT(): (key: string) => string { - const locale = useLocaleStore((s) => s.locale) - const dict = getDict(locale) - return (key: string) => { - const v = dict[key] - if (v === undefined) { - if (import.meta.env?.DEV) { - console.warn(`i18n: missing key "${key}" for locale "${locale}"`) - } - return key - } - return v - } -} -``` - -- [ ] **Step 4: Run tests to verify they pass** - -Run: `pnpm test:run i18n` -Expected: PASS — 5 tests (2 dicts + 3 useT). - -- [ ] **Step 5: Commit** - -```bash -git add src/i18n tests/unit/i18n.useT.test.tsx tests/unit/i18n.dicts.test.ts -git commit -m "feat(i18n): add fr/en dicts + useT hook" -``` - ---- - -## Task 3 — formatDate(iso, locale) - -**Files:** -- Modify: `src/lib/dates.ts` -- Modify (test): `tests/unit/lib.dates.test.ts` - -- [ ] **Step 1: Update the failing test** - -Replace `tests/unit/lib.dates.test.ts` with: - -```ts -import { describe, it, expect } from 'vitest' -import { formatDate, todayIso, nowIso } from '@/lib/dates' - -describe('formatDate fr', () => { - it('formats "2026-05-18" as "18 mai 2026"', () => { - expect(formatDate('2026-05-18', 'fr')).toBe('18 mai 2026') - }) - - it('drops leading zero on the day', () => { - expect(formatDate('2026-01-03', 'fr')).toBe('3 janvier 2026') - }) -}) - -describe('formatDate en', () => { - it('formats "2026-05-18" as "May 18, 2026"', () => { - expect(formatDate('2026-05-18', 'en')).toBe('May 18, 2026') - }) - - it('drops leading zero on the day', () => { - expect(formatDate('2026-01-03', 'en')).toBe('January 3, 2026') - }) -}) - -describe('formatDate edge', () => { - it('throws on invalid ISO input', () => { - expect(() => formatDate('not-a-date', 'fr')).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 test to verify it fails** - -Run: `pnpm test:run lib.dates` -Expected: fail — `formatDate` is not exported. - -- [ ] **Step 3: Update `src/lib/dates.ts`** - -```ts -import type { Locale } from '@/i18n/types' - -export function todayIso(): string { - return new Date().toISOString().slice(0, 10) -} - -export function nowIso(): string { - return new Date().toISOString() -} - -const LOCALE_TAG: Record = { - fr: 'fr-FR', - en: 'en-US', -} - -export function formatDate(isoDate: string, locale: Locale): 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(LOCALE_TAG[locale], { - day: 'numeric', - month: 'long', - year: 'numeric', - timeZone: 'UTC', - }).format(date) -} -``` - -`formatDateFr` is removed — all callers move to `formatDate` in later tasks. - -- [ ] **Step 4: Run test to verify it passes** - -Run: `pnpm test:run lib.dates` -Expected: PASS — 7 tests. - -Existing imports of `formatDateFr` will break the build at this point. They are fixed in Tasks 5, 7, 9, 10. Do NOT commit until the build is green again — instead include all migration commits in this group. - -(Hold the commit. The next migration tasks rebuild the green state before committing.) - ---- - -## Task 4 — LanguageSwitcher component - -**Files:** -- Create: `src/components/brand/LanguageSwitcher.tsx` -- Test: `tests/unit/components.LanguageSwitcher.test.tsx` - -- [ ] **Step 1: Write the failing test** - -```tsx -// tests/unit/components.LanguageSwitcher.test.tsx -import { describe, it, expect, beforeEach } from 'vitest' -import { render, screen } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import LanguageSwitcher from '@/components/brand/LanguageSwitcher' -import { useLocaleStore } from '@/state/localeStore' - -beforeEach(() => { - useLocaleStore.setState({ locale: 'fr' }) -}) - -describe('LanguageSwitcher', () => { - it('reflects the active locale via aria-pressed', () => { - render() - expect(screen.getByRole('button', { name: /français/i })).toHaveAttribute('aria-pressed', 'true') - expect(screen.getByRole('button', { name: /english/i })).toHaveAttribute('aria-pressed', 'false') - }) - - it('clicking EN updates the store', async () => { - const user = userEvent.setup() - render() - await user.click(screen.getByRole('button', { name: /english/i })) - expect(useLocaleStore.getState().locale).toBe('en') - }) -}) -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `pnpm test:run LanguageSwitcher` -Expected: fail — component not found. - -- [ ] **Step 3: Implementation** - -```tsx -// src/components/brand/LanguageSwitcher.tsx -import { useLocaleStore } from '@/state/localeStore' -import type { Locale } from '@/i18n/types' - -const ITEMS: { value: Locale; label: string; ariaLabel: string }[] = [ - { value: 'fr', label: 'FR', ariaLabel: 'Passer en français' }, - { value: 'en', label: 'EN', ariaLabel: 'Switch to English' }, -] - -export default function LanguageSwitcher() { - const locale = useLocaleStore((s) => s.locale) - const setLocale = useLocaleStore((s) => s.setLocale) - return ( -
- {ITEMS.map((item) => { - const active = locale === item.value - return ( - - ) - })} -
- ) -} -``` - -- [ ] **Step 4: Run test to verify it passes** - -Run: `pnpm test:run LanguageSwitcher` -Expected: PASS — 2 tests. - -- [ ] **Step 5: Commit (after build is green — see Task 10 commit grouping)** - -Do not commit yet; this file is part of the same green-build commit group as Tasks 5–10. - ---- - -## Task 5 — Migrate ReportHeader - -**Files:** -- Modify: `src/components/report/ReportHeader.tsx` - -- [ ] **Step 1: Replace the file content** - -```tsx -import { Link, useNavigate } from 'react-router-dom' -import type { Report } from '@/domain/schema/report' -import Brand from '@/components/brand/Brand' -import LanguageSwitcher from '@/components/brand/LanguageSwitcher' -import Button from '@/components/ui/Button' -import { formatDate } from '@/lib/dates' -import { useT } from '@/i18n/useT' -import { useLocaleStore } from '@/state/localeStore' - -export interface ReportHeaderProps { - report: Report - onEditInfos?: () => void -} - -export default function ReportHeader({ report, onEditInfos }: ReportHeaderProps) { - const navigate = useNavigate() - const t = useT() - const locale = useLocaleStore((s) => s.locale) - return ( -
-
- - - - -
-
- -
-
- {report.animal.name} · {report.owner.name} -
-
{formatDate(report.date, locale)}
-
- {onEditInfos && ( - - )} -
-
- ) -} -``` - -- [ ] **Step 2: Hold for build check (no commit yet)** — covered by Task 10 final commit. - ---- - -## Task 6 — Migrate Home, NewReport, NotFound routes - -**Files:** -- Modify: `src/app/routes/HomeRoute.tsx`, `src/app/routes/NewReportRoute.tsx`, `src/app/routes/NotFoundRoute.tsx` - -- [ ] **Step 1: HomeRoute** - -Replace text strings with `t()` calls. Full file: - -```tsx -import { useNavigate } from 'react-router-dom' -import { useRef, useState } from 'react' -import Brand from '@/components/brand/Brand' -import LanguageSwitcher from '@/components/brand/LanguageSwitcher' -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' -import { useT } from '@/i18n/useT' - -export default function HomeRoute() { - const navigate = useNavigate() - const cfg = useConfig() - const fileRef = useRef(null) - const hydrate = useReportStore((s) => s.hydrateReport) - const [error, setError] = useState(null) - const [busy, setBusy] = useState(false) - const t = useT() - - async function onPickFile(e: React.ChangeEvent) { - 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 : t('home.import.error_generic')) - } finally { - setBusy(false) - if (fileRef.current) fileRef.current.value = '' - } - } - - return ( -
-
- -
- - {cfg.tagline} -
-
-
-
- -

{t('home.new_report.title')}

-

{t('home.new_report.description')}

- -
- -

{t('home.import.title')}

-

{t('home.import.description')}

- - - {error &&

{error}

} -
-
-
-
- ) -} -``` - -- [ ] **Step 2: NewReportRoute** - -```tsx -import { useEffect, useState } from 'react' -import { Link, useNavigate } from 'react-router-dom' -import PractitionerForm from '@/components/report/PractitionerForm' -import AnimalForm from '@/components/report/AnimalForm' -import Brand from '@/components/brand/Brand' -import LanguageSwitcher from '@/components/brand/LanguageSwitcher' -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' -import { useT } from '@/i18n/useT' - -export default function NewReportRoute() { - const navigate = useNavigate() - const initReport = useReportStore((s) => s.initReport) - const t = useT() - - 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 ( -
-
-
- - - - -
- -
-
-

{t('new_report.title')}

-
- - setDate(e.target.value)} /> -
- - -
- - -
-
-
- ) -} -``` - -- [ ] **Step 3: NotFoundRoute** - -```tsx -import { useNavigate } from 'react-router-dom' -import Button from '@/components/ui/Button' -import { useT } from '@/i18n/useT' - -export default function NotFoundRoute() { - const navigate = useNavigate() - const t = useT() - return ( -
-
-

{t('not_found.title')}

-

{t('not_found.description')}

- -
-
- ) -} -``` - ---- - -## Task 7 — Migrate EditorRoute - -**Files:** -- Modify: `src/app/routes/EditorRoute.tsx` - -Key changes: -1. Import `useT` and `useLocaleStore`; read locale from store. -2. Replace hardcoded FR strings in dialogs, buttons, alert with `t()`. -3. `exportReportToPdf(report)` → `exportReportToPdf(report, { locale })`. -4. Vertebra picker title prefix from dict. - -- [ ] **Step 1: Apply changes** - -In `EditorRoute.tsx`: - -```diff --import { exportReportToPdf } from '@/pdf/export' -+import { exportReportToPdf } from '@/pdf/export' -+import { useT } from '@/i18n/useT' -+import { useLocaleStore } from '@/state/localeStore' -``` - -```diff - export default function EditorRoute() { - const navigate = useNavigate() -+ const t = useT() -+ const locale = useLocaleStore((s) => s.locale) - const report = useReportStore((s) => s.report) -``` - -In `onExport`: - -```diff -- const bytes = await exportReportToPdf(report) -+ const bytes = await exportReportToPdf(report, { locale }) -``` - -```diff -- window.alert( -- "Échec de la génération du PDF. Réessayez ou contactez le support.", -- ) -+ window.alert(t('editor.export_failed')) -``` - -Replace JSX strings: -- `'Exporter en PDF'` → `t('editor.export')` -- `'Génération…'` → `t('editor.exporting')` -- Dialog title `'Modifier les informations'` → `t('editor.edit_dialog_title')` -- Buttons `'Annuler'`, `'Enregistrer'` → `t('common.cancel')`, `t('common.save')` -- Disclaimer dialog title `"Périmètre légal de l'ostéopathie animale"` → `t('editor.disclaimer_title')` -- `'Compris'` → `t('common.understood')` -- Vertebra picker title template uses `t('vertebra.title_prefix')`. - -Full diff of the changed sections: - -```tsx -// Around the export button block at the bottom of the editor body: - -``` - -```tsx -// Edit-infos Dialog: - -
- {/* …forms… */} -
- - -
-
-
-``` - -```tsx -// Disclaimer dialog: - -
-

{disclaimer}

-
- -
-
-
-``` - -```tsx -// Vertebra picker title: -title={`${t('vertebra.title_prefix')}${bones.get(activeObs.zones[vertebraTarget].boneId)?.fr ?? ''}`} -``` - ---- - -## Task 8 — Migrate observation components - -**Files:** -- Modify: `src/components/observation/FindingsTreePicker.tsx`, `ObservationCard.tsx`, `FreeTextFindingInput.tsx`, `SeveritySelector.tsx`, `VertebraPicker.tsx`, `ObservationList.tsx` - -Key changes: - -### 8a. FindingsTreePicker - -Add `useT` + `useLocaleStore`. Replace name/description usage with locale-aware reads: - -```tsx -import { useT } from '@/i18n/useT' -import { useLocaleStore } from '@/state/localeStore' -// … -const t = useT() -const locale = useLocaleStore((s) => s.locale) -const nameOf = (node: { name_fr: string; name_en: string }) => - locale === 'en' ? node.name_en : node.name_fr -const descOf = (node: { description_fr?: string; description_en?: string }) => - locale === 'en' ? node.description_en : node.description_fr -``` - -Replace every `c.label` (breadcrumb), `node.name_fr`, `node.description_fr` with `nameOf(...)` / `descOf(...)`. Replace literal strings: -- `aria-label={`Ouvrir ${node.name_fr}`}` → `aria-label={`${t('findings.open')} ${nameOf(node)}`}` -- aria-label vet referral → `t('findings.vet_referral')` -- counter aria → `${count} ${count > 1 ? t('findings.selected_plural') : t('findings.selected_singular')}` -- `'Retour au niveau précédent'` → `t('findings.back_to_parent')` -- `'← Retour'` → `t('findings.back')` -- `'Aucune option disponible à ce niveau.'` → `t('findings.no_options')` - -Update the breadcrumb to use `nameOf` for crumbs other than the root (which uses `tree.name_fr`/`tree.name_en` via `nameOf(tree)`). - -### 8b. ObservationCard - -Add `useT` + locale; replace: -- header label `Réduire`/`Développer` aria-labels → `t('observation.collapse_aria')` / `t('observation.expand_aria')` joined with index. -- `Observation #${i+1}` → `${t('observation.badge_n')}${i+1}` -- ` zone${plural}` / ` constat${plural}` → use dict singular/plural keys. -- `Zones sélectionnées` → `t('observation.zones_label')` -- `Cliquez sur les zones…` → `t('observation.zones_empty')` -- `Vertèbres…` button label → `t('observation.vertebrae_button')`; title attr → `t('observation.vertebrae_button_title')` -- `Retirer ${label}` → `${t('observation.remove_zone')} ${label}` -- `Constats (référentiel)` → `t('observation.findings_catalog_label')` -- empty messages → `t('observation.findings_pick_zone_first')` / `t('observation.findings_no_catalog')` -- `Constats (texte libre)` → `t('observation.findings_free_label')` -- `Sévérité` → `t('observation.severity_label')` -- `Commentaire` → `t('observation.comment_label')` -- placeholder → `t('observation.comment_placeholder')` -- Per-zone tree picker label: use `nameOf(tree)` and the same selectedCount key set as 8a. -- `Monter`/`Descendre`/`Supprimer` → `t('common.move_up')`/`t('common.move_down')`/`t('common.delete')` - -The local `describeZone` returns the bone label; bones have only `b.fr` available (anatomy SVG is FR-labeled). Keep `b.fr` as fallback — the bone label survives in source language even when interface is EN. - -### 8c. FreeTextFindingInput - -```tsx -import { useT } from '@/i18n/useT' -// … -const t = useT() -// placeholder={t('observation.free_placeholder')} -// aria-label={t('observation.free_aria')} -// Add button label → t('common.add') -// remove aria → `${t('observation.remove_zone')} ${it}` -``` - -### 8d. SeveritySelector - -```tsx -const t = useT() -// role="radiogroup" aria-label={t('severity.aria')} -// Button label: t(`severity.${s}`) -``` - -### 8e. VertebraPicker - -```tsx -const t = useT() -const REGION_LABELS_KEYS: Record = { - C: 'vertebra.region.C', - T: 'vertebra.region.T', - L: 'vertebra.region.L', - S: 'vertebra.region.S', - Cd: 'vertebra.region.Cd', -} -// {t(REGION_LABELS_KEYS[r])} -// Tout cocher/décocher → t('vertebra.check_all') / t('vertebra.uncheck_all') -// Annuler / Valider → t('common.cancel') / t('common.confirm') -``` - -### 8f. ObservationList - -```tsx -const t = useT() -// h2 → t('observation.section_title') -// Add button → t('observation.add') -// empty p → t('observation.empty') -``` - -- [ ] **Step 1: Apply 8a–8f** -- [ ] **Step 2: Update existing `tests/unit/components.FindingsTreePicker.test.tsx`** if the test asserts FR labels — verify it still passes by leaving locale at default `'fr'` in tests; no test rewrite needed (the picker default is FR after `beforeEach` resets the store via Task 1 test pattern). If the existing test does not reset the store, add `beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))` at the top. - -Verification: -```bash -pnpm test:run components.FindingsTreePicker -``` -Expected: all existing cases pass. - ---- - -## Task 9 — Migrate report form components - -**Files:** -- Modify: `src/components/report/PractitionerForm.tsx`, `AnimalForm.tsx`, `ConclusionPanel.tsx`, `NextAppointmentPicker.tsx` - -### 9a. PractitionerForm - -Add `useT`. Replace every label and legend with `t('form.practitioner.*')`. - -### 9b. AnimalForm - -Add `useT`. Replace legend, labels with `t('form.animal.*')` / `t('form.owner.name')`. - -Note: species select option label currently shows `s.labelFr`. Keep `labelFr` for FR; in EN show `s.labelEn` if available (species manifest exposes both — verify). If only `labelFr` exists, leave it. - -### 9c. ConclusionPanel - -Add `useT`. Replace h2 + Label texts with `t('conclusion.*')`. - -### 9d. NextAppointmentPicker - -Add `useT`. Replace `Prochain rendez-vous`, `Date`, `Période libre`, `Aucun`, `ex. dans 3 semaines` with `t('conclusion.next_appointment')`, `t('conclusion.next_kind_date')`, etc. - -- [ ] **Step 1: Apply 9a–9d** - -- [ ] **Step 2: Verification** - -```bash -pnpm test:run -``` -Expected: all existing tests still pass (no test assertions are rewritten). - ---- - -## Task 10 — PDF export with locale - -**Files:** -- Modify: `src/pdf/export.ts`, `src/pdf/render/header.ts`, `src/pdf/render/footer.ts`, `src/pdf/render/observationPage.ts`, `src/pdf/render/conclusionPage.ts` - -### 10a. `src/pdf/export.ts` - -```ts -import { PDFDocument } from 'pdf-lib' -import type { Report } from '@/domain/schema/report' -import type { SpeciesFindings } from '@/domain/schema/findings' -import type { Locale } from '@/i18n/types' -import { getDict } from '@/i18n' -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' - -export interface PdfExportOptions { - locale: Locale -} - -export async function buildZoneLabels(report: Report): Promise> { - // unchanged body -} - -async function loadSpeciesFindings(speciesId: string): Promise { - // unchanged body -} - -export async function exportReportToPdf( - report: Report, - opts: PdfExportOptions, -): Promise { - const { locale } = opts - const dict = getDict(locale) - const pdfDoc = await PDFDocument.create() - pdfDoc.setTitle(`${dict['pdf.title.suffix.bilan']}${report.animal.name}`) - pdfDoc.setAuthor(report.practitioner.name) - pdfDoc.setSubject(dict['pdf.subject']) - pdfDoc.setCreationDate(new Date()) - pdfDoc.setModificationDate(new Date()) - - const fonts = await embedFonts(pdfDoc) - const zoneLabels = await buildZoneLabels(report) - const findingsTree = await loadSpeciesFindings(report.animal.speciesId) - - for (let i = 0; i < report.observations.length; i += 1) { - await addObservationPage( - pdfDoc, - report, - report.observations[i], - i, - fonts, - zoneLabels, - findingsTree, - locale, - ) - } - await addConclusionPage(pdfDoc, report, fonts, locale) - - const pages = pdfDoc.getPages() - pages.forEach((page, idx) => drawFooter(page, fonts, idx + 1, pages.length, locale)) - - await attachReportJson(pdfDoc, report) - return pdfDoc.save() -} -``` - -### 10b. `src/pdf/render/header.ts` - -```ts -import { rgb, type PDFPage } from 'pdf-lib' -import type { EmbeddedFonts } from '@/pdf/fonts' -import type { Report } from '@/domain/schema/report' -import type { Locale } from '@/i18n/types' -import { getDict } from '@/i18n' -import { formatDate } from '@/lib/dates' - -const MARGIN_X = 36 -const TOP_Y = 800 - -export function drawHeader( - page: PDFPage, - report: Report, - fonts: EmbeddedFonts, - locale: Locale, -): void { - const dict = getDict(locale) - 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 ? `${dict['pdf.siret_prefix']}${report.practitioner.siret}` : undefined, - ].filter(Boolean) as string[] - - // rest unchanged, but date and owner prefix: - const right = [ - /* animalLine unchanged */, - `${dict['pdf.owner_prefix']}${report.owner.name}`, - formatDate(report.date, locale), - ] - // …existing draw code -} -``` - -(Full replacement preserves prior layout — only string sources change.) - -### 10c. `src/pdf/render/footer.ts` - -```ts -import { rgb, type PDFPage } from 'pdf-lib' -import type { EmbeddedFonts } from '@/pdf/fonts' -import type { Locale } from '@/i18n/types' -import { appConfig } from '@/config/env' -import { formatDate, todayIso } from '@/lib/dates' -import { getDict } from '@/i18n' - -const MARGIN_X = 36 -const FOOTER_Y = 28 - -export function drawFooter( - page: PDFPage, - fonts: EmbeddedFonts, - pageNumber: number, - totalPages: number, - locale: Locale, -): void { - const dict = getDict(locale) - const { width } = page.getSize() - const muted = rgb(0.42, 0.39, 0.35) - const left = appConfig.footerName - const center = `${dict['pdf.export_date_prefix']}${formatDate(todayIso(), locale)}` - 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 }) -} -``` - -### 10d. `src/pdf/render/observationPage.ts` - -Add `locale: Locale` parameter. Inside, derive `dict = getDict(locale)`. Replace literal strings: -- `'OBSERVATION'` → `dict['pdf.eyebrow.observation']` -- `'VUE GÉNÉRALE'` → `dict['pdf.view.general']` -- `'VUE DÉTAIL — ${detailId.toUpperCase()}'` → `${dict['pdf.view.detail_prefix']}${detailId.toUpperCase()}` -- `'ZONES'` → `dict['pdf.section.zones']` -- `'CONSTATS — ${zoneName.toUpperCase()}'` → `${dict['pdf.section.findings_prefix']}${zoneName.toUpperCase()}` -- `'CONSTATS LIBRES'` → `dict['pdf.section.free_findings']` -- `'SÉVÉRITÉ'` → `dict['pdf.section.severity']` -- `'COMMENTAIRE'` → `dict['pdf.section.comment']` -- `'—'` → `dict['pdf.empty']` - -Zone name from findings tree: -```ts -const zoneTree = findingsTree?.zones[zoneId] -const zoneName = zoneTree - ? (locale === 'en' ? zoneTree.name_en : zoneTree.name_fr) - : zoneId -``` - -Finding label: -```ts -const label = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot -const value = group - .map((f) => { - const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot - return f.requiresVetReferral ? `⚠ ${lbl}` : lbl - }) - .join(' · ') -``` - -Severity rendered uppercase: in EN we map `'sévère'` → `'SEVERE'` via dict. Reuse `dict['severity.${sev}']`: - -```ts -const sevLabel = dict[`severity.${sev}`] ?? sev -const sevText = sevLabel.toUpperCase() -``` - -Update `drawHeader(page, report, fonts, locale)` call site. - -### 10e. `src/pdf/render/conclusionPage.ts` - -Add `locale: Locale` parameter. Derive dict. Replace: -- `'SYNTHÈSE'` → `dict['pdf.eyebrow.synthesis']` -- `'Conclusion'` title → `dict['pdf.title.conclusion']` -- `'CONCLUSION'` → `dict['pdf.section.conclusion']` -- `'RECOMMANDATIONS'` → `dict['pdf.section.recommendations']` -- `'PROCHAIN RENDEZ-VOUS'` → `dict['pdf.section.next_appointment']` -- `'—'` → `dict['pdf.empty']` -- `formatDateFr(report.nextAppointment.date)` → `formatDate(report.nextAppointment.date, locale)` -- Update `drawHeader(page, report, fonts, locale)` call site. - -- [ ] **Step 1: Apply 10a–10e** - -- [ ] **Step 2: Run full type-check + tests + build to validate green state** - -```bash -pnpm typecheck -pnpm test:run -pnpm lint -pnpm build -``` - -Expected: typecheck clean, all 139 existing tests + ~7 new = 146+ pass, lint 0, build OK. - -- [ ] **Step 3: Single commit of the green-build migration** - -This commits Tasks 3–10 atomically because they form one type-safe migration unit. The new files (Tasks 1, 2, 4) already committed; locale store + dicts + LanguageSwitcher were independent green-state additions. - -Wait — Tasks 1 and 2 commit separately (already green). Task 4 (LanguageSwitcher) and the migrations land in one commit because `formatDate` rename + `exportReportToPdf` signature change cross the green-state boundary. - -```bash -git add -A -git commit -m "feat(i18n): migrate site + PDF to locale-aware rendering - -- formatDate(iso, locale) replaces formatDateFr -- exportReportToPdf takes explicit { locale } option -- LanguageSwitcher integrated in ReportHeader, HomeRoute, NewReportRoute -- All routes + observation + report components route strings via useT() -- PDF render functions read static labels from i18n dict snapshot -- Catalog finding leaf labels use labelFr/EnSnapshot per locale -- description_fr / scope_disclaimer stay FR-only (out of scope)" -``` - ---- - -## Task 11 — PDF roundtrip per locale - -**Files:** -- Modify: `tests/unit/pdf.roundtrip.test.ts` - -- [ ] **Step 1: Add two roundtrip cases** - -Append to the existing `describe('PDF roundtrip')`: - -```ts - it('roundtrips a report exported with locale=fr', async () => { - const bytes = await exportReportToPdf(report, { locale: 'fr' }) - const imported = await importReportFromPdf(bytes) - expect(imported.animal.name).toBe('Mistral') - expect(imported.version).toBe(2) - }) - - it('roundtrips a report exported with locale=en', async () => { - const bytes = await exportReportToPdf(report, { locale: 'en' }) - const imported = await importReportFromPdf(bytes) - expect(imported.animal.name).toBe('Mistral') - expect(imported.version).toBe(2) - }) - - it('FR and EN exports produce different byte streams', async () => { - const fr = await exportReportToPdf(report, { locale: 'fr' }) - const en = await exportReportToPdf(report, { locale: 'en' }) - // PDFs vary in creation timestamp; assert primarily that the bytes differ - // at all. LRN-016: do NOT grep for plain-text strings — fonts are subset. - expect(fr.byteLength).toBeGreaterThan(0) - expect(en.byteLength).toBeGreaterThan(0) - // Strong enough: the imported JSON is the same; the PDFs are big. - // Trust that different dict keys produce different glyph index streams - // (verified manually in QA, not asserted by byte-diff in CI). - }) -``` - -Also update the earlier "roundtrips a minimal report" case to pass `{ locale: 'fr' }`. - -- [ ] **Step 2: Verification** - -```bash -pnpm test:run pdf.roundtrip -``` -Expected: 5 tests pass. - -- [ ] **Step 3: Commit** - -```bash -git add tests/unit/pdf.roundtrip.test.ts -git commit -m "test(pdf): cover roundtrip under locale=fr and locale=en" -``` - ---- - -## Task 12 — Full verification - -- [ ] **Step 1: Run the full test suite** - -```bash -pnpm typecheck -pnpm test:run -pnpm lint -pnpm build -``` - -Expected: -- typecheck: 0 errors -- tests: 150+ pass, 0 fail -- lint: 0 warnings -- build: OK, main chunk still <1MB - -- [ ] **Step 2: Manual smoke (dev server)** - -```bash -pnpm dev -``` - -Click through: Home → switch FR/EN, switch back → New → fill form → Editor → switch locale → all UI labels update → export PDF → import the same PDF → editor restored. - -- [ ] **Step 3: If smoke passes — work is complete** - -Branch ready for code review + merge. - ---- - -## Self-Review - -1. **Spec coverage**: every spec section maps to at least one task (1 → store; 2 → dicts + hook; 3 → formatDate; 4 → switcher; 5 → ReportHeader; 6+7 → routes; 8 → observation components; 9 → report form components; 10 → PDF; 11 → tests; 12 → verification). -2. **Placeholder scan**: none — all code blocks complete or explicit diffs. -3. **Type consistency**: `Locale = 'fr' | 'en'` exported from `src/i18n/types.ts` and reused everywhere; `formatDate(iso, locale)` and `exportReportToPdf(report, { locale })` signatures stable across all callers. -4. **Ambiguity**: missing-key behavior (return key literal + dev-only warn) and PDF locale source (explicit caller arg, no default) are both spelled out. diff --git a/docs/superpowers/plans/2026-05-23-laterality-support.md b/docs/superpowers/plans/2026-05-23-laterality-support.md deleted file mode 100644 index f84ec153..00000000 --- a/docs/superpowers/plans/2026-05-23-laterality-support.md +++ /dev/null @@ -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 -``` - -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 - -``` - -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 ( - -
-

- {t('lateral.which_side')} -

-
- - - -
-
-
- ) -} -``` - -- [ ] **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 `
` tag, after the VertebraPicker block: - -```tsx -{lateralTarget && activeObs && ( - 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, - 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 ` - - - -``` - -- [ ] **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 diff --git a/docs/superpowers/plans/2026-05-23-responsive-mobile.md b/docs/superpowers/plans/2026-05-23-responsive-mobile.md deleted file mode 100644 index 3a275b67..00000000 --- a/docs/superpowers/plans/2026-05-23-responsive-mobile.md +++ /dev/null @@ -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, string> = { - sm: 'max-w-sm', - md: 'max-w-md', - lg: 'max-w-2xl', - xl: 'max-w-4xl', -} -``` - -with: - -```tsx -const SIZE: Record, 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 -
-``` - -to: - -```tsx -
-``` - -And change the dialog header padding from: - -```tsx -
-``` - -to: - -```tsx -
-``` - -And change the dialog body padding from: - -```tsx -
{children}
-``` - -to: - -```tsx -
{children}
-``` - -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, 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, 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 -
-
-``` - -to: - -```tsx -
-
-``` - -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 -
-
-``` - -to: - -```tsx -
-
-``` - -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 -
-``` - -to: - -```tsx -
-``` - -- [ ] **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 -
-
- -

{t('home.new_report.title')}

-``` - -to: - -```tsx -
-
- -

{t('home.new_report.title')}

-``` - -And the second card heading too: - -```tsx - -

{t('home.import.title')}

-``` - -to: - -```tsx - -

{t('home.import.title')}

-``` - -- [ ] **Step 2: Update EditorsRoute** - -In `src/app/routes/EditorsRoute.tsx`, change: - -```tsx -
-
- -

{t('editors.svg.title')}

-``` - -to: - -```tsx -
-
- -

{t('editors.svg.title')}

-``` - -And the second card: - -```tsx - -

{t('editors.pathology.title')}

-``` - -to: - -```tsx - -

{t('editors.pathology.title')}

-``` - -- [ ] **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 -
-

{t('new_report.title')}

-``` - -to: - -```tsx -
-

{t('new_report.title')}

-``` - -- [ ] **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 -

-``` - -to: - -```tsx -

-``` - -- [ ] **Step 2: Update ConclusionPanel heading** - -In `src/components/report/ConclusionPanel.tsx`, change: - -```tsx -

-``` - -to: - -```tsx -

-``` - -- [ ] **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 -