Files
faunosteo/src/components/observation/ObservationCard.tsx
T
Bastien ChanotandClaude Opus 4.7 9cf8a66dad feat(i18n): navigator-detect default locale + locale-aware bone labels
- localeStore.readInitial now consults navigator.language(s) when
  localStorage is empty (first fr/en hit, FR fallback). Persisted user
  choice still wins.
- New helper src/anatomy/labels.ts (boneLabel(b, locale, fallback))
  with cross-language fallback so missing labels never render blank.
- AnatomyCanvas rewrites native SVG <title> tooltips per locale on
  mount and on locale change (upstream SVG ships titles as "FR / EN"
  concat; we replace with the active-locale label only). Detail-popup
  trigger titles ("🔍 Zoom: …") left intact.
- DetailModal + EditorRoute detail title prefix + vertebra picker
  title now route through useT()/boneLabel.
- ObservationCard.describeZone takes locale, picks bone.fr / bone.en.
- PDF: buildZoneLabels returns Map<id, { fr, en }> instead of FR-only;
  observationPage picks per locale with cross-language fallback.
- Tests: FindingsTreePicker + VertebraPicker reset locale to 'fr' in
  beforeEach (navigator-detect may land on EN in happy-dom).
- pdf.zoneLabels test updated to assert the new pair shape.

154/154 tests pass, lint clean, typecheck clean, build OK.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 07:56:22 +02:00

403 lines
15 KiB
TypeScript

import { useMemo, useState } from 'react'
import type {
Observation,
ObservationZone,
Vertebra,
} from '@/domain/schema/observation'
import type {
SpeciesFindings,
ZoneFindings,
} from '@/domain/schema/findings'
import type { Bone } from '@/anatomy/types'
import { matchZoneFindings } from '@/lib/zoneMatch'
import { AnimatePresence, motion } from 'motion/react'
import Card from '@/components/ui/Card'
import Badge from '@/components/ui/Badge'
import Button from '@/components/ui/Button'
import Label from '@/components/ui/Label'
import Textarea from '@/components/ui/Textarea'
import FindingsTreePicker from './FindingsTreePicker'
import FreeTextFindingInput from './FreeTextFindingInput'
import SeveritySelector from './SeveritySelector'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { boneLabel } from '@/anatomy/labels'
import type { Locale } from '@/i18n/types'
export interface ObservationCardProps {
observation: Observation
index: number
expanded: boolean
onToggle: () => void
onDelete: () => void
onMoveUp: () => void
onMoveDown: () => void
canMoveUp: boolean
canMoveDown: boolean
// Editor body props (used only when expanded)
bones: Map<string, Bone>
findings: SpeciesFindings | null
onChange: (next: Observation) => void
onOpenVertebraPicker: (zoneIndex: number) => void
onRemoveZone: (zoneIndex: number) => void
}
function describeZone(
z: ObservationZone,
bones: Map<string, Bone>,
locale: Locale,
): string {
const label = boneLabel(bones.get(z.boneId), locale, z.boneId)
if (z.vertebrae?.length) {
const vs = z.vertebrae
.map((v: Vertebra) => `${v.region}${v.index}`)
.join(', ')
return `${label} (${vs})`
}
return label
}
export default function ObservationCard({
observation,
index,
expanded,
onToggle,
onDelete,
onMoveUp,
onMoveDown,
canMoveUp,
canMoveDown,
bones,
findings,
onChange,
onOpenVertebraPicker,
onRemoveZone,
}: 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,
// matching the observation-card accordion semantics. Closed by default
// so the card stays compact when first expanded.
const [expandedZoneId, setExpandedZoneId] = useState<string | null>(null)
const zoneCount = observation.zones.length
const findingCount =
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>) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
onToggle()
}
}
function stop(fn: () => void) {
return (event: React.MouseEvent) => {
event.stopPropagation()
fn()
}
}
const zonesArray = useMemo(
() => (findings ? Object.values(findings.zones) : []),
[findings],
)
const zonesWithTree = useMemo(() => {
if (zonesArray.length === 0) return [] as { tree: ZoneFindings }[]
const seen = new Set<string>()
const out: { tree: ZoneFindings }[] = []
for (const z of observation.zones) {
const bone = bones.get(z.boneId)
if (!bone) continue
const tree = matchZoneFindings(
{ fr: bone.fr, en: bone.en },
zonesArray,
)
if (!tree) continue
if (seen.has(tree.id)) continue
seen.add(tree.id)
out.push({ tree })
}
return out
}, [observation.zones, bones, zonesArray])
return (
<Card
className={[
'transition',
expanded
? 'ring-2 ring-[var(--color-accent)]'
: 'hover:bg-[var(--color-surface-strong)]',
].join(' ')}
>
<div
role="button"
tabIndex={0}
aria-expanded={expanded}
aria-label={`${expanded ? t('observation.collapse_aria') : t('observation.expand_aria')} ${index + 1}`}
onClick={onToggle}
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"
>
<div className="flex-1 min-h-[60px] text-left">
<div className="flex items-center gap-2 mb-2">
<Badge tone="neutral">{t('observation.badge_n')}{index + 1}</Badge>
{observation.severity && (
<Badge
tone={
observation.severity === 'sévère'
? 'danger'
: observation.severity === 'modérée'
? 'warn'
: 'neutral'
}
>
{t(`severity.${observation.severity}`)}
</Badge>
)}
</div>
<div className="text-sm text-[var(--color-ink-muted)]">
{zoneCount} {zoneCountLabel} · {findingCount} {findingCountLabel}
</div>
{!expanded && observation.comment && (
<p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]">
{observation.comment}
</p>
)}
</div>
<div
className="flex items-start gap-1"
onClick={(event) => event.stopPropagation()}
>
<Button
size="sm"
variant="ghost"
disabled={!canMoveUp}
onClick={stop(onMoveUp)}
aria-label={t('common.move_up')}
>
↑
</Button>
<Button
size="sm"
variant="ghost"
disabled={!canMoveDown}
onClick={stop(onMoveDown)}
aria-label={t('common.move_down')}
>
↓
</Button>
<Button
size="sm"
variant="ghost"
onClick={stop(onDelete)}
aria-label={t('common.delete')}
>
🗑
</Button>
<Button
size="sm"
variant="ghost"
onClick={stop(onToggle)}
aria-label={expanded ? t('common.collapse') : t('common.expand')}
>
{expanded ? '▲' : '▼'}
</Button>
</div>
</div>
<AnimatePresence initial={false}>
{expanded && (
<motion.div
key="body"
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.18, ease: 'easeOut' }}
className="overflow-hidden"
>
<div className="px-4 pb-4 pt-2 border-t border-[var(--color-border)] space-y-6">
<section>
<Label>{t('observation.zones_label')}</Label>
{observation.zones.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('observation.zones_empty')}
</p>
) : (
<ul className="flex flex-wrap gap-2">
{observation.zones.map((z, i) => {
const b = bones.get(z.boneId)
const supportsVertebrae =
b?.special === 'vertebral-precision'
return (
<li key={`${z.boneId}-${i}`}>
<Badge tone="accent" className="gap-2">
{describeZone(z, bones, locale)}
{supportsVertebrae && (
<button
type="button"
onClick={() => onOpenVertebraPicker(i)}
className="underline text-xs text-[var(--color-accent-strong)]"
title={t('observation.vertebrae_button_title')}
>
{t('observation.vertebrae_button')}
</button>
)}
<button
type="button"
aria-label={`${t('observation.remove_zone')} ${boneLabel(b, locale, z.boneId)}`}
onClick={() => onRemoveZone(i)}
className="ml-1 text-[var(--color-accent-strong)]"
>
✕
</button>
</Badge>
</li>
)
})}
</ul>
)}
</section>
<section>
<Label>{t('observation.findings_catalog_label')}</Label>
{zonesWithTree.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
{observation.zones.length === 0
? t('observation.findings_pick_zone_first')
: t('observation.findings_no_catalog')}
</p>
) : (
<ul className="space-y-2">
{zonesWithTree.map(({ tree }) => {
const expanded = expandedZoneId === tree.id
const selectedCount = observation.findings.filter(
(f) => f.zoneId === tree.id,
).length
const selectedAria = `${selectedCount} ${
selectedCount > 1
? t('findings.selected_plural')
: t('findings.selected_singular')
}`
return (
<li
key={tree.id}
className={[
'rounded-xl border bg-[var(--color-surface)] transition',
expanded
? 'border-[var(--color-accent)] ring-1 ring-[var(--color-accent)]'
: 'border-[var(--color-border)]',
].join(' ')}
>
<button
type="button"
onClick={() =>
setExpandedZoneId(expanded ? null : tree.id)
}
aria-expanded={expanded}
aria-controls={`findings-zone-${tree.id}`}
className="w-full flex items-center justify-between gap-2 px-3 py-2 text-left rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40"
>
<span className="flex items-center gap-2">
<span className="text-sm font-medium text-[var(--color-ink)]">
{nameOf(tree)}
</span>
{selectedCount > 0 && (
<span
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"
>
{selectedCount}
</span>
)}
</span>
<span
aria-hidden="true"
className="text-[var(--color-ink-muted)]"
>
{expanded ? '▲' : '▼'}
</span>
</button>
<AnimatePresence initial={false}>
{expanded && (
<motion.div
key="picker-body"
id={`findings-zone-${tree.id}`}
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.18, ease: 'easeOut' }}
className="overflow-hidden"
>
<div className="px-3 pb-3 pt-1 border-t border-[var(--color-border)]">
<FindingsTreePicker
zoneId={tree.id}
tree={tree}
selected={observation.findings}
onChange={(next) =>
onChange({ ...observation, findings: next })
}
/>
</div>
</motion.div>
)}
</AnimatePresence>
</li>
)
})}
</ul>
)}
</section>
<section>
<Label>{t('observation.findings_free_label')}</Label>
<FreeTextFindingInput
items={observation.freeTextFindings}
onChange={(items) =>
onChange({ ...observation, freeTextFindings: items })
}
/>
</section>
<section>
<Label>{t('observation.severity_label')}</Label>
<SeveritySelector
value={observation.severity}
onChange={(s) => onChange({ ...observation, severity: s })}
/>
</section>
<section>
<Label htmlFor={`obs-comment-${observation.id}`}>
{t('observation.comment_label')}
</Label>
<Textarea
id={`obs-comment-${observation.id}`}
value={observation.comment}
onChange={(e) =>
onChange({ ...observation, comment: e.target.value })
}
placeholder={t('observation.comment_placeholder')}
/>
</section>
</div>
</motion.div>
)}
</AnimatePresence>
</Card>
)
}