Purged from docs/superpowers by the gitflow finish of step 1 (BDR-065); that path is purged at every finish, so the records live under docs/history/superpowers/ instead. References updated.
53 KiB
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<string, string> |
src/i18n/fr.ts |
FR dict (flat snake_case keys) |
src/i18n/en.ts |
EN dict, same keys |
src/i18n/index.ts |
dicts: Record<Locale, Dict>, 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
// 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
// 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<LocaleStore>((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).
// src/i18n/types.ts
export type Locale = 'fr' | 'en'
export type Dict = Record<string, string>
- Step 4: Run test to verify it passes
Run: pnpm test:run state.localeStore
Expected: PASS — 3 tests.
- Step 5: Commit
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
// 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)
}
})
})
// 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
// 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',
}
// 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',
}
// src/i18n/index.ts
import { fr } from './fr'
import { en } from './en'
import type { Dict, Locale } from './types'
export const dicts: Record<Locale, Dict> = { fr, en }
export function getDict(locale: Locale): Dict {
return dicts[locale]
}
// 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
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:
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
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<Locale, string> = {
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
// 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(<LanguageSwitcher />)
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(<LanguageSwitcher />)
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
// 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 (
<div
role="group"
aria-label="Language"
className="inline-flex rounded-full border border-[var(--color-border)] overflow-hidden text-xs font-medium"
>
{ITEMS.map((item) => {
const active = locale === item.value
return (
<button
key={item.value}
type="button"
aria-label={item.ariaLabel}
aria-pressed={active}
onClick={() => setLocale(item.value)}
className={[
'px-2.5 py-1 transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]',
active
? 'bg-[var(--color-accent)] text-white'
: 'text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)]',
].join(' ')}
>
{item.label}
</button>
)
})}
</div>
)
}
- 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
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 (
<header className="flex items-center justify-between gap-4 px-6 py-3 border-b border-[var(--color-border)] bg-[var(--color-surface)]">
<div className="flex items-center gap-3">
<Button
variant="ghost"
size="sm"
onClick={() => navigate('/')}
aria-label={t('common.back_to_home')}
>
← {t('common.home')}
</Button>
<Link
to="/"
aria-label={t('common.back_to_home')}
className="rounded-md px-1 py-0.5 hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Brand />
</Link>
</div>
<div className="flex items-center gap-4">
<LanguageSwitcher />
<div className="text-sm text-right text-[var(--color-ink-muted)]">
<div className="text-[var(--color-ink)] font-medium">
{report.animal.name} · {report.owner.name}
</div>
<div>{formatDate(report.date, locale)}</div>
</div>
{onEditInfos && (
<Button variant="secondary" size="sm" onClick={onEditInfos}>
{t('editor.edit_infos')}
</Button>
)}
</div>
</header>
)
}
- 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:
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<HTMLInputElement | null>(null)
const hydrate = useReportStore((s) => s.hydrateReport)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const t = useT()
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
if (!file) return
setBusy(true)
setError(null)
try {
const bytes = new Uint8Array(await file.arrayBuffer())
const report = await importReportFromPdf(bytes)
hydrate(report)
navigate('/editor')
} catch (err) {
setError(err instanceof ImportError ? err.message : t('home.import.error_generic'))
} finally {
setBusy(false)
if (fileRef.current) fileRef.current.value = ''
}
}
return (
<main className="min-h-screen flex flex-col">
<header className="px-6 py-4 border-b border-[var(--color-border)] flex items-center justify-between">
<Brand size="lg" />
<div className="flex items-center gap-4">
<LanguageSwitcher />
<span className="text-sm text-[var(--color-ink-muted)]">{cfg.tagline}</span>
</div>
</header>
<section className="flex-1 grid place-items-center px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
<Card className="p-6 space-y-4">
<h2 className="font-serif text-2xl">{t('home.new_report.title')}</h2>
<p className="text-sm text-[var(--color-ink-muted)]">{t('home.new_report.description')}</p>
<Button onClick={() => navigate('/new')} size="lg">{t('home.new_report.cta')}</Button>
</Card>
<Card className="p-6 space-y-4">
<h2 className="font-serif text-2xl">{t('home.import.title')}</h2>
<p className="text-sm text-[var(--color-ink-muted)]">{t('home.import.description')}</p>
<input ref={fileRef} type="file" accept="application/pdf,.pdf" className="hidden" onChange={onPickFile} />
<Button variant="secondary" size="lg" onClick={() => fileRef.current?.click()} disabled={busy}>
{busy ? t('home.import.loading') : t('home.import.cta')}
</Button>
{error && <p className="text-sm text-red-700">{error}</p>}
</Card>
</div>
</section>
</main>
)
}
- Step 2: NewReportRoute
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 (
<main className="min-h-screen">
<header className="px-6 py-4 border-b border-[var(--color-border)] flex items-center justify-between">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate('/')} aria-label={t('common.back_to_home')}>
← {t('common.home')}
</Button>
<Link
to="/"
aria-label={t('common.back_to_home')}
className="rounded-md px-1 py-0.5 hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Brand />
</Link>
</div>
<LanguageSwitcher />
</header>
<div className="max-w-3xl mx-auto px-6 py-8 space-y-8">
<h1 className="font-serif text-3xl">{t('new_report.title')}</h1>
<div>
<Label htmlFor="date">{t('new_report.date_label')}</Label>
<Input id="date" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</div>
<PractitionerForm value={practitioner} onChange={setPractitioner} />
<AnimalForm animal={animal} owner={owner} onChangeAnimal={setAnimal} onChangeOwner={setOwner} />
<div className="flex gap-3 justify-end">
<Button variant="ghost" onClick={() => navigate('/')}>{t('common.cancel')}</Button>
<Button disabled={!canSubmit} onClick={submit}>{t('new_report.submit')}</Button>
</div>
</div>
</main>
)
}
- Step 3: NotFoundRoute
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 (
<main className="min-h-screen grid place-items-center">
<div className="text-center space-y-4">
<h1 className="font-serif text-4xl">{t('not_found.title')}</h1>
<p className="text-[var(--color-ink-muted)]">{t('not_found.description')}</p>
<Button onClick={() => navigate('/')}>{t('common.back_to_home')}</Button>
</div>
</main>
)
}
Task 7 — Migrate EditorRoute
Files:
- Modify:
src/app/routes/EditorRoute.tsx
Key changes:
- Import
useTanduseLocaleStore; read locale from store. - Replace hardcoded FR strings in dialogs, buttons, alert with
t(). exportReportToPdf(report)→exportReportToPdf(report, { locale }).- Vertebra picker title prefix from dict.
- Step 1: Apply changes
In EditorRoute.tsx:
-import { exportReportToPdf } from '@/pdf/export'
+import { exportReportToPdf } from '@/pdf/export'
+import { useT } from '@/i18n/useT'
+import { useLocaleStore } from '@/state/localeStore'
export default function EditorRoute() {
const navigate = useNavigate()
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
const report = useReportStore((s) => s.report)
In onExport:
- const bytes = await exportReportToPdf(report)
+ const bytes = await exportReportToPdf(report, { locale })
- 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:
// Around the export button block at the bottom of the editor body:
<Button onClick={onExport} disabled={exporting}>
{exporting ? t('editor.exporting') : t('editor.export')}
</Button>
// Edit-infos Dialog:
<Dialog
open={editOpen}
onClose={closeEditInfos}
title={t('editor.edit_dialog_title')}
size="lg"
>
<div className="space-y-8">
{/* …forms… */}
<div className="flex gap-3 justify-end pt-2 border-t border-[var(--color-border)]">
<Button variant="ghost" onClick={closeEditInfos}>
{t('common.cancel')}
</Button>
<Button
onClick={saveEditInfos}
disabled={
!editDraft.practitioner.name.trim() ||
!editDraft.animal.name.trim() ||
!editDraft.owner.name.trim()
}
>
{t('common.save')}
</Button>
</div>
</div>
</Dialog>
// Disclaimer dialog:
<Dialog
open
onClose={acknowledgeDisclaimer}
title={t('editor.disclaimer_title')}
size="md"
>
<div className="space-y-4">
<p className="text-sm text-[var(--color-ink)]">{disclaimer}</p>
<div className="flex justify-end">
<Button onClick={acknowledgeDisclaimer}>{t('common.understood')}</Button>
</div>
</div>
</Dialog>
// 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:
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évelopperaria-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
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
const t = useT()
// role="radiogroup" aria-label={t('severity.aria')}
// Button label: t(`severity.${s}`)
8e. VertebraPicker
const t = useT()
const REGION_LABELS_KEYS: Record<VertebralRegion, string> = {
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
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.tsxif 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 afterbeforeEachresets the store via Task 1 test pattern). If the existing test does not reset the store, addbeforeEach(() => useLocaleStore.setState({ locale: 'fr' }))at the top.
Verification:
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
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
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<Map<string, string>> {
// unchanged body
}
async function loadSpeciesFindings(speciesId: string): Promise<SpeciesFindings | null> {
// unchanged body
}
export async function exportReportToPdf(
report: Report,
opts: PdfExportOptions,
): Promise<Uint8Array> {
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
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
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:
const zoneTree = findingsTree?.zones[zoneId]
const zoneName = zoneTree
? (locale === 'en' ? zoneTree.name_en : zoneTree.name_fr)
: zoneId
Finding label:
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}']:
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
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.
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'):
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
pnpm test:run pdf.roundtrip
Expected: 5 tests pass.
- Step 3: Commit
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
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)
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
- 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).
- Placeholder scan: none — all code blocks complete or explicit diffs.
- Type consistency:
Locale = 'fr' | 'en'exported fromsrc/i18n/types.tsand reused everywhere;formatDate(iso, locale)andexportReportToPdf(report, { locale })signatures stable across all callers. - Ambiguity: missing-key behavior (return key literal + dev-only warn) and PDF locale source (explicit caller arg, no default) are both spelled out.