Files
faunosteo/apps/app/src/components/observation/ObservationCard.tsx
T

488 lines
18 KiB
TypeScript

import { useMemo, useState } from 'react'
import type {
Finding,
FindingZone,
LateralSide,
Observation,
ReportZone,
} from '@faunosteo/core-wasm/types'
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 { isObservable, type SheetIndex } from '@/services/sheetIndex'
import { pickLabel } from '@/i18n/pickLocaleLabel'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
import { coreFailureMessage } from '@/core/failure'
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)
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: ReportZone,
sheet: SheetIndex,
locale: Locale,
t: (key: string) => string,
): string {
const label = zoneLabel(z, sheet, locale)
if (z.vertebrae?.length) {
return `${label} (${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')})`
}
if (z.side) {
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.hasNode(f.findingZoneId, f.path),
)
}
export default function ObservationCard({
observation,
index,
expanded,
onToggle,
onDelete,
onMoveUp,
onMoveDown,
canMoveUp,
canMoveDown,
sheet,
onChange,
onOpenVertebraPicker,
onRemoveZone,
}: ObservationCardProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [expandedZoneId, setExpandedZoneId] = useState<string | null>(null)
const zoneCount = observation.zones.length
const findingCount =
observation.findings.length + observation.freeTextFindings.length
const zoneCountLabel = t(
zoneCount > 1
? 'observation.zone_label_plural'
: 'observation.zone_label_singular',
)
const findingCountLabel = t(
findingCount > 1
? '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 === ' ') {
event.preventDefault()
onToggle()
}
}
const stop = (fn: () => void) => (event: React.MouseEvent) => {
event.stopPropagation()
fn()
}
/** The core builds or removes the finding of the clicked leaf (R2). */
function toggleFinding(
findingZoneId: string,
side: LateralSide | undefined,
path: string[],
leafPosition: number,
) {
const outcome = sheet.ops.toggleFinding({
observation,
findingZoneId,
path,
leafPosition,
...(side ? { side } : {}),
})
if (outcome.ok) onChange(outcome.value)
else window.alert(coreFailureMessage(t))
}
const removeFinding = (target: Finding) =>
onChange({
...observation,
findings: observation.findings.filter((f) => f !== target),
})
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 === 'severe'
? 'danger'
: observation.severity === 'moderate'
? '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) => (
<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.unresolved_short')}
</span>
)}
{sheet.isSpine(z.annotationId) && (
<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')} ${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>
{trees.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">
{trees.map(({ zone, side }) => {
const pickerKey = side ? `${zone.id}:${side}` : zone.id
const open = expandedZoneId === pickerKey
const selectedCount = observation.findings.filter(
(f) => f.findingZoneId === zone.id && f.side === side,
).length
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',
open
? 'border-[var(--color-accent)] ring-1 ring-[var(--color-accent)]'
: 'border-[var(--color-border)]',
].join(' ')}
>
<button
type="button"
onClick={() =>
setExpandedZoneId(open ? null : pickerKey)
}
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)]">
{pickLabel(zone.name, locale)}
{side &&
` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`}
</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)]"
>
{open ? '▲' : '▼'}
</span>
</button>
<AnimatePresence initial={false}>
{open && (
<motion.div
key="picker-body"
id={`findings-zone-${pickerKey}`}
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
zone={zone}
side={side}
selected={observation.findings}
onToggle={(path, leafPosition) =>
toggleFinding(zone.id, side, path, leafPosition)
}
/>
</div>
</motion.div>
)}
</AnimatePresence>
</li>
)
})}
</ul>
)}
</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
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>
)
}