553 lines
19 KiB
TypeScript
553 lines
19 KiB
TypeScript
import { useEffect, useMemo, useState } from 'react'
|
|
import { useNavigate } from 'react-router-dom'
|
|
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
|
|
import DetailModal from '@/components/canvas/DetailModal'
|
|
import ObservationList from '@/components/observation/ObservationList'
|
|
import VertebraPicker from '@/components/observation/VertebraPicker'
|
|
import { regionFromLabel } from '@/lib/spineZones'
|
|
import LateralityPicker from '@/components/observation/LateralityPicker'
|
|
import type { LateralSide } from '@/domain/schema/observation'
|
|
import ConclusionPanel from '@/components/report/ConclusionPanel'
|
|
import ReportHeader from '@/components/report/ReportHeader'
|
|
import PractitionerForm from '@/components/report/PractitionerForm'
|
|
import AnimalForm from '@/components/report/AnimalForm'
|
|
import Button from '@/components/ui/Button'
|
|
import Dialog from '@/components/ui/Dialog'
|
|
import { useReportStore } from '@/state/reportStore'
|
|
import { writeCachedPractitioner } from '@/state/practitionerCache'
|
|
import { getSpecies } from '@/domain/species/registry'
|
|
import { loadSvg } from '@/anatomy/svgLoader'
|
|
import { parseSvgBones } from '@/anatomy/svgConvention'
|
|
import { collectSpineVertebrae, syncSpineZones } from '@/lib/spineZones'
|
|
import type { Bone, BoneState } from '@/anatomy/types'
|
|
import type { Observation, ObservationZone } from '@/domain/schema/observation'
|
|
import type { Report } from '@/domain/schema/report'
|
|
import type { SpeciesFindings } from '@/domain/schema/findings'
|
|
import type { Practitioner } from '@/domain/schema/practitioner'
|
|
import type { Animal, Owner } from '@/domain/schema/animal'
|
|
import { exportReportToPdf } from '@/pdf/export'
|
|
import { useT } from '@/i18n/useT'
|
|
import { useLocaleStore } from '@/state/localeStore'
|
|
import { boneLabel } from '@/anatomy/labels'
|
|
|
|
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
|
|
|
|
/** Merges newly parsed bones into the accumulated map without overwriting. */
|
|
function mergeBones(prev: Map<string, Bone>, parsed: Map<string, Bone>) {
|
|
const merged = new Map(prev)
|
|
parsed.forEach((b, id) => {
|
|
if (!merged.has(id)) merged.set(id, b)
|
|
})
|
|
return merged
|
|
}
|
|
|
|
export default function EditorRoute() {
|
|
const navigate = useNavigate()
|
|
const t = useT()
|
|
const locale = useLocaleStore((s) => s.locale)
|
|
const report = useReportStore((s) => s.report)
|
|
const activeIndex = useReportStore((s) => s.activeObservationIndex)
|
|
const addObservation = useReportStore((s) => s.addObservation)
|
|
const updateObservation = useReportStore((s) => s.updateObservation)
|
|
const removeObservation = useReportStore((s) => s.removeObservation)
|
|
const moveObservationUp = useReportStore((s) => s.moveObservationUp)
|
|
const moveObservationDown = useReportStore((s) => s.moveObservationDown)
|
|
const setActiveObservation = useReportStore((s) => s.setActiveObservation)
|
|
const setConclusion = useReportStore((s) => s.setConclusion)
|
|
const setRecommendations = useReportStore((s) => s.setRecommendations)
|
|
const setNextAppointment = useReportStore((s) => s.setNextAppointment)
|
|
const setPractitioner = useReportStore((s) => s.setPractitioner)
|
|
const setAnimal = useReportStore((s) => s.setAnimal)
|
|
const setOwner = useReportStore((s) => s.setOwner)
|
|
|
|
const [bones, setBones] = useState<Map<string, Bone>>(new Map())
|
|
const [detailBones, setDetailBones] = useState<Map<string, Bone>>(new Map())
|
|
const [findings, setFindings] = useState<SpeciesFindings | null>(null)
|
|
const [disclaimer, setDisclaimer] = useState<string | null>(null)
|
|
const [detail, setDetail] = useState<{
|
|
id: string
|
|
src: string
|
|
title: string
|
|
} | null>(null)
|
|
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
|
|
const [lateralTarget, setLateralTarget] = useState<{
|
|
boneId: string
|
|
detailSourceId?: string
|
|
} | null>(null)
|
|
const [exporting, setExporting] = useState(false)
|
|
const [editOpen, setEditOpen] = useState(false)
|
|
const [editDraft, setEditDraft] = useState<{
|
|
practitioner: Practitioner
|
|
animal: Animal
|
|
owner: Owner
|
|
} | null>(null)
|
|
|
|
function openEditInfos() {
|
|
if (!report) return
|
|
setEditDraft({
|
|
practitioner: report.practitioner,
|
|
animal: report.animal,
|
|
owner: report.owner,
|
|
})
|
|
setEditOpen(true)
|
|
}
|
|
|
|
function closeEditInfos() {
|
|
setEditOpen(false)
|
|
setEditDraft(null)
|
|
}
|
|
|
|
function saveEditInfos() {
|
|
if (!editDraft) return closeEditInfos()
|
|
const name = editDraft.practitioner.name.trim()
|
|
const animalName = editDraft.animal.name.trim()
|
|
const ownerName = editDraft.owner.name.trim()
|
|
if (!name || !animalName || !ownerName) return
|
|
setPractitioner(editDraft.practitioner)
|
|
setAnimal(editDraft.animal)
|
|
setOwner(editDraft.owner)
|
|
writeCachedPractitioner(editDraft.practitioner)
|
|
closeEditInfos()
|
|
}
|
|
|
|
function acknowledgeDisclaimer() {
|
|
if (typeof sessionStorage !== 'undefined') {
|
|
sessionStorage.setItem(DISCLAIMER_FLAG, '1')
|
|
}
|
|
setDisclaimer(null)
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (!report) navigate('/')
|
|
}, [report, navigate])
|
|
|
|
useEffect(() => {
|
|
window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
|
|
}, [])
|
|
|
|
const species = useMemo(
|
|
() => (report ? getSpecies(report.animal.speciesId) : undefined),
|
|
[report],
|
|
)
|
|
|
|
useEffect(() => {
|
|
if (!species) return
|
|
loadSvg(species.mainSvg).then((root) => setBones(parseSvgBones(root)))
|
|
species.findings().then((m) => setFindings(m.default))
|
|
|
|
// Eagerly preload every detail SVG so observation zones imported
|
|
// from a PDF (which can carry detail-popup boneIds without the user
|
|
// ever re-opening the popup) resolve their labels and findings
|
|
// pickers immediately on mount. Each fetch is independent — a 404
|
|
// on one detail asset must not prevent the others from loading.
|
|
Object.values(species.details).forEach((path) => {
|
|
loadSvg(path)
|
|
.then((root) => {
|
|
const parsed = parseSvgBones(root)
|
|
setDetailBones((prev) => mergeBones(prev, parsed))
|
|
})
|
|
.catch((err) => {
|
|
console.warn(`EditorRoute: failed to preload detail SVG ${path}`, err)
|
|
})
|
|
})
|
|
}, [species])
|
|
|
|
useEffect(() => {
|
|
if (!findings) return
|
|
if (typeof sessionStorage === 'undefined') return
|
|
if (sessionStorage.getItem(DISCLAIMER_FLAG)) return
|
|
setDisclaimer(findings.scope_disclaimer)
|
|
}, [findings])
|
|
|
|
useEffect(() => {
|
|
if (!detail) return
|
|
let cancelled = false
|
|
loadSvg(detail.src).then((root) => {
|
|
if (cancelled) return
|
|
const parsed = parseSvgBones(root)
|
|
setDetailBones((prev) => mergeBones(prev, parsed))
|
|
})
|
|
return () => {
|
|
cancelled = true
|
|
}
|
|
}, [detail])
|
|
|
|
const allBones = useMemo(() => {
|
|
const m = new Map(bones)
|
|
detailBones.forEach((b, id) => {
|
|
if (!m.has(id)) m.set(id, b)
|
|
})
|
|
return m
|
|
}, [bones, detailBones])
|
|
|
|
const activeObs =
|
|
activeIndex >= 0 ? report?.observations[activeIndex] : undefined
|
|
|
|
const boneStates = useMemo<Map<string, BoneState>>(() => {
|
|
const map = new Map<string, BoneState>()
|
|
if (!report || activeIndex < 0) return map
|
|
const active = report.observations[activeIndex]
|
|
if (!active) return map
|
|
active.zones.forEach((z) => {
|
|
map.set(z.boneId, 'current')
|
|
})
|
|
return map
|
|
}, [report, activeIndex])
|
|
|
|
function onToggleCard(index: number) {
|
|
setActiveObservation(activeIndex === index ? -1 : index)
|
|
}
|
|
|
|
/** Opens the detail-popup modal for a bone that carries data-anno-opens-detail. */
|
|
function handleDetailOpen(bone: Bone, detailId: string, detailSrc: string) {
|
|
setDetail({
|
|
id: detailId,
|
|
src: detailSrc,
|
|
title: boneLabel(bone, locale, detailId),
|
|
})
|
|
}
|
|
|
|
/**
|
|
* No expanded observation — auto-expand the most recent one (or the
|
|
* first if no rows yet) so the click lands somewhere. Defers the actual
|
|
* zone add to the next render where activeObs is set.
|
|
*/
|
|
function activateFallbackObservation(report: Report) {
|
|
const fallbackIndex =
|
|
report.observations.length > 0 ? report.observations.length - 1 : -1
|
|
if (fallbackIndex < 0) return
|
|
setActiveObservation(fallbackIndex)
|
|
}
|
|
|
|
/**
|
|
* Spine-zone behavior: always open VertebraPicker on click. Adds the
|
|
* zone if missing; never toggles it off here (use the ✕ button).
|
|
*/
|
|
function handleSpineZone(
|
|
activeObs: Observation,
|
|
boneId: string,
|
|
detailSourceId: string | undefined,
|
|
existingIndex: number,
|
|
) {
|
|
let targetIndex = existingIndex
|
|
if (existingIndex < 0) {
|
|
const newZone: ObservationZone = {
|
|
boneId,
|
|
...(detailSourceId ? { detailSourceId } : {}),
|
|
}
|
|
const nextZones = [...activeObs.zones, newZone]
|
|
targetIndex = nextZones.length - 1
|
|
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
|
|
}
|
|
setVertebraTarget(targetIndex)
|
|
}
|
|
|
|
/** Bilateral zone: adding a side, or clearing both once left+right are set. */
|
|
function handleBilateralZone(
|
|
activeObs: Observation,
|
|
boneId: string,
|
|
detailSourceId: string | undefined,
|
|
) {
|
|
const sidesPresent = activeObs.zones
|
|
.filter(
|
|
(z) => z.boneId === boneId && z.detailSourceId === detailSourceId,
|
|
)
|
|
.map((z) => z.side)
|
|
.filter(Boolean) as LateralSide[]
|
|
|
|
if (sidesPresent.includes('left') && sidesPresent.includes('right')) {
|
|
const nextZones = activeObs.zones.filter(
|
|
(z) => !(z.boneId === boneId && z.detailSourceId === detailSourceId),
|
|
)
|
|
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
|
|
return
|
|
}
|
|
|
|
setLateralTarget({
|
|
boneId,
|
|
...(detailSourceId ? { detailSourceId } : {}),
|
|
})
|
|
}
|
|
|
|
/** Plain zone: toggles it on the active observation. */
|
|
function toggleZone(
|
|
activeObs: Observation,
|
|
boneId: string,
|
|
detailSourceId: string | undefined,
|
|
existingIndex: number,
|
|
) {
|
|
const newZone: ObservationZone = {
|
|
boneId,
|
|
...(detailSourceId ? { detailSourceId } : {}),
|
|
}
|
|
const nextZones =
|
|
existingIndex >= 0
|
|
? activeObs.zones.filter((_, k) => k !== existingIndex)
|
|
: [...activeObs.zones, newZone]
|
|
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
|
|
}
|
|
|
|
function onZoneClick(boneId: string, detailSourceId?: string) {
|
|
if (!report) return
|
|
const bone = bones.get(boneId) ?? detailBones.get(boneId)
|
|
if (!bone) return
|
|
|
|
if (bone.opensDetail && species?.details[bone.opensDetail]) {
|
|
handleDetailOpen(bone, bone.opensDetail, species.details[bone.opensDetail])
|
|
return
|
|
}
|
|
|
|
if (!activeObs || activeIndex < 0) {
|
|
activateFallbackObservation(report)
|
|
return
|
|
}
|
|
|
|
const matches = (z: ObservationZone) =>
|
|
z.boneId === boneId && z.detailSourceId === detailSourceId
|
|
const existingIndex = activeObs.zones.findIndex(matches)
|
|
|
|
if (bone.special === 'vertebral-precision') {
|
|
handleSpineZone(activeObs, boneId, detailSourceId, existingIndex)
|
|
return
|
|
}
|
|
|
|
if (bone.lateral === 'bilateral') {
|
|
handleBilateralZone(activeObs, boneId, detailSourceId)
|
|
return
|
|
}
|
|
|
|
toggleZone(activeObs, boneId, detailSourceId, existingIndex)
|
|
}
|
|
|
|
async function onExport() {
|
|
if (!report) return
|
|
setExporting(true)
|
|
try {
|
|
const bytes = await exportReportToPdf(report, { locale })
|
|
const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' })
|
|
const url = URL.createObjectURL(blob)
|
|
const a = document.createElement('a')
|
|
a.href = url
|
|
a.download = `bilan-${report.animal.name}-${report.date}.pdf`
|
|
a.click()
|
|
URL.revokeObjectURL(url)
|
|
} catch (err) {
|
|
console.error('PDF export failed', err)
|
|
window.alert(t('editor.export_failed'))
|
|
} finally {
|
|
setExporting(false)
|
|
}
|
|
}
|
|
|
|
if (!report || !species) return null
|
|
|
|
return (
|
|
<main className="min-h-screen flex flex-col">
|
|
<ReportHeader report={report} onEditInfos={openEditInfos} />
|
|
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
|
|
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none">
|
|
<AnatomyCanvas
|
|
src={species.mainSvg}
|
|
boneStates={boneStates}
|
|
onZoneClick={(id) => onZoneClick(id)}
|
|
/>
|
|
</section>
|
|
<section className="space-y-4 sm:space-y-6">
|
|
<ObservationList
|
|
observations={report.observations}
|
|
activeIndex={activeIndex}
|
|
onToggle={onToggleCard}
|
|
onAdd={addObservation}
|
|
onDelete={removeObservation}
|
|
onMoveUp={moveObservationUp}
|
|
onMoveDown={moveObservationDown}
|
|
bones={allBones}
|
|
findings={findings}
|
|
onChange={(i, next: Observation) => updateObservation(i, next)}
|
|
onOpenVertebraPicker={(_i, zoneIndex) =>
|
|
setVertebraTarget(zoneIndex)
|
|
}
|
|
onRemoveZone={(i, zoneIndex) => {
|
|
const obs = report.observations[i]
|
|
if (!obs) return
|
|
const zones = obs.zones.filter((_, k) => k !== zoneIndex)
|
|
updateObservation(i, { ...obs, zones })
|
|
}}
|
|
/>
|
|
<ConclusionPanel
|
|
conclusion={report.conclusion}
|
|
recommendations={report.recommendations}
|
|
nextAppointment={report.nextAppointment}
|
|
onChangeConclusion={setConclusion}
|
|
onChangeRecommendations={setRecommendations}
|
|
onChangeNextAppointment={setNextAppointment}
|
|
/>
|
|
<div className="flex justify-end">
|
|
<Button onClick={onExport} disabled={exporting}>
|
|
{exporting ? t('editor.exporting') : t('editor.export')}
|
|
</Button>
|
|
</div>
|
|
</section>
|
|
</div>
|
|
|
|
{detail && (
|
|
<DetailModal
|
|
open
|
|
onClose={() => setDetail(null)}
|
|
detailSrc={detail.src}
|
|
detailId={detail.id}
|
|
title={`${t('editor.detail_title_prefix')}${detail.title}`}
|
|
boneStates={boneStates}
|
|
onZoneClick={(id, did) => onZoneClick(id, did)}
|
|
/>
|
|
)}
|
|
|
|
{editDraft && (
|
|
<Dialog
|
|
open={editOpen}
|
|
onClose={closeEditInfos}
|
|
title={t('editor.edit_dialog_title')}
|
|
size="lg"
|
|
>
|
|
<div className="space-y-8">
|
|
<PractitionerForm
|
|
value={editDraft.practitioner}
|
|
onChange={(next) =>
|
|
setEditDraft((d) => (d ? { ...d, practitioner: next } : d))
|
|
}
|
|
/>
|
|
<AnimalForm
|
|
animal={editDraft.animal}
|
|
owner={editDraft.owner}
|
|
onChangeAnimal={(next) =>
|
|
setEditDraft((d) => (d ? { ...d, animal: next } : d))
|
|
}
|
|
onChangeOwner={(next) =>
|
|
setEditDraft((d) => (d ? { ...d, owner: next } : d))
|
|
}
|
|
/>
|
|
<div className="flex gap-3 justify-end pt-2 border-t border-[var(--color-border)]">
|
|
<Button variant="ghost" onClick={closeEditInfos}>
|
|
{t('common.cancel')}
|
|
</Button>
|
|
<Button
|
|
onClick={saveEditInfos}
|
|
disabled={
|
|
!editDraft.practitioner.name.trim() ||
|
|
!editDraft.animal.name.trim() ||
|
|
!editDraft.owner.name.trim()
|
|
}
|
|
>
|
|
{t('common.save')}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</Dialog>
|
|
)}
|
|
|
|
{disclaimer && (
|
|
<Dialog
|
|
open
|
|
onClose={acknowledgeDisclaimer}
|
|
title={t('editor.disclaimer_title')}
|
|
size="md"
|
|
>
|
|
<div className="space-y-4">
|
|
<p className="text-sm text-[var(--color-ink)]">{disclaimer}</p>
|
|
<div className="flex justify-end">
|
|
<Button onClick={acknowledgeDisclaimer}>{t('common.understood')}</Button>
|
|
</div>
|
|
</div>
|
|
</Dialog>
|
|
)}
|
|
|
|
{vertebraTarget !== null &&
|
|
activeObs &&
|
|
activeObs.zones[vertebraTarget] && (
|
|
<VertebraPicker
|
|
open
|
|
onClose={() => setVertebraTarget(null)}
|
|
onConfirm={(vertebrae) => {
|
|
const fresh =
|
|
useReportStore.getState().report?.observations[activeIndex]
|
|
if (!fresh?.zones[vertebraTarget]) {
|
|
setVertebraTarget(null)
|
|
return
|
|
}
|
|
// Picker edits every region at once: reconcile all spine zones —
|
|
// spawn newly picked regions, prune emptied ones, keep the rest.
|
|
const next = syncSpineZones(fresh.zones, vertebrae, bones)
|
|
updateObservation(activeIndex, { ...fresh, zones: next })
|
|
setVertebraTarget(null)
|
|
}}
|
|
initial={collectSpineVertebrae(
|
|
activeObs.zones,
|
|
bones,
|
|
activeObs.zones[vertebraTarget].boneId,
|
|
)}
|
|
formula={species.vertebralFormula}
|
|
title={`${t('vertebra.title_prefix')}${boneLabel(
|
|
bones.get(activeObs.zones[vertebraTarget].boneId),
|
|
locale,
|
|
'',
|
|
)}`}
|
|
initialRegion={(() => {
|
|
const b = bones.get(activeObs.zones[vertebraTarget].boneId)
|
|
return regionFromLabel(b?.fr ?? '') ?? regionFromLabel(b?.en ?? '')
|
|
})()}
|
|
/>
|
|
)}
|
|
|
|
{lateralTarget && activeObs && (
|
|
<LateralityPicker
|
|
open
|
|
onClose={() => setLateralTarget(null)}
|
|
title={boneLabel(
|
|
allBones.get(lateralTarget.boneId),
|
|
locale,
|
|
lateralTarget.boneId,
|
|
)}
|
|
existingSides={
|
|
activeObs.zones
|
|
.filter(
|
|
(z) =>
|
|
z.boneId === lateralTarget.boneId &&
|
|
z.detailSourceId === lateralTarget.detailSourceId &&
|
|
z.side,
|
|
)
|
|
.map((z) => z.side!) as LateralSide[]
|
|
}
|
|
onSelect={(sides) => {
|
|
const fresh =
|
|
useReportStore.getState().report?.observations[activeIndex]
|
|
if (!fresh) {
|
|
setLateralTarget(null)
|
|
return
|
|
}
|
|
const newSideZones = sides
|
|
.filter(
|
|
(side) =>
|
|
!fresh.zones.some(
|
|
(z) =>
|
|
z.boneId === lateralTarget.boneId &&
|
|
z.detailSourceId === lateralTarget.detailSourceId &&
|
|
z.side === side,
|
|
),
|
|
)
|
|
.map((side) => ({
|
|
boneId: lateralTarget.boneId,
|
|
...(lateralTarget.detailSourceId
|
|
? { detailSourceId: lateralTarget.detailSourceId }
|
|
: {}),
|
|
side,
|
|
}))
|
|
const nextZones = [...fresh.zones, ...newSideZones]
|
|
updateObservation(activeIndex, { ...fresh, zones: nextZones })
|
|
setLateralTarget(null)
|
|
}}
|
|
/>
|
|
)}
|
|
</main>
|
|
)
|
|
}
|