feat(i18n): migrate site + PDF to locale-aware rendering

- formatDate(iso, locale) replaces formatDateFr in src/lib/dates.ts
- exportReportToPdf(report, { locale }) takes explicit locale option
- LanguageSwitcher segmented FR | EN toggle added; integrated in
  ReportHeader, HomeRoute, NewReportRoute
- All routes (Home, NewReport, Editor, NotFound) + observation
  components (FindingsTreePicker, ObservationCard, FreeTextFindingInput,
  SeveritySelector, VertebraPicker, ObservationList) + report forms
  (PractitionerForm, AnimalForm, ConclusionPanel, NextAppointmentPicker)
  route hardcoded FR via useT()
- PDF render functions (export.ts, header.ts, footer.ts,
  observationPage.ts, conclusionPage.ts) take a locale arg and read
  static labels from the dict snapshot at call time
- Catalog finding leaf labels rendered via labelFr/EnSnapshot per locale
- description_fr / scope_disclaimer stay FR-only (out of scope —
  vet-expert authoring needed for EN copy)
- LanguageSwitcher unit test (2) + lib.dates locale tests (7) cover
  the new behavior

151/151 tests pass, lint 0, typecheck clean, vite build OK
(902KB main + 15KB lazy pathologies chunk).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Bastien ChanotandClaude Opus 4.7 committed 2026-05-20 07:11:40 +02:00
1 parent 359104ce88
commit d6027266bc
25 files changed
+390 -207

No files matched your search

+13 -11
View File
@@ -23,11 +23,15 @@ import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Practitioner } from '@/domain/schema/practitioner' import type { Practitioner } from '@/domain/schema/practitioner'
import type { Animal, Owner } from '@/domain/schema/animal' import type { Animal, Owner } from '@/domain/schema/animal'
import { exportReportToPdf } from '@/pdf/export' import { exportReportToPdf } from '@/pdf/export'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
export default function EditorRoute() { export default function EditorRoute() {
const navigate = useNavigate() const navigate = useNavigate()
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const report = useReportStore((s) => s.report) const report = useReportStore((s) => s.report)
const activeIndex = useReportStore((s) => s.activeObservationIndex) const activeIndex = useReportStore((s) => s.activeObservationIndex)
const addObservation = useReportStore((s) => s.addObservation) const addObservation = useReportStore((s) => s.addObservation)
@@ -246,7 +250,7 @@ export default function EditorRoute() {
if (!report) return if (!report) return
setExporting(true) setExporting(true)
try { try {
const bytes = await exportReportToPdf(report) const bytes = await exportReportToPdf(report, { locale })
const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' }) const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' })
const url = URL.createObjectURL(blob) const url = URL.createObjectURL(blob)
const a = document.createElement('a') const a = document.createElement('a')
@@ -256,9 +260,7 @@ export default function EditorRoute() {
URL.revokeObjectURL(url) URL.revokeObjectURL(url)
} catch (err) { } catch (err) {
console.error('PDF export failed', err) console.error('PDF export failed', err)
window.alert( window.alert(t('editor.export_failed'))
"Échec de la génération du PDF. Réessayez ou contactez le support.",
)
} finally { } finally {
setExporting(false) setExporting(false)
} }
@@ -309,7 +311,7 @@ export default function EditorRoute() {
/> />
<div className="flex justify-end"> <div className="flex justify-end">
<Button onClick={onExport} disabled={exporting}> <Button onClick={onExport} disabled={exporting}>
{exporting ? 'Génération…' : 'Exporter en PDF'} {exporting ? t('editor.exporting') : t('editor.export')}
</Button> </Button>
</div> </div>
</section> </section>
@@ -331,7 +333,7 @@ export default function EditorRoute() {
<Dialog <Dialog
open={editOpen} open={editOpen}
onClose={closeEditInfos} onClose={closeEditInfos}
title="Modifier les informations" title={t('editor.edit_dialog_title')}
size="lg" size="lg"
> >
<div className="space-y-8"> <div className="space-y-8">
@@ -353,7 +355,7 @@ export default function EditorRoute() {
/> />
<div className="flex gap-3 justify-end pt-2 border-t border-[var(--color-border)]"> <div className="flex gap-3 justify-end pt-2 border-t border-[var(--color-border)]">
<Button variant="ghost" onClick={closeEditInfos}> <Button variant="ghost" onClick={closeEditInfos}>
Annuler {t('common.cancel')}
</Button> </Button>
<Button <Button
onClick={saveEditInfos} onClick={saveEditInfos}
@@ -363,7 +365,7 @@ export default function EditorRoute() {
!editDraft.owner.name.trim() !editDraft.owner.name.trim()
} }
> >
Enregistrer {t('common.save')}
</Button> </Button>
</div> </div>
</div> </div>
@@ -374,13 +376,13 @@ export default function EditorRoute() {
<Dialog <Dialog
open open
onClose={acknowledgeDisclaimer} onClose={acknowledgeDisclaimer}
title="Périmètre légal de l'ostéopathie animale" title={t('editor.disclaimer_title')}
size="md" size="md"
> >
<div className="space-y-4"> <div className="space-y-4">
<p className="text-sm text-[var(--color-ink)]">{disclaimer}</p> <p className="text-sm text-[var(--color-ink)]">{disclaimer}</p>
<div className="flex justify-end"> <div className="flex justify-end">
<Button onClick={acknowledgeDisclaimer}>Compris</Button> <Button onClick={acknowledgeDisclaimer}>{t('common.understood')}</Button>
</div> </div>
</div> </div>
</Dialog> </Dialog>
@@ -406,7 +408,7 @@ export default function EditorRoute() {
}} }}
initial={activeObs.zones[vertebraTarget].vertebrae ?? []} initial={activeObs.zones[vertebraTarget].vertebrae ?? []}
formula={species.vertebralFormula} formula={species.vertebralFormula}
title={`Préciser les vertèbres — ${bones.get(activeObs.zones[vertebraTarget].boneId)?.fr ?? ''}`} title={`${t('vertebra.title_prefix')}${bones.get(activeObs.zones[vertebraTarget].boneId)?.fr ?? ''}`}
initialRegion={(() => { initialRegion={(() => {
const b = bones.get(activeObs.zones[vertebraTarget].boneId) const b = bones.get(activeObs.zones[vertebraTarget].boneId)
return regionFromLabel(b?.fr ?? '') ?? regionFromLabel(b?.en ?? '') return regionFromLabel(b?.fr ?? '') ?? regionFromLabel(b?.en ?? '')
+14 -12
View File
@@ -1,11 +1,13 @@
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { useRef, useState } from 'react' import { useRef, useState } from 'react'
import Brand from '@/components/brand/Brand' import Brand from '@/components/brand/Brand'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card' import Card from '@/components/ui/Card'
import { useConfig } from '@/app/providers/ConfigProvider' import { useConfig } from '@/app/providers/ConfigProvider'
import { importReportFromPdf, ImportError } from '@/pdf/import' import { importReportFromPdf, ImportError } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore' import { useReportStore } from '@/state/reportStore'
import { useT } from '@/i18n/useT'
export default function HomeRoute() { export default function HomeRoute() {
const navigate = useNavigate() const navigate = useNavigate()
@@ -14,6 +16,7 @@ export default function HomeRoute() {
const hydrate = useReportStore((s) => s.hydrateReport) const hydrate = useReportStore((s) => s.hydrateReport)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const t = useT()
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) { async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0] const file = e.target.files?.[0]
@@ -26,7 +29,7 @@ export default function HomeRoute() {
hydrate(report) hydrate(report)
navigate('/editor') navigate('/editor')
} catch (err) { } catch (err) {
setError(err instanceof ImportError ? err.message : "Erreur de lecture du PDF.") setError(err instanceof ImportError ? err.message : t('home.import.error_generic'))
} finally { } finally {
setBusy(false) setBusy(false)
if (fileRef.current) fileRef.current.value = '' if (fileRef.current) fileRef.current.value = ''
@@ -37,25 +40,24 @@ export default function HomeRoute() {
<main className="min-h-screen flex flex-col"> <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"> <header className="px-6 py-4 border-b border-[var(--color-border)] flex items-center justify-between">
<Brand size="lg" /> <Brand size="lg" />
<span className="text-sm text-[var(--color-ink-muted)]">{cfg.tagline}</span> <div className="flex items-center gap-4">
<LanguageSwitcher />
<span className="text-sm text-[var(--color-ink-muted)]">{cfg.tagline}</span>
</div>
</header> </header>
<section className="flex-1 grid place-items-center px-6"> <section className="flex-1 grid place-items-center px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full"> <div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
<Card className="p-6 space-y-4"> <Card className="p-6 space-y-4">
<h2 className="font-serif text-2xl">Nouveau bilan</h2> <h2 className="font-serif text-2xl">{t('home.new_report.title')}</h2>
<p className="text-sm text-[var(--color-ink-muted)]"> <p className="text-sm text-[var(--color-ink-muted)]">{t('home.new_report.description')}</p>
Démarrer un nouveau bilan d&apos;ostéopathie sur un animal. <Button onClick={() => navigate('/new')} size="lg">{t('home.new_report.cta')}</Button>
</p>
<Button onClick={() => navigate('/new')} size="lg">Commencer</Button>
</Card> </Card>
<Card className="p-6 space-y-4"> <Card className="p-6 space-y-4">
<h2 className="font-serif text-2xl">Importer un PDF</h2> <h2 className="font-serif text-2xl">{t('home.import.title')}</h2>
<p className="text-sm text-[var(--color-ink-muted)]"> <p className="text-sm text-[var(--color-ink-muted)]">{t('home.import.description')}</p>
Reprendre un bilan précédent généré par cette application pour effectuer un suivi.
</p>
<input ref={fileRef} type="file" accept="application/pdf,.pdf" className="hidden" onChange={onPickFile} /> <input ref={fileRef} type="file" accept="application/pdf,.pdf" className="hidden" onChange={onPickFile} />
<Button variant="secondary" size="lg" onClick={() => fileRef.current?.click()} disabled={busy}> <Button variant="secondary" size="lg" onClick={() => fileRef.current?.click()} disabled={busy}>
{busy ? 'Lecture…' : 'Choisir un PDF'} {busy ? t('home.import.loading') : t('home.import.cta')}
</Button> </Button>
{error && <p className="text-sm text-red-700">{error}</p>} {error && <p className="text-sm text-red-700">{error}</p>}
</Card> </Card>
+21 -20
View File
@@ -3,16 +3,19 @@ import { Link, useNavigate } from 'react-router-dom'
import PractitionerForm from '@/components/report/PractitionerForm' import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm' import AnimalForm from '@/components/report/AnimalForm'
import Brand from '@/components/brand/Brand' import Brand from '@/components/brand/Brand'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import { todayIso } from '@/lib/dates' import { todayIso } from '@/lib/dates'
import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache' import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore' import { useReportStore } from '@/state/reportStore'
import { useT } from '@/i18n/useT'
export default function NewReportRoute() { export default function NewReportRoute() {
const navigate = useNavigate() const navigate = useNavigate()
const initReport = useReportStore((s) => s.initReport) const initReport = useReportStore((s) => s.initReport)
const t = useT()
const [practitioner, setPractitioner] = useState({ name: '' }) const [practitioner, setPractitioner] = useState({ name: '' })
const [animal, setAnimal] = useState({ speciesId: 'equine', name: '' }) const [animal, setAnimal] = useState({ speciesId: 'equine', name: '' })
@@ -43,34 +46,32 @@ export default function NewReportRoute() {
return ( return (
<main className="min-h-screen"> <main className="min-h-screen">
<header className="px-6 py-4 border-b border-[var(--color-border)] flex items-center gap-3"> <header className="px-6 py-4 border-b border-[var(--color-border)] flex items-center justify-between">
<Button <div className="flex items-center gap-3">
variant="ghost" <Button variant="ghost" size="sm" onClick={() => navigate('/')} aria-label={t('common.back_to_home')}>
size="sm" ← {t('common.home')}
onClick={() => navigate('/')} </Button>
aria-label="Retour à l'accueil" <Link
> to="/"
← Accueil aria-label={t('common.back_to_home')}
</Button> 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)]"
<Link >
to="/" <Brand />
aria-label="Retour à l'accueil" </Link>
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)]" </div>
> <LanguageSwitcher />
<Brand />
</Link>
</header> </header>
<div className="max-w-3xl mx-auto px-6 py-8 space-y-8"> <div className="max-w-3xl mx-auto px-6 py-8 space-y-8">
<h1 className="font-serif text-3xl">Nouveau bilan</h1> <h1 className="font-serif text-3xl">{t('new_report.title')}</h1>
<div> <div>
<Label htmlFor="date">Date du bilan</Label> <Label htmlFor="date">{t('new_report.date_label')}</Label>
<Input id="date" type="date" value={date} onChange={(e) => setDate(e.target.value)} /> <Input id="date" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</div> </div>
<PractitionerForm value={practitioner} onChange={setPractitioner} /> <PractitionerForm value={practitioner} onChange={setPractitioner} />
<AnimalForm animal={animal} owner={owner} onChangeAnimal={setAnimal} onChangeOwner={setOwner} /> <AnimalForm animal={animal} owner={owner} onChangeAnimal={setAnimal} onChangeOwner={setOwner} />
<div className="flex gap-3 justify-end"> <div className="flex gap-3 justify-end">
<Button variant="ghost" onClick={() => navigate('/')}>Annuler</Button> <Button variant="ghost" onClick={() => navigate('/')}>{t('common.cancel')}</Button>
<Button disabled={!canSubmit} onClick={submit}>Démarrer le bilan</Button> <Button disabled={!canSubmit} onClick={submit}>{t('new_report.submit')}</Button>
</div> </div>
</div> </div>
</main> </main>
+5 -3
View File
@@ -1,14 +1,16 @@
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import { useT } from '@/i18n/useT'
export default function NotFoundRoute() { export default function NotFoundRoute() {
const navigate = useNavigate() const navigate = useNavigate()
const t = useT()
return ( return (
<main className="min-h-screen grid place-items-center"> <main className="min-h-screen grid place-items-center">
<div className="text-center space-y-4"> <div className="text-center space-y-4">
<h1 className="font-serif text-4xl">Page introuvable</h1> <h1 className="font-serif text-4xl">{t('not_found.title')}</h1>
<p className="text-[var(--color-ink-muted)]">Le chemin demandé n&apos;existe pas.</p> <p className="text-[var(--color-ink-muted)]">{t('not_found.description')}</p>
<Button onClick={() => navigate('/')}>Retour à l&apos;accueil</Button> <Button onClick={() => navigate('/')}>{t('common.back_to_home')}</Button>
</div> </div>
</main> </main>
) )
+40
View File
@@ -0,0 +1,40 @@
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>
)
}
@@ -5,6 +5,8 @@ import type {
} from '@/domain/schema/findings' } from '@/domain/schema/findings'
import type { Finding } from '@/domain/schema/observation' import type { Finding } from '@/domain/schema/observation'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface FindingsTreePickerProps { export interface FindingsTreePickerProps {
zoneId: string zoneId: string
@@ -53,6 +55,13 @@ export default function FindingsTreePicker({
selected, selected,
onChange, onChange,
}: FindingsTreePickerProps) { }: FindingsTreePickerProps) {
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
const [path, setPath] = useState<string[]>([]) const [path, setPath] = useState<string[]>([])
const currentNodes = useMemo<FindingNode[]>(() => { const currentNodes = useMemo<FindingNode[]>(() => {
@@ -67,19 +76,21 @@ export default function FindingsTreePicker({
) )
const breadcrumb = useMemo<{ label: string; depth: number }[]>(() => { const breadcrumb = useMemo<{ label: string; depth: number }[]>(() => {
const pick = (z: { name_fr: string; name_en: string }) =>
locale === 'en' ? z.name_en : z.name_fr
const crumbs: { label: string; depth: number }[] = [ const crumbs: { label: string; depth: number }[] = [
{ label: tree.name_fr, depth: 0 }, { label: pick(tree), depth: 0 },
] ]
let nodes: FindingNode[] = tree.categories let nodes: FindingNode[] = tree.categories
path.forEach((seg, i) => { path.forEach((seg, i) => {
const n = nodes.find((x) => x.id === seg) const n = nodes.find((x) => x.id === seg)
if (n) { if (n) {
crumbs.push({ label: n.name_fr, depth: i + 1 }) crumbs.push({ label: pick(n), depth: i + 1 })
nodes = n.children ?? [] nodes = n.children ?? []
} }
}) })
return crumbs return crumbs
}, [tree, path]) }, [tree, path, locale])
function isLeafSelected(leafPath: string[]): boolean { function isLeafSelected(leafPath: string[]): boolean {
return selected.some( return selected.some(
@@ -141,9 +152,9 @@ export default function FindingsTreePicker({
})} })}
</div> </div>
{focusedNode?.description_fr && ( {focusedNode && descOf(focusedNode) && (
<p className="text-xs italic text-[var(--color-ink-muted)]"> <p className="text-xs italic text-[var(--color-ink-muted)]">
{focusedNode.description_fr} {descOf(focusedNode)}
</p> </p>
)} )}
@@ -152,22 +163,24 @@ export default function FindingsTreePicker({
size="sm" size="sm"
variant="ghost" variant="ghost"
onClick={() => setPath(path.slice(0, -1))} onClick={() => setPath(path.slice(0, -1))}
aria-label="Retour au niveau précédent" aria-label={t('findings.back_to_parent')}
> >
← Retour {t('findings.back')}
</Button> </Button>
)} )}
<ul className="space-y-1.5 max-h-64 overflow-auto pr-1"> <ul className="space-y-1.5 max-h-64 overflow-auto pr-1">
{currentNodes.length === 0 ? ( {currentNodes.length === 0 ? (
<li className="text-sm text-[var(--color-ink-muted)]"> <li className="text-sm text-[var(--color-ink-muted)]">
Aucune option disponible à ce niveau. {t('findings.no_options')}
</li> </li>
) : ( ) : (
currentNodes.map((node) => { currentNodes.map((node) => {
const nodePath = [...path, node.id] const nodePath = [...path, node.id]
if (isLeaf(node)) { if (isLeaf(node)) {
const checked = isLeafSelected(nodePath) const checked = isLeafSelected(nodePath)
const nodeLabel = nameOf(node)
const nodeDesc = descOf(node)
return ( return (
<li key={node.id}> <li key={node.id}>
<label className="flex items-start gap-2 cursor-pointer"> <label className="flex items-start gap-2 cursor-pointer">
@@ -176,26 +189,26 @@ export default function FindingsTreePicker({
checked={checked} checked={checked}
onChange={() => toggleLeaf(nodePath, node)} onChange={() => toggleLeaf(nodePath, node)}
className="mt-1 accent-[var(--color-accent)]" className="mt-1 accent-[var(--color-accent)]"
aria-label={node.name_fr} aria-label={nodeLabel}
/> />
<div className="flex-1"> <div className="flex-1">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-sm font-medium text-[var(--color-ink)]"> <span className="text-sm font-medium text-[var(--color-ink)]">
{node.name_fr} {nodeLabel}
</span> </span>
{node.requires_vet_referral && ( {node.requires_vet_referral && (
<span <span
title="Référer au vétérinaire" title={t('findings.vet_referral')}
aria-label="Référer au vétérinaire" aria-label={t('findings.vet_referral')}
className="text-[var(--color-danger)]" className="text-[var(--color-danger)]"
> >
⚠ ⚠
</span> </span>
)} )}
</div> </div>
{node.description_fr && ( {nodeDesc && (
<div className="text-xs text-[var(--color-ink-muted)]"> <div className="text-xs text-[var(--color-ink-muted)]">
{node.description_fr} {nodeDesc}
</div> </div>
)} )}
</div> </div>
@@ -204,19 +217,25 @@ export default function FindingsTreePicker({
) )
} }
const selectedCount = countSelectedUnder(nodePath) const selectedCount = countSelectedUnder(nodePath)
const nodeLabel = nameOf(node)
const selectedAria = `${selectedCount} ${
selectedCount > 1
? t('findings.selected_plural')
: t('findings.selected_singular')
}`
return ( return (
<li key={node.id}> <li key={node.id}>
<button <button
type="button" type="button"
onClick={() => setPath(nodePath)} onClick={() => setPath(nodePath)}
className="flex items-center justify-between w-full text-left text-sm px-2 py-1.5 rounded hover:bg-[var(--color-surface-strong)] text-[var(--color-ink)]" className="flex items-center justify-between w-full text-left text-sm px-2 py-1.5 rounded hover:bg-[var(--color-surface-strong)] text-[var(--color-ink)]"
aria-label={`Ouvrir ${node.name_fr}`} aria-label={`${t('findings.open')} ${nodeLabel}`}
> >
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
<span>{node.name_fr}</span> <span>{nodeLabel}</span>
{selectedCount > 0 && ( {selectedCount > 0 && (
<span <span
aria-label={`${selectedCount} constat${selectedCount > 1 ? 's' : ''} sélectionné${selectedCount > 1 ? 's' : ''}`} aria-label={selectedAria}
className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white" className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white"
> >
{selectedCount} {selectedCount}
@@ -2,6 +2,7 @@ import { useState } from 'react'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import Badge from '@/components/ui/Badge' import Badge from '@/components/ui/Badge'
import { useT } from '@/i18n/useT'
export interface FreeTextFindingInputProps { export interface FreeTextFindingInputProps {
items: string[] items: string[]
@@ -13,6 +14,7 @@ export default function FreeTextFindingInput({
onChange, onChange,
}: FreeTextFindingInputProps) { }: FreeTextFindingInputProps) {
const [v, setV] = useState('') const [v, setV] = useState('')
const t = useT()
function add() { function add() {
const trimmed = v.trim() const trimmed = v.trim()
@@ -31,17 +33,17 @@ export default function FreeTextFindingInput({
<Input <Input
value={v} value={v}
onChange={(e) => setV(e.target.value)} onChange={(e) => setV(e.target.value)}
placeholder="Observation additionnelle (texte libre)" placeholder={t('observation.free_placeholder')}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
e.preventDefault() e.preventDefault()
add() add()
} }
}} }}
aria-label="Observation libre" aria-label={t('observation.free_aria')}
/> />
<Button onClick={add} variant="secondary"> <Button onClick={add} variant="secondary">
Ajouter {t('common.add')}
</Button> </Button>
</div> </div>
{items.length > 0 && ( {items.length > 0 && (
@@ -52,7 +54,7 @@ export default function FreeTextFindingInput({
{it} {it}
<button <button
type="button" type="button"
aria-label={`Retirer ${it}`} aria-label={`${t('observation.remove_zone')} ${it}`}
onClick={() => remove(i)} onClick={() => remove(i)}
className="ml-1 text-[var(--color-accent-strong)] hover:text-[var(--color-danger)]" className="ml-1 text-[var(--color-accent-strong)] hover:text-[var(--color-danger)]"
> >
+43 -29
View File
@@ -19,6 +19,8 @@ import Textarea from '@/components/ui/Textarea'
import FindingsTreePicker from './FindingsTreePicker' import FindingsTreePicker from './FindingsTreePicker'
import FreeTextFindingInput from './FreeTextFindingInput' import FreeTextFindingInput from './FreeTextFindingInput'
import SeveritySelector from './SeveritySelector' import SeveritySelector from './SeveritySelector'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface ObservationCardProps { export interface ObservationCardProps {
observation: Observation observation: Observation
@@ -66,6 +68,11 @@ export default function ObservationCard({
onOpenVertebraPicker, onOpenVertebraPicker,
onRemoveZone, onRemoveZone,
}: ObservationCardProps) { }: ObservationCardProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const nameOf = (z: { name_fr: string; name_en: string }) =>
locale === 'en' ? z.name_en : z.name_fr
// Per-zone picker accordion — only one tree picker open at a time, // Per-zone picker accordion — only one tree picker open at a time,
// matching the observation-card accordion semantics. Closed by default // matching the observation-card accordion semantics. Closed by default
// so the card stays compact when first expanded. // so the card stays compact when first expanded.
@@ -75,6 +82,15 @@ export default function ObservationCard({
const findingCount = const findingCount =
observation.findings.length + observation.freeTextFindings.length observation.findings.length + observation.freeTextFindings.length
const zoneCountLabel =
zoneCount > 1
? t('observation.zone_label_plural')
: t('observation.zone_label_singular')
const findingCountLabel =
findingCount > 1
? t('observation.finding_label_plural')
: t('observation.finding_label_singular')
function onHeaderKey(event: React.KeyboardEvent<HTMLDivElement>) { function onHeaderKey(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Enter' || event.key === ' ') { if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault() event.preventDefault()
@@ -89,11 +105,6 @@ export default function ObservationCard({
} }
} }
// SVG data-anno-id values are opaque generator strings (e.g.
// "point-mpbyk..."); the JSON catalog keys observations by stable
// human zone names (e.g. "sphenoid"). Bridge the two by matching the
// bone's FR/EN labels against the catalog labels — EN exact first,
// then FR, then small typos / abbreviations via fuzzy scoring.
const zonesArray = useMemo( const zonesArray = useMemo(
() => (findings ? Object.values(findings.zones) : []), () => (findings ? Object.values(findings.zones) : []),
[findings], [findings],
@@ -131,14 +142,14 @@ export default function ObservationCard({
role="button" role="button"
tabIndex={0} tabIndex={0}
aria-expanded={expanded} aria-expanded={expanded}
aria-label={`${expanded ? 'Réduire' : 'Développer'} l'observation ${index + 1}`} aria-label={`${expanded ? t('observation.collapse_aria') : t('observation.expand_aria')} ${index + 1}`}
onClick={onToggle} onClick={onToggle}
onKeyDown={onHeaderKey} onKeyDown={onHeaderKey}
className="flex items-start justify-between gap-3 p-4 cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40 rounded-2xl" className="flex items-start justify-between gap-3 p-4 cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40 rounded-2xl"
> >
<div className="flex-1 min-h-[60px] text-left"> <div className="flex-1 min-h-[60px] text-left">
<div className="flex items-center gap-2 mb-2"> <div className="flex items-center gap-2 mb-2">
<Badge tone="neutral">Observation #{index + 1}</Badge> <Badge tone="neutral">{t('observation.badge_n')}{index + 1}</Badge>
{observation.severity && ( {observation.severity && (
<Badge <Badge
tone={ tone={
@@ -149,13 +160,12 @@ export default function ObservationCard({
: 'neutral' : 'neutral'
} }
> >
{observation.severity} {t(`severity.${observation.severity}`)}
</Badge> </Badge>
)} )}
</div> </div>
<div className="text-sm text-[var(--color-ink-muted)]"> <div className="text-sm text-[var(--color-ink-muted)]">
{zoneCount} zone{zoneCount > 1 ? 's' : ''} · {findingCount} constat {zoneCount} {zoneCountLabel} · {findingCount} {findingCountLabel}
{findingCount > 1 ? 's' : ''}
</div> </div>
{!expanded && observation.comment && ( {!expanded && observation.comment && (
<p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]"> <p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]">
@@ -172,7 +182,7 @@ export default function ObservationCard({
variant="ghost" variant="ghost"
disabled={!canMoveUp} disabled={!canMoveUp}
onClick={stop(onMoveUp)} onClick={stop(onMoveUp)}
aria-label="Monter" aria-label={t('common.move_up')}
> >
↑ ↑
</Button> </Button>
@@ -181,7 +191,7 @@ export default function ObservationCard({
variant="ghost" variant="ghost"
disabled={!canMoveDown} disabled={!canMoveDown}
onClick={stop(onMoveDown)} onClick={stop(onMoveDown)}
aria-label="Descendre" aria-label={t('common.move_down')}
> >
↓ ↓
</Button> </Button>
@@ -189,7 +199,7 @@ export default function ObservationCard({
size="sm" size="sm"
variant="ghost" variant="ghost"
onClick={stop(onDelete)} onClick={stop(onDelete)}
aria-label="Supprimer" aria-label={t('common.delete')}
> >
🗑 🗑
</Button> </Button>
@@ -197,7 +207,7 @@ export default function ObservationCard({
size="sm" size="sm"
variant="ghost" variant="ghost"
onClick={stop(onToggle)} onClick={stop(onToggle)}
aria-label={expanded ? 'Réduire' : 'Développer'} aria-label={expanded ? t('common.collapse') : t('common.expand')}
> >
{expanded ? '▲' : '▼'} {expanded ? '▲' : '▼'}
</Button> </Button>
@@ -216,11 +226,10 @@ export default function ObservationCard({
> >
<div className="px-4 pb-4 pt-2 border-t border-[var(--color-border)] space-y-6"> <div className="px-4 pb-4 pt-2 border-t border-[var(--color-border)] space-y-6">
<section> <section>
<Label>Zones sélectionnées</Label> <Label>{t('observation.zones_label')}</Label>
{observation.zones.length === 0 ? ( {observation.zones.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]"> <p className="text-sm text-[var(--color-ink-muted)]">
Cliquez sur les zones du schéma pour les ajouter à cette {t('observation.zones_empty')}
observation.
</p> </p>
) : ( ) : (
<ul className="flex flex-wrap gap-2"> <ul className="flex flex-wrap gap-2">
@@ -237,14 +246,14 @@ export default function ObservationCard({
type="button" type="button"
onClick={() => onOpenVertebraPicker(i)} onClick={() => onOpenVertebraPicker(i)}
className="underline text-xs text-[var(--color-accent-strong)]" className="underline text-xs text-[var(--color-accent-strong)]"
title="Préciser les vertèbres pour cette zone" title={t('observation.vertebrae_button_title')}
> >
Vertèbres… {t('observation.vertebrae_button')}
</button> </button>
)} )}
<button <button
type="button" type="button"
aria-label={`Retirer ${b?.fr ?? z.boneId}`} aria-label={`${t('observation.remove_zone')} ${b?.fr ?? z.boneId}`}
onClick={() => onRemoveZone(i)} onClick={() => onRemoveZone(i)}
className="ml-1 text-[var(--color-accent-strong)]" className="ml-1 text-[var(--color-accent-strong)]"
> >
@@ -259,12 +268,12 @@ export default function ObservationCard({
</section> </section>
<section> <section>
<Label>Constats (référentiel)</Label> <Label>{t('observation.findings_catalog_label')}</Label>
{zonesWithTree.length === 0 ? ( {zonesWithTree.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]"> <p className="text-sm text-[var(--color-ink-muted)]">
{observation.zones.length === 0 {observation.zones.length === 0
? 'Sélectionnez une zone pour accéder au référentiel.' ? t('observation.findings_pick_zone_first')
: 'Aucun référentiel disponible pour ces zones. Utilisez le texte libre ci-dessous.'} : t('observation.findings_no_catalog')}
</p> </p>
) : ( ) : (
<ul className="space-y-2"> <ul className="space-y-2">
@@ -273,6 +282,11 @@ export default function ObservationCard({
const selectedCount = observation.findings.filter( const selectedCount = observation.findings.filter(
(f) => f.zoneId === tree.id, (f) => f.zoneId === tree.id,
).length ).length
const selectedAria = `${selectedCount} ${
selectedCount > 1
? t('findings.selected_plural')
: t('findings.selected_singular')
}`
return ( return (
<li <li
key={tree.id} key={tree.id}
@@ -294,11 +308,11 @@ export default function ObservationCard({
> >
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
<span className="text-sm font-medium text-[var(--color-ink)]"> <span className="text-sm font-medium text-[var(--color-ink)]">
{tree.name_fr} {nameOf(tree)}
</span> </span>
{selectedCount > 0 && ( {selectedCount > 0 && (
<span <span
aria-label={`${selectedCount} constat${selectedCount > 1 ? 's' : ''} sélectionné${selectedCount > 1 ? 's' : ''}`} aria-label={selectedAria}
className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white" className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white"
> >
{selectedCount} {selectedCount}
@@ -344,7 +358,7 @@ export default function ObservationCard({
</section> </section>
<section> <section>
<Label>Constats (texte libre)</Label> <Label>{t('observation.findings_free_label')}</Label>
<FreeTextFindingInput <FreeTextFindingInput
items={observation.freeTextFindings} items={observation.freeTextFindings}
onChange={(items) => onChange={(items) =>
@@ -354,7 +368,7 @@ export default function ObservationCard({
</section> </section>
<section> <section>
<Label>Sévérité</Label> <Label>{t('observation.severity_label')}</Label>
<SeveritySelector <SeveritySelector
value={observation.severity} value={observation.severity}
onChange={(s) => onChange({ ...observation, severity: s })} onChange={(s) => onChange({ ...observation, severity: s })}
@@ -363,7 +377,7 @@ export default function ObservationCard({
<section> <section>
<Label htmlFor={`obs-comment-${observation.id}`}> <Label htmlFor={`obs-comment-${observation.id}`}>
Commentaire {t('observation.comment_label')}
</Label> </Label>
<Textarea <Textarea
id={`obs-comment-${observation.id}`} id={`obs-comment-${observation.id}`}
@@ -371,7 +385,7 @@ export default function ObservationCard({
onChange={(e) => onChange={(e) =>
onChange({ ...observation, comment: e.target.value }) onChange({ ...observation, comment: e.target.value })
} }
placeholder="Notes cliniques détaillées…" placeholder={t('observation.comment_placeholder')}
/> />
</section> </section>
</div> </div>
@@ -3,6 +3,7 @@ import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Bone } from '@/anatomy/types' import type { Bone } from '@/anatomy/types'
import ObservationCard from './ObservationCard' import ObservationCard from './ObservationCard'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import { useT } from '@/i18n/useT'
export interface ObservationListProps { export interface ObservationListProps {
observations: Observation[] observations: Observation[]
@@ -34,20 +35,20 @@ export default function ObservationList({
onOpenVertebraPicker, onOpenVertebraPicker,
onRemoveZone, onRemoveZone,
}: ObservationListProps) { }: ObservationListProps) {
const t = useT()
return ( return (
<div className="space-y-3"> <div className="space-y-3">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h2 className="font-serif text-xl text-[var(--color-ink)]"> <h2 className="font-serif text-xl text-[var(--color-ink)]">
Observations {t('observation.section_title')}
</h2> </h2>
<Button size="sm" onClick={onAdd}> <Button size="sm" onClick={onAdd}>
+ Nouvelle observation {t('observation.add')}
</Button> </Button>
</div> </div>
{observations.length === 0 ? ( {observations.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]"> <p className="text-sm text-[var(--color-ink-muted)]">
Aucune observation. Cliquez sur &quot;+ Nouvelle observation&quot; {t('observation.empty')}
puis sur les zones du schéma.
</p> </p>
) : ( ) : (
<ul className="space-y-2"> <ul className="space-y-2">
@@ -1,4 +1,5 @@
import type { Severity } from '@/domain/schema/observation' import type { Severity } from '@/domain/schema/observation'
import { useT } from '@/i18n/useT'
export interface SeveritySelectorProps { export interface SeveritySelectorProps {
value: Severity | undefined value: Severity | undefined
@@ -13,8 +14,9 @@ const COLORS: Record<Severity, string> = {
} }
export default function SeveritySelector({ value, onChange }: SeveritySelectorProps) { export default function SeveritySelector({ value, onChange }: SeveritySelectorProps) {
const t = useT()
return ( return (
<div role="radiogroup" aria-label="Sévérité" className="flex gap-2"> <div role="radiogroup" aria-label={t('severity.aria')} className="flex gap-2">
{SEVERITIES.map((s) => ( {SEVERITIES.map((s) => (
<button <button
key={s} key={s}
@@ -28,7 +30,7 @@ export default function SeveritySelector({ value, onChange }: SeveritySelectorPr
: 'border-[var(--color-border)] text-[var(--color-ink-muted)]', : 'border-[var(--color-border)] text-[var(--color-ink-muted)]',
].join(' ')} ].join(' ')}
> >
{s} {t(`severity.${s}`)}
</button> </button>
))} ))}
</div> </div>
+19 -14
View File
@@ -4,13 +4,15 @@ import Button from '@/components/ui/Button'
import Chip from '@/components/ui/Chip' import Chip from '@/components/ui/Chip'
import type { Vertebra, VertebralRegion } from '@/domain/schema/observation' import type { Vertebra, VertebralRegion } from '@/domain/schema/observation'
import type { VertebralFormula } from '@/domain/species/types' import type { VertebralFormula } from '@/domain/species/types'
import { useT } from '@/i18n/useT'
const REGION_LABELS: Record<VertebralRegion, string> = { const REGIONS: VertebralRegion[] = ['C', 'T', 'L', 'S', 'Cd']
C: 'Cervicales', const REGION_KEY: Record<VertebralRegion, string> = {
T: 'Thoraciques', C: 'vertebra.region.C',
L: 'Lombaires', T: 'vertebra.region.T',
S: 'Sacrales', L: 'vertebra.region.L',
Cd: 'Caudales', S: 'vertebra.region.S',
Cd: 'vertebra.region.Cd',
} }
/** /**
@@ -23,8 +25,6 @@ export function regionFromLabel(label: string): VertebralRegion | undefined {
.normalize('NFD') .normalize('NFD')
.replace(/\p{Diacritic}/gu, '') .replace(/\p{Diacritic}/gu, '')
.toLowerCase() .toLowerCase()
// Order matters: 'caudal'/'coccyg' before 'cervic' is fine; just be
// explicit so no root subsumes another.
if (norm.includes('cervic')) return 'C' if (norm.includes('cervic')) return 'C'
if (norm.includes('thorac') || norm.includes('dors')) return 'T' if (norm.includes('thorac') || norm.includes('dors')) return 'T'
if (norm.includes('lombair') || norm.includes('lumbar')) return 'L' if (norm.includes('lombair') || norm.includes('lumbar')) return 'L'
@@ -53,6 +53,7 @@ export default function VertebraPicker({
title, title,
initialRegion, initialRegion,
}: VertebraPickerProps) { }: VertebraPickerProps) {
const t = useT()
const [selected, setSelected] = useState<Vertebra[]>(initial) const [selected, setSelected] = useState<Vertebra[]>(initial)
const [activeRegion, setActiveRegion] = useState<VertebralRegion>( const [activeRegion, setActiveRegion] = useState<VertebralRegion>(
() => initial[0]?.region ?? initialRegion ?? 'C', () => initial[0]?.region ?? initialRegion ?? 'C',
@@ -84,7 +85,7 @@ export default function VertebraPicker({
return ( return (
<Dialog open={open} onClose={onClose} title={title} size="lg"> <Dialog open={open} onClose={onClose} title={title} size="lg">
<div role="tablist" className="flex flex-wrap gap-2 mb-4"> <div role="tablist" className="flex flex-wrap gap-2 mb-4">
{(Object.keys(REGION_LABELS) as VertebralRegion[]).map((r) => ( {REGIONS.map((r) => (
<button <button
key={r} key={r}
role="tab" role="tab"
@@ -97,7 +98,7 @@ export default function VertebraPicker({
: 'bg-white text-[var(--color-ink)] border-[var(--color-border)]', : 'bg-white text-[var(--color-ink)] border-[var(--color-border)]',
].join(' ')} ].join(' ')}
> >
{REGION_LABELS[r]} {t(REGION_KEY[r])}
</button> </button>
))} ))}
</div> </div>
@@ -115,13 +116,17 @@ export default function VertebraPicker({
</div> </div>
<div className="flex flex-wrap items-center gap-2 mb-6"> <div className="flex flex-wrap items-center gap-2 mb-6">
<Button variant="ghost" size="sm" onClick={() => all(activeRegion, count)}>Tout cocher</Button> <Button variant="ghost" size="sm" onClick={() => all(activeRegion, count)}>
<Button variant="ghost" size="sm" onClick={() => none(activeRegion)}>Tout décocher</Button> {t('vertebra.check_all')}
</Button>
<Button variant="ghost" size="sm" onClick={() => none(activeRegion)}>
{t('vertebra.uncheck_all')}
</Button>
</div> </div>
<div className="flex justify-end gap-2"> <div className="flex justify-end gap-2">
<Button variant="ghost" onClick={onClose}>Annuler</Button> <Button variant="ghost" onClick={onClose}>{t('common.cancel')}</Button>
<Button onClick={() => onConfirm(selected)}>Valider</Button> <Button onClick={() => onConfirm(selected)}>{t('common.confirm')}</Button>
</div> </div>
</Dialog> </Dialog>
) )
+10 -6
View File
@@ -3,6 +3,7 @@ import Label from '@/components/ui/Label'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import Select from '@/components/ui/Select' import Select from '@/components/ui/Select'
import { getAllSpecies } from '@/domain/species/registry' import { getAllSpecies } from '@/domain/species/registry'
import { useT } from '@/i18n/useT'
export interface AnimalFormProps { export interface AnimalFormProps {
animal: Animal animal: Animal
@@ -12,13 +13,16 @@ export interface AnimalFormProps {
} }
export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwner }: AnimalFormProps) { export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwner }: AnimalFormProps) {
const t = useT()
const species = getAllSpecies() const species = getAllSpecies()
const setA = (patch: Partial<Animal>) => onChangeAnimal({ ...animal, ...patch }) const setA = (patch: Partial<Animal>) => onChangeAnimal({ ...animal, ...patch })
return ( return (
<fieldset className="space-y-3"> <fieldset className="space-y-3">
<legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">Animal & propriétaire</legend> <legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">
{t('form.animal.legend')}
</legend>
<div> <div>
<Label htmlFor="an-species">Espèce *</Label> <Label htmlFor="an-species">{t('form.animal.species')}</Label>
<Select <Select
id="an-species" id="an-species"
value={animal.speciesId} value={animal.speciesId}
@@ -30,19 +34,19 @@ export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwne
</Select> </Select>
</div> </div>
<div> <div>
<Label htmlFor="an-name">Nom de l&apos;animal *</Label> <Label htmlFor="an-name">{t('form.animal.name')}</Label>
<Input id="an-name" required value={animal.name} onChange={(e) => setA({ name: e.target.value })} /> <Input id="an-name" required value={animal.name} onChange={(e) => setA({ name: e.target.value })} />
</div> </div>
<div> <div>
<Label htmlFor="an-breed">Race</Label> <Label htmlFor="an-breed">{t('form.animal.breed')}</Label>
<Input id="an-breed" value={animal.breed ?? ''} onChange={(e) => setA({ breed: e.target.value || undefined })} /> <Input id="an-breed" value={animal.breed ?? ''} onChange={(e) => setA({ breed: e.target.value || undefined })} />
</div> </div>
<div> <div>
<Label htmlFor="an-age">Âge</Label> <Label htmlFor="an-age">{t('form.animal.age')}</Label>
<Input id="an-age" value={animal.age ?? ''} onChange={(e) => setA({ age: e.target.value || undefined })} /> <Input id="an-age" value={animal.age ?? ''} onChange={(e) => setA({ age: e.target.value || undefined })} />
</div> </div>
<div> <div>
<Label htmlFor="own-name">Nom du propriétaire *</Label> <Label htmlFor="own-name">{t('form.owner.name')}</Label>
<Input id="own-name" required value={owner.name} onChange={(e) => onChangeOwner({ name: e.target.value })} /> <Input id="own-name" required value={owner.name} onChange={(e) => onChangeOwner({ name: e.target.value })} />
</div> </div>
</fieldset> </fieldset>
+7 -3
View File
@@ -2,6 +2,7 @@ import type { Report } from '@/domain/schema/report'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import Textarea from '@/components/ui/Textarea' import Textarea from '@/components/ui/Textarea'
import NextAppointmentPicker from './NextAppointmentPicker' import NextAppointmentPicker from './NextAppointmentPicker'
import { useT } from '@/i18n/useT'
export interface ConclusionPanelProps { export interface ConclusionPanelProps {
conclusion: string conclusion: string
@@ -20,15 +21,18 @@ export default function ConclusionPanel({
onChangeRecommendations, onChangeRecommendations,
onChangeNextAppointment, onChangeNextAppointment,
}: ConclusionPanelProps) { }: ConclusionPanelProps) {
const t = useT()
return ( return (
<section className="space-y-4"> <section className="space-y-4">
<h2 className="font-serif text-xl text-[var(--color-ink)]">Conclusion & recommandations</h2> <h2 className="font-serif text-xl text-[var(--color-ink)]">
{t('conclusion.section_title')}
</h2>
<div> <div>
<Label htmlFor="conclusion">Conclusion</Label> <Label htmlFor="conclusion">{t('conclusion.conclusion')}</Label>
<Textarea id="conclusion" value={conclusion} onChange={(e) => onChangeConclusion(e.target.value)} /> <Textarea id="conclusion" value={conclusion} onChange={(e) => onChangeConclusion(e.target.value)} />
</div> </div>
<div> <div>
<Label htmlFor="recommendations">Recommandations</Label> <Label htmlFor="recommendations">{t('conclusion.recommendations')}</Label>
<Textarea id="recommendations" value={recommendations} onChange={(e) => onChangeRecommendations(e.target.value)} /> <Textarea id="recommendations" value={recommendations} onChange={(e) => onChangeRecommendations(e.target.value)} />
</div> </div>
<NextAppointmentPicker value={nextAppointment} onChange={onChangeNextAppointment} /> <NextAppointmentPicker value={nextAppointment} onChange={onChangeNextAppointment} />
@@ -1,6 +1,7 @@
import type { Report } from '@/domain/schema/report' import type { Report } from '@/domain/schema/report'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import { useT } from '@/i18n/useT'
export interface NextAppointmentPickerProps { export interface NextAppointmentPickerProps {
value: Report['nextAppointment'] value: Report['nextAppointment']
@@ -11,10 +12,11 @@ export default function NextAppointmentPicker({
value, value,
onChange, onChange,
}: NextAppointmentPickerProps) { }: NextAppointmentPickerProps) {
const t = useT()
const kind = value?.kind const kind = value?.kind
return ( return (
<div className="space-y-2"> <div className="space-y-2">
<Label>Prochain rendez-vous</Label> <Label>{t('conclusion.next_appointment')}</Label>
<div className="flex gap-2 mb-2"> <div className="flex gap-2 mb-2">
<label className="text-sm flex items-center gap-1"> <label className="text-sm flex items-center gap-1">
<input <input
@@ -22,7 +24,7 @@ export default function NextAppointmentPicker({
checked={kind === 'date'} checked={kind === 'date'}
onChange={() => onChange({ kind: 'date', date: '' })} onChange={() => onChange({ kind: 'date', date: '' })}
/> />
Date {t('conclusion.next_kind_date')}
</label> </label>
<label className="text-sm flex items-center gap-1"> <label className="text-sm flex items-center gap-1">
<input <input
@@ -30,7 +32,7 @@ export default function NextAppointmentPicker({
checked={kind === 'period'} checked={kind === 'period'}
onChange={() => onChange({ kind: 'period', text: '' })} onChange={() => onChange({ kind: 'period', text: '' })}
/> />
Période libre {t('conclusion.next_kind_period')}
</label> </label>
<label className="text-sm flex items-center gap-1"> <label className="text-sm flex items-center gap-1">
<input <input
@@ -38,7 +40,7 @@ export default function NextAppointmentPicker({
checked={value === undefined} checked={value === undefined}
onChange={() => onChange(undefined)} onChange={() => onChange(undefined)}
/> />
Aucun {t('conclusion.next_kind_none')}
</label> </label>
</div> </div>
{value?.kind === 'date' && ( {value?.kind === 'date' && (
@@ -51,7 +53,7 @@ export default function NextAppointmentPicker({
{value?.kind === 'period' && ( {value?.kind === 'period' && (
<Input <Input
value={value.text} value={value.text}
placeholder="ex. dans 3 semaines" placeholder={t('conclusion.next_period_placeholder')}
onChange={(e) => onChange({ kind: 'period', text: e.target.value })} onChange={(e) => onChange({ kind: 'period', text: e.target.value })}
/> />
)} )}
+9 -5
View File
@@ -1,6 +1,7 @@
import type { Practitioner } from '@/domain/schema/practitioner' import type { Practitioner } from '@/domain/schema/practitioner'
import Label from '@/components/ui/Label' import Label from '@/components/ui/Label'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import { useT } from '@/i18n/useT'
export interface PractitionerFormProps { export interface PractitionerFormProps {
value: Practitioner value: Practitioner
@@ -8,24 +9,27 @@ export interface PractitionerFormProps {
} }
export default function PractitionerForm({ value, onChange }: PractitionerFormProps) { export default function PractitionerForm({ value, onChange }: PractitionerFormProps) {
const t = useT()
const set = (patch: Partial<Practitioner>) => onChange({ ...value, ...patch }) const set = (patch: Partial<Practitioner>) => onChange({ ...value, ...patch })
return ( return (
<fieldset className="space-y-3"> <fieldset className="space-y-3">
<legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">Praticien</legend> <legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">
{t('form.practitioner.legend')}
</legend>
<div> <div>
<Label htmlFor="prac-name">Nom complet *</Label> <Label htmlFor="prac-name">{t('form.practitioner.name')}</Label>
<Input id="prac-name" required value={value.name} onChange={(e) => set({ name: e.target.value })} /> <Input id="prac-name" required value={value.name} onChange={(e) => set({ name: e.target.value })} />
</div> </div>
<div> <div>
<Label htmlFor="prac-cabinet">Cabinet / clinique</Label> <Label htmlFor="prac-cabinet">{t('form.practitioner.cabinet')}</Label>
<Input id="prac-cabinet" value={value.cabinet ?? ''} onChange={(e) => set({ cabinet: e.target.value || undefined })} /> <Input id="prac-cabinet" value={value.cabinet ?? ''} onChange={(e) => set({ cabinet: e.target.value || undefined })} />
</div> </div>
<div> <div>
<Label htmlFor="prac-contact">Contact (téléphone, email…)</Label> <Label htmlFor="prac-contact">{t('form.practitioner.contact')}</Label>
<Input id="prac-contact" value={value.contact ?? ''} onChange={(e) => set({ contact: e.target.value || undefined })} /> <Input id="prac-contact" value={value.contact ?? ''} onChange={(e) => set({ contact: e.target.value || undefined })} />
</div> </div>
<div> <div>
<Label htmlFor="prac-siret">SIRET</Label> <Label htmlFor="prac-siret">{t('form.practitioner.siret')}</Label>
<Input id="prac-siret" value={value.siret ?? ''} onChange={(e) => set({ siret: e.target.value || undefined })} /> <Input id="prac-siret" value={value.siret ?? ''} onChange={(e) => set({ siret: e.target.value || undefined })} />
</div> </div>
</fieldset> </fieldset>
+12 -6
View File
@@ -1,8 +1,11 @@
import { Link, useNavigate } from 'react-router-dom' import { Link, useNavigate } from 'react-router-dom'
import type { Report } from '@/domain/schema/report' import type { Report } from '@/domain/schema/report'
import Brand from '@/components/brand/Brand' import Brand from '@/components/brand/Brand'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import { formatDateFr } from '@/lib/dates' import { formatDate } from '@/lib/dates'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface ReportHeaderProps { export interface ReportHeaderProps {
report: Report report: Report
@@ -11,6 +14,8 @@ export interface ReportHeaderProps {
export default function ReportHeader({ report, onEditInfos }: ReportHeaderProps) { export default function ReportHeader({ report, onEditInfos }: ReportHeaderProps) {
const navigate = useNavigate() const navigate = useNavigate()
const t = useT()
const locale = useLocaleStore((s) => s.locale)
return ( return (
<header className="flex items-center justify-between gap-4 px-6 py-3 border-b border-[var(--color-border)] bg-[var(--color-surface)]"> <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"> <div className="flex items-center gap-3">
@@ -18,28 +23,29 @@ export default function ReportHeader({ report, onEditInfos }: ReportHeaderProps)
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => navigate('/')} onClick={() => navigate('/')}
aria-label="Retour à l'accueil" aria-label={t('common.back_to_home')}
> >
← Accueil ← {t('common.home')}
</Button> </Button>
<Link <Link
to="/" to="/"
aria-label="Retour à l'accueil" 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)]" 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 /> <Brand />
</Link> </Link>
</div> </div>
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<LanguageSwitcher />
<div className="text-sm text-right text-[var(--color-ink-muted)]"> <div className="text-sm text-right text-[var(--color-ink-muted)]">
<div className="text-[var(--color-ink)] font-medium"> <div className="text-[var(--color-ink)] font-medium">
{report.animal.name} · {report.owner.name} {report.animal.name} · {report.owner.name}
</div> </div>
<div>{formatDateFr(report.date)}</div> <div>{formatDate(report.date, locale)}</div>
</div> </div>
{onEditInfos && ( {onEditInfos && (
<Button variant="secondary" size="sm" onClick={onEditInfos}> <Button variant="secondary" size="sm" onClick={onEditInfos}>
Modifier les infos {t('editor.edit_infos')}
</Button> </Button>
)} )}
</div> </div>
+13 -15
View File
@@ -1,30 +1,28 @@
/** import type { Locale } from '@/i18n/types'
* Returns today's date as an ISO date string (YYYY-MM-DD).
*/
export function todayIso(): string { export function todayIso(): string {
return new Date().toISOString().slice(0, 10) return new Date().toISOString().slice(0, 10)
} }
/** export function nowIso(): string {
* Formats an ISO date string as a French locale date (e.g. "18 mai 2026"). return new Date().toISOString()
*/ }
export function formatDateFr(isoDate: string): string {
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})$/) const match = isoDate.match(/^(\d{4})-(\d{2})-(\d{2})$/)
if (!match) throw new Error(`Invalid ISO date: ${isoDate}`) if (!match) throw new Error(`Invalid ISO date: ${isoDate}`)
const [, y, mo, d] = match const [, y, mo, d] = match
const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d))) 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}`) if (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date: ${isoDate}`)
return new Intl.DateTimeFormat('fr-FR', { return new Intl.DateTimeFormat(LOCALE_TAG[locale], {
day: 'numeric', day: 'numeric',
month: 'long', month: 'long',
year: 'numeric', year: 'numeric',
timeZone: 'UTC', timeZone: 'UTC',
}).format(date) }).format(date)
} }
/**
* Returns the current instant as an ISO timestamp string.
*/
export function nowIso(): string {
return new Date().toISOString()
}
+18 -11
View File
@@ -1,6 +1,8 @@
import { PDFDocument } from 'pdf-lib' import { PDFDocument } from 'pdf-lib'
import type { Report } from '@/domain/schema/report' import type { Report } from '@/domain/schema/report'
import type { SpeciesFindings } from '@/domain/schema/findings' import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { embedFonts } from './fonts' import { embedFonts } from './fonts'
import { addObservationPage } from './render/observationPage' import { addObservationPage } from './render/observationPage'
import { addConclusionPage } from './render/conclusionPage' import { addConclusionPage } from './render/conclusionPage'
@@ -10,6 +12,10 @@ import { loadSvg } from '@/anatomy/svgLoader'
import { parseSvgBones } from '@/anatomy/svgConvention' import { parseSvgBones } from '@/anatomy/svgConvention'
import { getSpecies } from '@/domain/species/registry' import { getSpecies } from '@/domain/species/registry'
export interface PdfExportOptions {
locale: Locale
}
/** /**
* Builds a `data-anno-id → French label` map by parsing every SVG the * Builds a `data-anno-id → French label` map by parsing every SVG the
* species manifest knows about. Each SVG is loaded independently so a * species manifest knows about. Each SVG is loaded independently so a
@@ -36,9 +42,6 @@ export async function buildZoneLabels(report: Report): Promise<Map<string, strin
if (b.fr) labels.set(id, b.fr) if (b.fr) labels.set(id, b.fr)
}) })
} catch (err) { } catch (err) {
// Asset unavailable (404 / fetch failure / parse error). Log and
// continue — observers downstream fall back to the raw bone id,
// which is preferable to crashing the whole export.
console.warn(`buildZoneLabels: skipped ${src}`, err) console.warn(`buildZoneLabels: skipped ${src}`, err)
} }
}), }),
@@ -50,9 +53,7 @@ export async function buildZoneLabels(report: Report): Promise<Map<string, strin
/** /**
* Loads the parsed findings catalog for a species so the PDF renderer * Loads the parsed findings catalog for a species so the PDF renderer
* can resolve a Finding's `zoneId` (JSON catalog key) back to its * can resolve a Finding's `zoneId` (JSON catalog key) back to its
* human-readable zone name. Returns null if the species lacks a * human-readable zone name.
* catalog or the lazy import fails — the PDF still renders, but
* per-zone groups fall back to the raw zoneId.
*/ */
async function loadSpeciesFindings( async function loadSpeciesFindings(
speciesId: string, speciesId: string,
@@ -68,11 +69,16 @@ async function loadSpeciesFindings(
} }
} }
export async function exportReportToPdf(report: Report): Promise<Uint8Array> { export async function exportReportToPdf(
report: Report,
opts: PdfExportOptions,
): Promise<Uint8Array> {
const { locale } = opts
const dict = getDict(locale)
const pdfDoc = await PDFDocument.create() const pdfDoc = await PDFDocument.create()
pdfDoc.setTitle(`Bilan ostéo — ${report.animal.name}`) pdfDoc.setTitle(`${dict['pdf.title.suffix.bilan']}${report.animal.name}`)
pdfDoc.setAuthor(report.practitioner.name) pdfDoc.setAuthor(report.practitioner.name)
pdfDoc.setSubject("Bilan d'ostéopathie animalière") pdfDoc.setSubject(dict['pdf.subject'])
pdfDoc.setCreationDate(new Date()) pdfDoc.setCreationDate(new Date())
pdfDoc.setModificationDate(new Date()) pdfDoc.setModificationDate(new Date())
@@ -89,12 +95,13 @@ export async function exportReportToPdf(report: Report): Promise<Uint8Array> {
fonts, fonts,
zoneLabels, zoneLabels,
findingsTree, findingsTree,
locale,
) )
} }
await addConclusionPage(pdfDoc, report, fonts) await addConclusionPage(pdfDoc, report, fonts, locale)
const pages = pdfDoc.getPages() const pages = pdfDoc.getPages()
pages.forEach((page, idx) => drawFooter(page, fonts, idx + 1, pages.length)) pages.forEach((page, idx) => drawFooter(page, fonts, idx + 1, pages.length, locale))
await attachReportJson(pdfDoc, report) await attachReportJson(pdfDoc, report)
return pdfDoc.save() return pdfDoc.save()
+13 -9
View File
@@ -1,8 +1,10 @@
import { rgb, PageSizes, type PDFDocument, type PDFFont } from 'pdf-lib' import { rgb, PageSizes, type PDFDocument, type PDFFont } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts' import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report' import type { Report } from '@/domain/schema/report'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { drawHeader } from './header' import { drawHeader } from './header'
import { formatDateFr } from '@/lib/dates' import { formatDate } from '@/lib/dates'
const MARGIN_X = 36 const MARGIN_X = 36
const EYEBROW_Y_OFFSET = 95 const EYEBROW_Y_OFFSET = 95
@@ -39,23 +41,25 @@ export async function addConclusionPage(
pdfDoc: PDFDocument, pdfDoc: PDFDocument,
report: Report, report: Report,
fonts: EmbeddedFonts, fonts: EmbeddedFonts,
locale: Locale,
): Promise<void> { ): Promise<void> {
const dict = getDict(locale)
const page = pdfDoc.addPage(PageSizes.A4) const page = pdfDoc.addPage(PageSizes.A4)
const { width, height } = page.getSize() const { width, height } = page.getSize()
const max = width - MARGIN_X * 2 const max = width - MARGIN_X * 2
drawHeader(page, report, fonts) drawHeader(page, report, fonts, locale)
const eyebrowY = height - EYEBROW_Y_OFFSET const eyebrowY = height - EYEBROW_Y_OFFSET
const titleY = height - TITLE_Y_OFFSET const titleY = height - TITLE_Y_OFFSET
page.drawText('SYNTHÈSE', { page.drawText(dict['pdf.eyebrow.synthesis'], {
x: MARGIN_X, x: MARGIN_X,
y: eyebrowY, y: eyebrowY,
size: 9, size: 9,
font: fonts.bodyBold, font: fonts.bodyBold,
color: COLOR_ACCENT, color: COLOR_ACCENT,
}) })
page.drawText('Conclusion', { page.drawText(dict['pdf.title.conclusion'], {
x: MARGIN_X, x: MARGIN_X,
y: titleY, y: titleY,
size: 22, size: 22,
@@ -72,17 +76,17 @@ export async function addConclusionPage(
let cursorY = titleY - SECTION_TOP_GAP let cursorY = titleY - SECTION_TOP_GAP
const sections: Array<{ label: string; body: string; color?: typeof COLOR_INK }> = [ const sections: Array<{ label: string; body: string; color?: typeof COLOR_INK }> = [
{ label: 'CONCLUSION', body: report.conclusion || '—' }, { label: dict['pdf.section.conclusion'], body: report.conclusion || dict['pdf.empty'] },
{ label: 'RECOMMANDATIONS', body: report.recommendations || '—' }, { label: dict['pdf.section.recommendations'], body: report.recommendations || dict['pdf.empty'] },
] ]
if (report.nextAppointment) { if (report.nextAppointment) {
const txt = const txt =
report.nextAppointment.kind === 'date' report.nextAppointment.kind === 'date'
? formatDateFr(report.nextAppointment.date) ? formatDate(report.nextAppointment.date, locale)
: report.nextAppointment.text : report.nextAppointment.text
sections.push({ sections.push({
label: 'PROCHAIN RENDEZ-VOUS', label: dict['pdf.section.next_appointment'],
body: txt || '—', body: txt || dict['pdf.empty'],
color: COLOR_MUTED, color: COLOR_MUTED,
}) })
} }
+6 -2
View File
@@ -1,7 +1,9 @@
import { rgb, type PDFPage } from 'pdf-lib' import { rgb, type PDFPage } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts' import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Locale } from '@/i18n/types'
import { appConfig } from '@/config/env' import { appConfig } from '@/config/env'
import { formatDateFr, todayIso } from '@/lib/dates' import { formatDate, todayIso } from '@/lib/dates'
import { getDict } from '@/i18n'
const MARGIN_X = 36 const MARGIN_X = 36
const FOOTER_Y = 28 const FOOTER_Y = 28
@@ -11,11 +13,13 @@ export function drawFooter(
fonts: EmbeddedFonts, fonts: EmbeddedFonts,
pageNumber: number, pageNumber: number,
totalPages: number, totalPages: number,
locale: Locale,
): void { ): void {
const dict = getDict(locale)
const { width } = page.getSize() const { width } = page.getSize()
const muted = rgb(0.42, 0.39, 0.35) const muted = rgb(0.42, 0.39, 0.35)
const left = appConfig.footerName const left = appConfig.footerName
const center = `Exporté le ${formatDateFr(todayIso())}` const center = `${dict['pdf.export_date_prefix']}${formatDate(todayIso(), locale)}`
const right = `${pageNumber} / ${totalPages}` const right = `${pageNumber} / ${totalPages}`
page.drawText(left, { x: MARGIN_X, y: FOOTER_Y, size: 9, font: fonts.bodyRegular, color: muted }) page.drawText(left, { x: MARGIN_X, y: FOOTER_Y, size: 9, font: fonts.bodyRegular, color: muted })
+18 -6
View File
@@ -1,12 +1,20 @@
import { rgb, type PDFPage } from 'pdf-lib' import { rgb, type PDFPage } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts' import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report' import type { Report } from '@/domain/schema/report'
import { formatDateFr } from '@/lib/dates' import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { formatDate } from '@/lib/dates'
const MARGIN_X = 36 const MARGIN_X = 36
const TOP_Y = 800 const TOP_Y = 800
export function drawHeader(page: PDFPage, report: Report, fonts: EmbeddedFonts): void { export function drawHeader(
page: PDFPage,
report: Report,
fonts: EmbeddedFonts,
locale: Locale,
): void {
const dict = getDict(locale)
const { width } = page.getSize() const { width } = page.getSize()
const ink = rgb(0.12, 0.11, 0.09) const ink = rgb(0.12, 0.11, 0.09)
const muted = rgb(0.42, 0.39, 0.35) const muted = rgb(0.42, 0.39, 0.35)
@@ -15,7 +23,9 @@ export function drawHeader(page: PDFPage, report: Report, fonts: EmbeddedFonts):
report.practitioner.name, report.practitioner.name,
report.practitioner.cabinet, report.practitioner.cabinet,
report.practitioner.contact, report.practitioner.contact,
report.practitioner.siret ? `SIRET ${report.practitioner.siret}` : undefined, report.practitioner.siret
? `${dict['pdf.siret_prefix']}${report.practitioner.siret}`
: undefined,
].filter(Boolean) as string[] ].filter(Boolean) as string[]
const y = TOP_Y const y = TOP_Y
@@ -33,12 +43,14 @@ export function drawHeader(page: PDFPage, report: Report, fonts: EmbeddedFonts):
report.animal.name, report.animal.name,
report.animal.breed ? `(${report.animal.breed})` : '', report.animal.breed ? `(${report.animal.breed})` : '',
report.animal.age ? `· ${report.animal.age}` : '', report.animal.age ? `· ${report.animal.age}` : '',
].filter(Boolean).join(' ') ]
.filter(Boolean)
.join(' ')
const right = [ const right = [
animalLine, animalLine,
`Propriétaire : ${report.owner.name}`, `${dict['pdf.owner_prefix']}${report.owner.name}`,
formatDateFr(report.date), formatDate(report.date, locale),
] ]
right.forEach((line, i) => { right.forEach((line, i) => {
const size = i === 0 ? 11 : 9 const size = i === 0 ? 11 : 9
+26 -14
View File
@@ -3,6 +3,8 @@ import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report' import type { Report } from '@/domain/schema/report'
import type { Finding, Observation } from '@/domain/schema/observation' import type { Finding, Observation } from '@/domain/schema/observation'
import type { SpeciesFindings } from '@/domain/schema/findings' import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Locale } from '@/i18n/types'
import { getDict } from '@/i18n'
import { drawHeader } from './header' import { drawHeader } from './header'
import { rasterizeSvg } from './svgToPng' import { rasterizeSvg } from './svgToPng'
import { loadSvg } from '@/anatomy/svgLoader' import { loadSvg } from '@/anatomy/svgLoader'
@@ -271,15 +273,17 @@ export async function addObservationPage(
fonts: EmbeddedFonts, fonts: EmbeddedFonts,
zoneLabels: Map<string, string>, zoneLabels: Map<string, string>,
findingsTree: SpeciesFindings | null, findingsTree: SpeciesFindings | null,
locale: Locale,
): Promise<void> { ): Promise<void> {
const dict = getDict(locale)
const page = pdfDoc.addPage(PageSizes.A4) const page = pdfDoc.addPage(PageSizes.A4)
const { width, height } = page.getSize() const { width, height } = page.getSize()
drawHeader(page, report, fonts) drawHeader(page, report, fonts, locale)
const eyebrowY = height - EYEBROW_Y_OFFSET const eyebrowY = height - EYEBROW_Y_OFFSET
const titleY = height - TITLE_Y_OFFSET const titleY = height - TITLE_Y_OFFSET
const obsLabel = String(obsIndex + 1).padStart(2, '0') const obsLabel = String(obsIndex + 1).padStart(2, '0')
page.drawText('OBSERVATION', { page.drawText(dict['pdf.eyebrow.observation'], {
x: MARGIN_X, x: MARGIN_X,
y: eyebrowY, y: eyebrowY,
size: 9, size: 9,
@@ -296,7 +300,8 @@ export async function addObservationPage(
if (observation.severity) { if (observation.severity) {
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22) const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
const sev = observation.severity const sev = observation.severity
const sevText = sev.toUpperCase() const sevLabel = dict[`severity.${sev}`] ?? sev
const sevText = sevLabel.toUpperCase()
const sevSize = 9 const sevSize = 9
const sevTextW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize) const sevTextW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize)
const padX = 8 const padX = 8
@@ -337,13 +342,13 @@ export async function addObservationPage(
const items: Array<{ label: string; src: string; sourceId: string | undefined }> = [] const items: Array<{ label: string; src: string; sourceId: string | undefined }> = []
if (hasMainZones) { if (hasMainZones) {
items.push({ label: 'VUE GÉNÉRALE', src: species.mainSvg, sourceId: undefined }) items.push({ label: dict['pdf.view.general'], src: species.mainSvg, sourceId: undefined })
} }
for (const detailId of detailIds) { for (const detailId of detailIds) {
const detailPath = species.details[detailId] const detailPath = species.details[detailId]
if (!detailPath) continue if (!detailPath) continue
items.push({ items.push({
label: `VUE DÉTAIL — ${detailId.toUpperCase()}`, label: `${dict['pdf.view.detail_prefix']}${detailId.toUpperCase()}`,
src: detailPath, src: detailPath,
sourceId: detailId, sourceId: detailId,
}) })
@@ -370,7 +375,7 @@ export async function addObservationPage(
.join(' · ') .join(' · ')
const sections: Array<{ label: string; value: string }> = [ const sections: Array<{ label: string; value: string }> = [
{ label: 'ZONES', value: zonesText || '—' }, { label: dict['pdf.section.zones'], value: zonesText || dict['pdf.empty'] },
] ]
// Group catalog findings by their JSON zoneId so each zone gets its // Group catalog findings by their JSON zoneId so each zone gets its
// own labelled section. Preserves first-seen order so the on-screen // own labelled section. Preserves first-seen order so the on-screen
@@ -386,29 +391,36 @@ export async function addObservationPage(
} }
for (const [zoneId, group] of findingsByZone) { for (const [zoneId, group] of findingsByZone) {
const zoneName = findingsTree?.zones[zoneId]?.name_fr ?? zoneId const zoneTree = findingsTree?.zones[zoneId]
const zoneName = zoneTree
? locale === 'en'
? zoneTree.name_en
: zoneTree.name_fr
: zoneId
const value = group const value = group
.map((f) => .map((f) => {
f.requiresVetReferral ? `⚠ ${f.labelFrSnapshot}` : f.labelFrSnapshot, const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
) return f.requiresVetReferral ? `⚠ ${lbl}` : lbl
})
.join(' · ') .join(' · ')
sections.push({ sections.push({
label: `CONSTATS — ${zoneName.toUpperCase()}`, label: `${dict['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
value, value,
}) })
} }
if (observation.freeTextFindings.length) { if (observation.freeTextFindings.length) {
sections.push({ sections.push({
label: 'CONSTATS LIBRES', label: dict['pdf.section.free_findings'],
value: observation.freeTextFindings.join(' · '), value: observation.freeTextFindings.join(' · '),
}) })
} }
if (observation.severity) { if (observation.severity) {
sections.push({ label: 'SÉVÉRITÉ', value: observation.severity }) const sevLabel = dict[`severity.${observation.severity}`] ?? observation.severity
sections.push({ label: dict['pdf.section.severity'], value: sevLabel })
} }
if (observation.comment.trim()) { if (observation.comment.trim()) {
sections.push({ label: 'COMMENTAIRE', value: observation.comment.trim() }) sections.push({ label: dict['pdf.section.comment'], value: observation.comment.trim() })
} }
const maxTextW = width - MARGIN_X * 2 const maxTextW = width - MARGIN_X * 2
@@ -0,0 +1,24 @@
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')
})
})
+20 -8
View File
@@ -1,17 +1,29 @@
import { describe, it, expect } from 'vitest' import { describe, it, expect } from 'vitest'
import { formatDateFr, todayIso, nowIso } from '@/lib/dates' import { formatDate, todayIso, nowIso } from '@/lib/dates'
describe('formatDateFr', () => { describe('formatDate fr', () => {
it('formats an ISO date as "18 mai 2026"', () => { it('formats "2026-05-18" as "18 mai 2026"', () => {
expect(formatDateFr('2026-05-18')).toBe('18 mai 2026') expect(formatDate('2026-05-18', 'fr')).toBe('18 mai 2026')
}) })
it('formats a leading-zero day correctly', () => { it('drops leading zero on the day', () => {
expect(formatDateFr('2026-01-03')).toBe('3 janvier 2026') 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('throws on invalid input', () => { it('drops leading zero on the day', () => {
expect(() => formatDateFr('not-a-date')).toThrow() 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()
}) })
}) })
+1 -1
View File
@@ -26,7 +26,7 @@ describe('PDF roundtrip', () => {
}) })
it('roundtrips a minimal report (no observations)', async () => { it('roundtrips a minimal report (no observations)', async () => {
const bytes = await exportReportToPdf(report) const bytes = await exportReportToPdf(report, { locale: 'fr' })
const imported = await importReportFromPdf(bytes) const imported = await importReportFromPdf(bytes)
expect(imported.animal.name).toBe('Mistral') expect(imported.animal.name).toBe('Mistral')
expect(imported.version).toBe(2) expect(imported.version).toBe(2)