feat(app): application on the canonical sheet — report v3 store with v2 draft migration, bundled SheetProvider (SHEET_BUNDLE), annotation layer rendered from the document, zone interaction service, pickers and cards on the sheet index, PDF v3 export with v2 archive import; legacy registry, matchers, editors and assets removed

This commit is contained in:
bchanot committed 2026-10-10 11:36:14 +02:00
1 parent 0a17e390cf
commit ce2ec26112
114 files changed
+3560 -14637

No files matched your search

@@ -1,75 +1,84 @@
import { useMemo, useState } from 'react'
import { motion } from 'motion/react'
import type {
Finding,
FindingCategory,
FindingNode,
ZoneFindings,
} from '@/domain/schema/findings'
import type { Finding, LateralSide } from '@/domain/schema/observation'
FindingZone,
LateralSide,
LocalizedOptionalText,
} from '@faunosteo/domain'
import Button from '@/components/ui/Button'
import { pickLabel } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
const levelVariants = {
enter: (dir: 1 | -1) => ({ opacity: 0, x: dir * 32 }),
center: { opacity: 1, x: 0 },
}
type TreeNode = FindingCategory | FindingNode
export interface FindingsTreePickerProps {
zoneId: string
tree: ZoneFindings
zone: FindingZone
side?: LateralSide
selected: Finding[]
onChange: (next: Finding[]) => void
}
function isLeaf(node: FindingNode): boolean {
return !node.children || node.children.length === 0
function isLeaf(node: TreeNode): boolean {
return node.children.length === 0
}
function samePath(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) return false
}
return true
function samePath(a: readonly string[], b: readonly string[]): boolean {
return a.length === b.length && a.every((seg, i) => seg === b[i])
}
function pathStartsWith(full: string[], prefix: string[]): boolean {
if (full.length < prefix.length) return false
for (let i = 0; i < prefix.length; i += 1) {
if (full[i] !== prefix[i]) return false
}
return true
function pathStartsWith(
full: readonly string[],
prefix: readonly string[],
): boolean {
return (
full.length >= prefix.length && prefix.every((seg, i) => full[i] === seg)
)
}
function findNode(
categories: FindingNode[],
path: string[],
): FindingNode | undefined {
let nodes: FindingNode[] = categories
let node: FindingNode | undefined
categories: readonly FindingCategory[],
path: readonly string[],
): TreeNode | undefined {
let nodes: readonly TreeNode[] = categories
let node: TreeNode | undefined
for (const segment of path) {
node = nodes.find((n) => n.id === segment)
if (!node) return undefined
nodes = node.children ?? []
nodes = node.children
}
return node
}
function descriptionOf(node: TreeNode, locale: Locale): string | undefined {
const text: LocalizedOptionalText | undefined = node.description
if (!text) return undefined
return (
(locale === 'en' ? text.en || text.fr : text.fr || text.en) || undefined
)
}
/**
* Drill-down picker over one finding zone of the sheet. A finding is keyed
* by `(findingZoneId, path, side)`; labels are snapshotted at selection.
*/
export default function FindingsTreePicker({
zoneId,
tree,
zone,
side,
selected,
onChange,
}: 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 [direction, setDirection] = useState<1 | -1>(1)
@@ -86,74 +95,57 @@ export default function FindingsTreePicker({
setPath(path.slice(0, depth))
}
const currentNodes = useMemo<FindingNode[]>(() => {
if (path.length === 0) return tree.categories
const node = findNode(tree.categories, path)
return node?.children ?? []
}, [tree, path])
const currentNodes = useMemo<readonly TreeNode[]>(() => {
if (path.length === 0) return zone.categories
return findNode(zone.categories, path)?.children ?? []
}, [zone, path])
const focusedNode = useMemo(
() => (path.length === 0 ? undefined : findNode(tree.categories, path)),
[tree, path],
() => (path.length === 0 ? undefined : findNode(zone.categories, path)),
[zone, path],
)
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 }[] = [
{ label: pick(tree), depth: 0 },
]
let nodes: FindingNode[] = tree.categories
const crumbs = [{ label: pickLabel(zone.name, locale), depth: 0 }]
let nodes: readonly TreeNode[] = zone.categories
path.forEach((seg, i) => {
const n = nodes.find((x) => x.id === seg)
if (n) {
crumbs.push({ label: pick(n), depth: i + 1 })
nodes = n.children ?? []
crumbs.push({ label: pickLabel(n.name, locale), depth: i + 1 })
nodes = n.children
}
})
return crumbs
}, [tree, path, locale])
}, [zone, path, locale])
function matchesSide(f: Finding): boolean {
return f.zoneId === zoneId && f.side === side
}
const matches = (f: Finding) => f.findingZoneId === zone.id && f.side === side
const isLeafSelected = (leafPath: string[]) =>
selected.some((f) => matches(f) && samePath(f.path, leafPath))
const countSelectedUnder = (nodePath: string[]) =>
selected.filter((f) => matches(f) && pathStartsWith(f.path, nodePath))
.length
function isLeafSelected(leafPath: string[]): boolean {
return selected.some(
(f) => matchesSide(f) && samePath(f.path, leafPath),
)
}
function countSelectedUnder(nodePath: string[]): number {
let n = 0
for (const f of selected) {
if (!matchesSide(f)) continue
if (!pathStartsWith(f.path, nodePath)) continue
n += 1
}
return n
}
function toggleLeaf(leafPath: string[], leaf: FindingNode) {
function toggleLeaf(leafPath: string[], leaf: TreeNode) {
if (isLeafSelected(leafPath)) {
onChange(
selected.filter(
(f) => !(matchesSide(f) && samePath(f.path, leafPath)),
),
selected.filter((f) => !(matches(f) && samePath(f.path, leafPath))),
)
return
}
const next: Finding = {
zoneId,
findingZoneId: zone.id,
path: leafPath,
labelFrSnapshot: leaf.name_fr,
labelEnSnapshot: leaf.name_en,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en,
}
if (leaf.requires_vet_referral) next.requiresVetReferral = true
if ('requires_vet_referral' in leaf && leaf.requires_vet_referral)
next.requiresVetReferral = true
if (side) next.side = side
onChange([...selected, next])
}
const focusedDescription = focusedNode && descriptionOf(focusedNode, locale)
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-1 text-xs text-[var(--color-ink-muted)]">
@@ -179,9 +171,9 @@ export default function FindingsTreePicker({
})}
</div>
{focusedNode && descOf(focusedNode) && (
{focusedDescription && (
<p className="text-xs italic text-[var(--color-ink-muted)]">
{descOf(focusedNode)}
{focusedDescription}
</p>
)}
@@ -196,16 +188,16 @@ export default function FindingsTreePicker({
</Button>
)}
<motion.ul
key={path.join('/') || '__root__'}
custom={direction}
variants={levelVariants}
initial="enter"
animate="center"
transition={{ duration: 0.22, ease: 'easeOut' }}
style={{ willChange: 'transform, opacity' }}
className="space-y-1.5 max-h-64 overflow-auto pr-1"
>
<motion.ul
key={path.join('/') || '__root__'}
custom={direction}
variants={levelVariants}
initial="enter"
animate="center"
transition={{ duration: 0.22, ease: 'easeOut' }}
style={{ willChange: 'transform, opacity' }}
className="space-y-1.5 max-h-64 overflow-auto pr-1"
>
{currentNodes.length === 0 ? (
<li className="text-sm text-[var(--color-ink-muted)]">
{t('findings.no_options')}
@@ -213,16 +205,17 @@ export default function FindingsTreePicker({
) : (
currentNodes.map((node) => {
const nodePath = [...path, node.id]
const nodeLabel = pickLabel(node.name, locale)
const nodeDesc = descriptionOf(node, locale)
if (isLeaf(node)) {
const checked = isLeafSelected(nodePath)
const nodeLabel = nameOf(node)
const nodeDesc = descOf(node)
const vet =
'requires_vet_referral' in node && node.requires_vet_referral
return (
<li key={node.id}>
<label className="flex items-start gap-2 cursor-pointer">
<input
type="checkbox"
checked={checked}
checked={isLeafSelected(nodePath)}
onChange={() => toggleLeaf(nodePath, node)}
className="mt-1 accent-[var(--color-accent)]"
aria-label={nodeLabel}
@@ -232,7 +225,7 @@ export default function FindingsTreePicker({
<span className="text-sm font-medium text-[var(--color-ink)]">
{nodeLabel}
</span>
{node.requires_vet_referral && (
{vet && (
<span
title={t('findings.vet_referral')}
aria-label={t('findings.vet_referral')}
@@ -253,7 +246,6 @@ export default function FindingsTreePicker({
)
}
const selectedCount = countSelectedUnder(nodePath)
const nodeLabel = nameOf(node)
const selectedAria = `${selectedCount} ${
selectedCount > 1
? t('findings.selected_plural')
@@ -278,7 +270,10 @@ export default function FindingsTreePicker({
</span>
)}
</span>
<span aria-hidden="true" className="text-[var(--color-ink-muted)]">
<span
aria-hidden="true"
className="text-[var(--color-ink-muted)]"
>
›
</span>
</button>
@@ -286,7 +281,7 @@ export default function FindingsTreePicker({
)
})
)}
</motion.ul>
</motion.ul>
</div>
)
}
@@ -1,6 +1,6 @@
import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button'
import type { LateralSide } from '@/domain/schema/observation'
import type { LateralSide } from '@faunosteo/domain'
import { useT } from '@/i18n/useT'
export interface LateralityPickerProps {
@@ -1,16 +1,11 @@
import { useMemo, useState } from 'react'
import type {
Observation,
ObservationZone,
Vertebra,
Finding,
FindingZone,
LateralSide,
} from '@/domain/schema/observation'
import type {
SpeciesFindings,
ZoneFindings,
} from '@/domain/schema/findings'
import type { Bone } from '@/anatomy/types'
import { matchZoneFindings } from '@/lib/zoneMatch'
Observation,
ReportZone,
} from '@faunosteo/domain'
import { AnimatePresence, motion } from 'motion/react'
import Card from '@/components/ui/Card'
import Badge from '@/components/ui/Badge'
@@ -20,9 +15,9 @@ import Textarea from '@/components/ui/Textarea'
import FindingsTreePicker from './FindingsTreePicker'
import FreeTextFindingInput from './FreeTextFindingInput'
import SeveritySelector from './SeveritySelector'
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { boneLabel } from '@/anatomy/labels'
import type { Locale } from '@/i18n/types'
export interface ObservationCardProps {
@@ -36,35 +31,75 @@ export interface ObservationCardProps {
canMoveUp: boolean
canMoveDown: boolean
// Editor body props (used only when expanded)
bones: Map<string, Bone>
findings: SpeciesFindings | null
sheet: SheetIndex
onChange: (next: Observation) => void
onOpenVertebraPicker: (zoneIndex: number) => void
onRemoveZone: (zoneIndex: number) => void
}
/** Zone label: the sheet's current name, else the snapshot, else the id. */
export function zoneLabel(
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const annotation = sheet.annotation(z.annotationId)
if (annotation) return pickLabel(sheet.name(annotation), locale)
const snapshot =
locale === 'en'
? z.labelEnSnapshot || z.labelFrSnapshot
: z.labelFrSnapshot || z.labelEnSnapshot
return snapshot || z.annotationId
}
function describeZone(
z: ObservationZone,
bones: Map<string, Bone>,
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
t: (key: string) => string,
): string {
const label = boneLabel(bones.get(z.boneId), locale, z.boneId)
const label = zoneLabel(z, sheet, locale)
if (z.vertebrae?.length) {
const vs = z.vertebrae
.map((v: Vertebra) => `${v.region}${v.index}`)
.join(', ')
return `${label} (${vs})`
return `${label} (${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')})`
}
if (z.side) {
const sideLabel = t(
z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short',
)
return `${label} (${sideLabel})`
return `${label} (${t(z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`
}
return label
}
interface ZoneTree {
zone: FindingZone
side?: LateralSide
}
/** One picker per (finding zone, side) the observation's zones resolve to. */
function zoneTrees(observation: Observation, sheet: SheetIndex): ZoneTree[] {
const seen = new Set<string>()
const out: ZoneTree[] = []
for (const z of observation.zones) {
const annotation = sheet.annotation(z.annotationId)
if (!isObservable(annotation) || !annotation.finding_zone_id) continue
const zone = sheet.findingZone(annotation.finding_zone_id)
if (!zone) continue
const key = z.side ? `${zone.id}:${z.side}` : zone.id
if (seen.has(key)) continue
seen.add(key)
out.push({ zone, side: z.side })
}
return out
}
/** Findings the sheet no longer holds at their path (migrated data, kept verbatim). */
function unresolvedFindings(
observation: Observation,
sheet: SheetIndex,
): Finding[] {
return observation.findings.filter(
(f) => !sheet.nodeAt(f.findingZoneId, f.path),
)
}
export default function ObservationCard({
observation,
index,
@@ -75,34 +110,37 @@ export default function ObservationCard({
onMoveDown,
canMoveUp,
canMoveDown,
bones,
findings,
sheet,
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 =
const zoneCountLabel = t(
zoneCount > 1
? t('observation.zone_label_plural')
: t('observation.zone_label_singular')
const findingCountLabel =
? 'observation.zone_label_plural'
: 'observation.zone_label_singular',
)
const findingCountLabel = t(
findingCount > 1
? t('observation.finding_label_plural')
: t('observation.finding_label_singular')
? 'observation.finding_label_plural'
: 'observation.finding_label_singular',
)
const trees = useMemo(
() => zoneTrees(observation, sheet),
[observation, sheet],
)
const unresolved = useMemo(
() => unresolvedFindings(observation, sheet),
[observation, sheet],
)
function onHeaderKey(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Enter' || event.key === ' ') {
@@ -110,39 +148,15 @@ export default function ObservationCard({
onToggle()
}
}
function stop(fn: () => void) {
return (event: React.MouseEvent) => {
event.stopPropagation()
fn()
}
const stop = (fn: () => void) => (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; side?: LateralSide }[]
const seen = new Set<string>()
const out: { tree: ZoneFindings; side?: LateralSide }[] = []
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
const key = z.side ? `${tree.id}:${z.side}` : tree.id
if (seen.has(key)) continue
seen.add(key)
out.push({ tree, side: z.side })
}
return out
}, [observation.zones, bones, zonesArray])
const removeFinding = (target: Finding) =>
onChange({
...observation,
findings: observation.findings.filter((f) => f !== target),
})
return (
<Card
@@ -164,13 +178,16 @@ export default function ObservationCard({
>
<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>
<Badge tone="neutral">
{t('observation.badge_n')}
{index + 1}
</Badge>
{observation.severity && (
<Badge
tone={
observation.severity === 'sévère'
observation.severity === 'severe'
? 'danger'
: observation.severity === 'modérée'
: observation.severity === 'moderate'
? 'warn'
: 'neutral'
}
@@ -248,43 +265,49 @@ export default function ObservationCard({
</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, t)}
{supportsVertebrae && (
<button
type="button"
onClick={() => onOpenVertebraPicker(i)}
className="underline text-xs text-[var(--color-accent-strong)]"
title={t('observation.vertebrae_button_title')}
{observation.zones.map((z, i) => (
<li
key={`${z.annotationId}-${z.viewId}-${z.side ?? ''}-${i}`}
>
<Badge tone="accent" className="gap-2">
{describeZone(z, sheet, locale, t)}
{z.unresolved &&
!sheet.annotation(z.annotationId) && (
<span
className="text-xs italic"
title={t('observation.zone_unresolved')}
>
{t('observation.vertebrae_button')}
</button>
{t('observation.unresolved_short')}
</span>
)}
{sheet.isSpine(z.annotationId) && (
<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)]"
onClick={() => onOpenVertebraPicker(i)}
className="underline text-xs text-[var(--color-accent-strong)]"
title={t('observation.vertebrae_button_title')}
>
✕
{t('observation.vertebrae_button')}
</button>
</Badge>
</li>
)
})}
)}
<button
type="button"
aria-label={`${t('observation.remove_zone')} ${zoneLabel(z, sheet, locale)}`}
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 ? (
{trees.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
{observation.zones.length === 0
? t('observation.findings_pick_zone_first')
@@ -292,26 +315,19 @@ export default function ObservationCard({
</p>
) : (
<ul className="space-y-2">
{zonesWithTree.map(({ tree, side }) => {
const pickerKey = side
? `${tree.id}:${side}`
: tree.id
const expanded = expandedZoneId === pickerKey
{trees.map(({ zone, side }) => {
const pickerKey = side ? `${zone.id}:${side}` : zone.id
const open = expandedZoneId === pickerKey
const selectedCount = observation.findings.filter(
(f) =>
f.zoneId === tree.id && f.side === side,
(f) => f.findingZoneId === zone.id && f.side === side,
).length
const selectedAria = `${selectedCount} ${
selectedCount > 1
? t('findings.selected_plural')
: t('findings.selected_singular')
}`
const selectedAria = `${selectedCount} ${selectedCount > 1 ? t('findings.selected_plural') : t('findings.selected_singular')}`
return (
<li
key={pickerKey}
className={[
'rounded-xl border bg-[var(--color-surface)] transition',
expanded
open
? 'border-[var(--color-accent)] ring-1 ring-[var(--color-accent)]'
: 'border-[var(--color-border)]',
].join(' ')}
@@ -319,16 +335,17 @@ export default function ObservationCard({
<button
type="button"
onClick={() =>
setExpandedZoneId(expanded ? null : pickerKey)
setExpandedZoneId(open ? null : pickerKey)
}
aria-expanded={expanded}
aria-expanded={open}
aria-controls={`findings-zone-${pickerKey}`}
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)}
{side && ` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`}
{pickLabel(zone.name, locale)}
{side &&
` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`}
</span>
{selectedCount > 0 && (
<span
@@ -343,11 +360,11 @@ export default function ObservationCard({
aria-hidden="true"
className="text-[var(--color-ink-muted)]"
>
{expanded ? '▲' : '▼'}
{open ? '▲' : '▼'}
</span>
</button>
<AnimatePresence initial={false}>
{expanded && (
{open && (
<motion.div
key="picker-body"
id={`findings-zone-${pickerKey}`}
@@ -359,12 +376,14 @@ export default function ObservationCard({
>
<div className="px-3 pb-3 pt-1 border-t border-[var(--color-border)]">
<FindingsTreePicker
zoneId={tree.id}
tree={tree}
zone={zone}
side={side}
selected={observation.findings}
onChange={(next) =>
onChange({ ...observation, findings: next })
onChange({
...observation,
findings: next,
})
}
/>
</div>
@@ -378,6 +397,40 @@ export default function ObservationCard({
)}
</section>
{unresolved.length > 0 && (
<section>
<Label>{t('observation.findings_unresolved_label')}</Label>
<p className="text-xs text-[var(--color-ink-muted)] mb-2">
{t('observation.findings_unresolved_help')}
</p>
<ul className="space-y-1">
{unresolved.map((f, i) => (
<li
key={`${f.findingZoneId}-${f.path.join('/')}-${f.side ?? ''}-${i}`}
className="flex items-center gap-2 text-sm"
>
<span className="text-[var(--color-ink)]">
{f.requiresVetReferral ? '⚠ ' : ''}
{locale === 'en'
? f.labelEnSnapshot
: f.labelFrSnapshot}
{f.side &&
` (${t(f.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`}
</span>
<button
type="button"
aria-label={`${t('common.delete')} ${locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot}`}
onClick={() => removeFinding(f)}
className="text-[var(--color-accent-strong)]"
>
✕
</button>
</li>
))}
</ul>
</section>
)}
<section>
<Label>{t('observation.findings_free_label')}</Label>
<FreeTextFindingInput
@@ -1,8 +1,7 @@
import type { Observation } from '@/domain/schema/observation'
import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Bone } from '@/anatomy/types'
import type { Observation } from '@faunosteo/domain'
import ObservationCard from './ObservationCard'
import Button from '@/components/ui/Button'
import type { SheetIndex } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
export interface ObservationListProps {
@@ -14,8 +13,7 @@ export interface ObservationListProps {
onMoveUp: (i: number) => void
onMoveDown: (i: number) => void
// Editor body props forwarded to each card
bones: Map<string, Bone>
findings: SpeciesFindings | null
sheet: SheetIndex
onChange: (i: number, next: Observation) => void
onOpenVertebraPicker: (i: number, zoneIndex: number) => void
onRemoveZone: (i: number, zoneIndex: number) => void
@@ -29,8 +27,7 @@ export default function ObservationList({
onDelete,
onMoveUp,
onMoveDown,
bones,
findings,
sheet,
onChange,
onOpenVertebraPicker,
onRemoveZone,
@@ -64,8 +61,7 @@ export default function ObservationList({
onMoveDown={() => onMoveDown(i)}
canMoveUp={i > 0}
canMoveDown={i < observations.length - 1}
bones={bones}
findings={findings}
sheet={sheet}
onChange={(next) => onChange(i, next)}
onOpenVertebraPicker={(zoneIndex) =>
onOpenVertebraPicker(i, zoneIndex)
@@ -1,4 +1,4 @@
import type { Severity } from '@/domain/schema/observation'
import type { Severity } from '@faunosteo/domain'
import { useT } from '@/i18n/useT'
export interface SeveritySelectorProps {
@@ -6,17 +6,25 @@ export interface SeveritySelectorProps {
onChange: (s: Severity | undefined) => void
}
const SEVERITIES: Severity[] = ['légère', 'modérée', 'sévère']
export const SEVERITIES: Severity[] = ['mild', 'moderate', 'severe']
const COLORS: Record<Severity, string> = {
'légère': 'border-[var(--severity-mild)] text-[var(--severity-mild)]',
'modérée': 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]',
'sévère': 'border-[var(--severity-severe)] text-[var(--severity-severe)]',
mild: 'border-[var(--severity-mild)] text-[var(--severity-mild)]',
moderate: 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]',
severe: 'border-[var(--severity-severe)] text-[var(--severity-severe)]',
}
export default function SeveritySelector({ value, onChange }: SeveritySelectorProps) {
/** Severity codes are persisted; labels come from the dictionary (D8). */
export default function SeveritySelector({
value,
onChange,
}: SeveritySelectorProps) {
const t = useT()
return (
<div role="radiogroup" aria-label={t('severity.aria')} className="flex gap-2">
<div
role="radiogroup"
aria-label={t('severity.aria')}
className="flex gap-2"
>
{SEVERITIES.map((s) => (
<button
key={s}
@@ -1,86 +1,93 @@
import { useState } from 'react'
import type { Vertebra, VertebralRegion } from '@faunosteo/domain'
import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button'
import Chip from '@/components/ui/Chip'
import type { Vertebra, VertebralRegion } from '@/domain/schema/observation'
import type { VertebralFormula } from '@/domain/species/types'
import { pickLabel } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
const REGIONS: VertebralRegion[] = ['C', 'T', 'L', 'S', 'Cd']
const REGION_KEY: Record<VertebralRegion, string> = {
C: 'vertebra.region.C',
T: 'vertebra.region.T',
L: 'vertebra.region.L',
S: 'vertebra.region.S',
Cd: 'vertebra.region.Cd',
}
import { useLocaleStore } from '@/state/localeStore'
export interface VertebraPickerProps {
open: boolean
onClose: () => void
onConfirm: (vertebrae: Vertebra[]) => void
initial: Vertebra[]
formula: VertebralFormula
/** Ordered regions of the sheet (`vertebral_config.regions`). */
regions: readonly VertebralRegion[]
title: string
/** Tab to open on. Takes priority so a click always lands on its own zone. */
initialRegion?: VertebralRegion
initialRegion?: string
}
const sameVertebra = (a: Vertebra, r: string, i: number) =>
a.region === r && a.index === i
/**
* Picks vertebrae across every region of the sheet. A region shows its
* usual count; when the sheet documents a wider range (D6), one control
* extends the grid to the documented maximum. Nothing horse-specific here.
*/
export default function VertebraPicker({
open,
onClose,
onConfirm,
initial,
formula,
regions,
title,
initialRegion,
}: VertebraPickerProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [selected, setSelected] = useState<Vertebra[]>(initial)
const [activeRegion, setActiveRegion] = useState<VertebralRegion>(
() => initialRegion ?? initial[0]?.region ?? 'C',
const [activeCode, setActiveCode] = useState<string>(
() => initialRegion ?? initial[0]?.region ?? regions[0]?.code ?? '',
)
const [extended, setExtended] = useState<Set<string>>(() => new Set())
const has = (r: VertebralRegion, i: number) =>
selected.some((v) => v.region === r && v.index === i)
const active = regions.find((r) => r.code === activeCode) ?? regions[0]
if (!active) return null
const maxCount = active.count_range?.max ?? active.count
const highestPicked = Math.max(
0,
...selected.filter((v) => v.region === active.code).map((v) => v.index),
)
const canExtend = maxCount > active.count
const showExtended = extended.has(active.code) || highestPicked > active.count
const count = showExtended ? maxCount : active.count
const toggle = (r: VertebralRegion, i: number) => {
const has = (r: string, i: number) =>
selected.some((v) => sameVertebra(v, r, i))
const toggle = (r: string, i: number) =>
setSelected((cur) =>
has(r, i)
? cur.filter((v) => !(v.region === r && v.index === i))
? cur.filter((v) => !sameVertebra(v, r, i))
: [...cur, { region: r, index: i }],
)
}
const all = (r: VertebralRegion, count: number) => {
setSelected((cur) => {
const rest = cur.filter((v) => v.region !== r)
return [...rest, ...Array.from({ length: count }, (_, k) => ({ region: r, index: k + 1 }))]
})
}
const none = (r: VertebralRegion) =>
const all = (r: string, n: number) =>
setSelected((cur) => [
...cur.filter((v) => v.region !== r),
...Array.from({ length: n }, (_, k) => ({ region: r, index: k + 1 })),
])
const none = (r: string) =>
setSelected((cur) => cur.filter((v) => v.region !== r))
const count = formula[activeRegion]
return (
<Dialog open={open} onClose={onClose} title={title} size="lg">
<div role="tablist" className="flex flex-wrap gap-2 mb-4">
{REGIONS.map((r) => (
{regions.map((r) => (
<button
key={r}
key={r.code}
role="tab"
aria-selected={activeRegion === r}
onClick={() => setActiveRegion(r)}
aria-selected={active.code === r.code}
onClick={() => setActiveCode(r.code)}
className={[
'rounded-full px-4 py-2.5 sm:py-1.5 text-sm font-medium border min-h-[2.75rem]',
activeRegion === r
active.code === r.code
? 'bg-[var(--color-accent)] text-white border-[var(--color-accent)]'
: 'bg-white text-[var(--color-ink)] border-[var(--color-border)]',
].join(' ')}
>
{t(REGION_KEY[r])}
{pickLabel(r.name, locale)}
</button>
))}
</div>
@@ -89,26 +96,52 @@ export default function VertebraPicker({
{Array.from({ length: count }, (_, k) => k + 1).map((i) => (
<Chip
key={i}
active={has(activeRegion, i)}
onClick={() => toggle(activeRegion, i)}
active={has(active.code, i)}
onClick={() => toggle(active.code, i)}
>
{activeRegion}{i}
{active.code}
{i}
</Chip>
))}
</div>
<div className="flex flex-wrap items-center gap-2 mb-6">
<Button variant="ghost" size="sm" onClick={() => all(activeRegion, count)}>
<Button
variant="ghost"
size="sm"
onClick={() => all(active.code, active.count)}
>
{t('vertebra.check_all')}
</Button>
<Button variant="ghost" size="sm" onClick={() => none(activeRegion)}>
<Button variant="ghost" size="sm" onClick={() => none(active.code)}>
{t('vertebra.uncheck_all')}
</Button>
{canExtend && !showExtended && (
<Button
variant="ghost"
size="sm"
onClick={() => setExtended((cur) => new Set(cur).add(active.code))}
>
{t('vertebra.extend_to').replace('{max}', String(maxCount))}
</Button>
)}
{canExtend && showExtended && (
<span className="text-xs text-[var(--color-ink-muted)]">
{t('vertebra.range_note')
.replace('{usual}', String(active.count))
.replace('{min}', String(active.count_range?.min ?? active.count))
.replace('{max}', String(maxCount))}
</span>
)}
</div>
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={onClose}>{t('common.cancel')}</Button>
<Button onClick={() => onConfirm(selected)}>{t('common.confirm')}</Button>
<Button variant="ghost" onClick={onClose}>
{t('common.cancel')}
</Button>
<Button onClick={() => onConfirm(selected)}>
{t('common.confirm')}
</Button>
</div>
</Dialog>
)