feat(app): R2 switch — the application runs its domain rules in the Rust core
Consumers now fed by the core (crates/core through @faunosteo/core-wasm):
- the sheet: the bundled payload is parsed and indexed by the core
(SheetHandle, SheetIndexData); SheetIndex reads precomputed tables only;
- the store: new report, add / remove / move observation, draft restore
(v2 migration + rebase) through the core, actions answering { ok };
- the editor click chain (zone.click), laterality and vertebra pickers
(zone.add_sides, vertebra.initial / sync / select), the findings picker
(finding.toggle by clicked leaf position), zone removal;
- the import: engine byte scan (TypeScript until R4), then the core's
layered reading and rebase in one call; the export: the core builds the
sheet snapshot, the frozen TypeScript engine writes the PDF (R4).
Lazy core: Home and the new-report form read the sheet availability from
the bundle and load the module on import / submit only; the auth shell
never references it. Degraded states (core_unavailable, invalid_sheet)
show the validated notice with a retry and never redirect or touch the
draft; an unreadable draft or archive is set aside under
osteo:quarantine:* (only content kinds; a failed write keeps it in place
and the editor stays), a rebase that flags items keeps the raw pre-rebase
draft. Four strings, wording validated by the owner.
Deleted: services/zoneInteraction.ts and its suite (13 cases ported to
cargo), the TypeScript Finding builder and vertebra selection rules of the
pickers, store rules, persistence parsing, hydrateReport. ESLint forbids
@faunosteo/domain in apps/app/src; the report:compare CLI keeps the frozen
domain until R4 (scripts/compare/sheet.ts). App suite 313/313 on the real
core (24 new tests: quarantine, degraded editor, core failures, N-1
reader); step6 goldens and the frozen envelopes unchanged.
This commit is contained in:
1 parent
794dfd9d0b
commit
74fcb37564
65 files changed
+2227
-1678
No files matched your search
@@ -3,7 +3,7 @@ import {
|
||||
renderAnnotationLayer,
|
||||
viewBoxOf,
|
||||
} from '@faunosteo/anatomy/render'
|
||||
import type { SheetView } from '@faunosteo/domain'
|
||||
import type { SheetView } from '@faunosteo/core-wasm/types'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,7 +3,10 @@ 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 ObservationPickers from '@/components/observation/ObservationPickers'
|
||||
import ObservationPickers, {
|
||||
type LateralTarget,
|
||||
type VertebraTarget,
|
||||
} from '@/components/observation/ObservationPickers'
|
||||
import ConclusionPanel from '@/components/report/ConclusionPanel'
|
||||
import ReportHeader from '@/components/report/ReportHeader'
|
||||
import EditInfosDialog, {
|
||||
@@ -11,25 +14,22 @@ import EditInfosDialog, {
|
||||
type Identity,
|
||||
} from '@/components/report/EditInfosDialog'
|
||||
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
|
||||
import CoreUnavailable from '@/components/report/CoreUnavailable'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import {
|
||||
useReportStore,
|
||||
type ActionResult,
|
||||
type RestoreResult,
|
||||
} from '@/state/reportStore'
|
||||
import { writeCachedPractitioner } from '@/state/practitionerCache'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { useSheet } from '@/sheets/useSheet'
|
||||
import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
decideZoneClick,
|
||||
ensureZone,
|
||||
refOf,
|
||||
removeAllSides,
|
||||
removeZoneAt,
|
||||
toggleZone,
|
||||
type ZoneRef,
|
||||
} from '@/services/zoneInteraction'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import type { ViewStates } from '@/anatomy/drawing'
|
||||
import { exportReportToPdf } from '@/pdf/export'
|
||||
import type { ExportWarning } from '@faunosteo/pdf'
|
||||
import type { RebaseOutcome } from '@faunosteo/domain'
|
||||
import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||
|
||||
@@ -45,6 +45,19 @@ function unresolvedCountOf(outcome: RebaseOutcome): number {
|
||||
return outcome.unresolvedZones + outcome.unresolvedFindings
|
||||
}
|
||||
|
||||
/** The alert of a restore, if any: a rebase on another sheet or a draft set aside. */
|
||||
function restoreAlert(
|
||||
result: RestoreResult,
|
||||
t: ReturnType<typeof useT>,
|
||||
): string | null {
|
||||
if (result.kind === 'quarantined') return t('editor.draft_quarantined')
|
||||
if (result.kind === 'restored' && result.rebase.rebased) {
|
||||
const count = String(unresolvedCountOf(result.rebase))
|
||||
return t('editor.draft_rebased').replace('{count}', count)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Editor on the reference sheet: wires the canvas, the pickers and the store. */
|
||||
export default function EditorRoute() {
|
||||
const navigate = useNavigate()
|
||||
@@ -56,8 +69,14 @@ export default function EditorRoute() {
|
||||
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
|
||||
|
||||
const [detailViewId, setDetailViewId] = useState<string | null>(null)
|
||||
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
|
||||
const [lateralTarget, setLateralTarget] = useState<ZoneRef | null>(null)
|
||||
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
|
||||
null,
|
||||
)
|
||||
const [lateralTarget, setLateralTarget] = useState<LateralTarget | null>(
|
||||
null,
|
||||
)
|
||||
// The core failed while reading the draft: stay here, keep the draft, offer a retry.
|
||||
const [restoreFailed, setRestoreFailed] = useState(false)
|
||||
const [disclaimer, setDisclaimer] = useState<string | null>(null)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [editDraft, setEditDraft] = useState<Identity | null>(null)
|
||||
@@ -69,15 +88,24 @@ export default function EditorRoute() {
|
||||
}, [])
|
||||
|
||||
// No report in memory: restore the per-tab draft once the sheet is known.
|
||||
// A draft rebased on another sheet is announced with its unresolved count.
|
||||
// A draft rebased on another sheet is announced with its unresolved count,
|
||||
// an unreadable one is set aside. While the core cannot run, nothing is
|
||||
// read or written and the page stays on the degraded notice (no redirect).
|
||||
useEffect(() => {
|
||||
if (report) return
|
||||
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet')
|
||||
return
|
||||
if (sheet.status === 'ready') {
|
||||
const outcome = store.restoreDraft(sheet.index)
|
||||
if (outcome?.rebased && !rebaseAlerted.current) {
|
||||
const result = store.restoreDraft(sheet.index)
|
||||
// Nothing could be read or set aside: stay, keep the draft where it is.
|
||||
if (result?.kind === 'core_unavailable' || result?.kind === 'unreadable_kept') {
|
||||
setRestoreFailed(true)
|
||||
return
|
||||
}
|
||||
const alert = result ? restoreAlert(result, t) : null
|
||||
if (alert && !rebaseAlerted.current) {
|
||||
rebaseAlerted.current = true
|
||||
const count = String(unresolvedCountOf(outcome))
|
||||
window.alert(t('editor.draft_rebased').replace('{count}', count))
|
||||
window.alert(alert)
|
||||
}
|
||||
}
|
||||
if (sheet.status !== 'loading' && !useReportStore.getState().report)
|
||||
@@ -111,42 +139,56 @@ export default function EditorRoute() {
|
||||
if (sheet.status !== 'ready' || !report) return
|
||||
const activeObs =
|
||||
activeIndex >= 0 ? report.observations[activeIndex] : undefined
|
||||
const index = sheet.index
|
||||
const annotation = index.annotation(annotationId)
|
||||
const decision = decideZoneClick(annotation, activeObs)
|
||||
if (!annotation) return
|
||||
switch (decision.kind) {
|
||||
case 'ignore':
|
||||
return
|
||||
const outcome = sheet.index.ops.zoneClick(activeObs ?? null, annotationId)
|
||||
if (!outcome.ok) return window.alert(t('core.action_failed'))
|
||||
const click = outcome.value
|
||||
if (click.observation) store.updateObservation(activeIndex, click.observation)
|
||||
switch (click.kind) {
|
||||
case 'open_view':
|
||||
return setDetailViewId(decision.viewId)
|
||||
return setDetailViewId(click.viewId ?? null)
|
||||
case 'activate_fallback':
|
||||
return store.setActiveObservation(report.observations.length - 1)
|
||||
case 'open_vertebra_picker': {
|
||||
const { observation, index: zoneIndex } = ensureZone(
|
||||
activeObs!,
|
||||
annotation,
|
||||
)
|
||||
store.updateObservation(activeIndex, observation)
|
||||
return setVertebraTarget(zoneIndex)
|
||||
}
|
||||
case 'open_vertebra_picker':
|
||||
return setVertebraTarget({
|
||||
zoneIndex: click.zoneIndex ?? 0,
|
||||
initial: click.vertebrae ?? [],
|
||||
})
|
||||
case 'open_laterality_picker':
|
||||
return setLateralTarget(refOf(annotation))
|
||||
case 'remove_both_sides':
|
||||
return store.updateObservation(
|
||||
activeIndex,
|
||||
removeAllSides(activeObs!, refOf(annotation)),
|
||||
)
|
||||
case 'toggle':
|
||||
return store.updateObservation(
|
||||
activeIndex,
|
||||
toggleZone(activeObs!, annotation),
|
||||
)
|
||||
return setLateralTarget({
|
||||
annotationId,
|
||||
sidesPresent: click.sidesPresent ?? [],
|
||||
})
|
||||
default:
|
||||
return
|
||||
}
|
||||
},
|
||||
[sheet, store],
|
||||
[sheet, store, t],
|
||||
)
|
||||
|
||||
/** A store action the core ran: the practitioner hears about a failure. */
|
||||
const guarded = useCallback(
|
||||
(result: ActionResult) => {
|
||||
if (!result.ok) window.alert(t('core.action_failed'))
|
||||
},
|
||||
[t],
|
||||
)
|
||||
|
||||
/** The vertebra picker opened from a zone chip: the core computes its selection. */
|
||||
function openVertebraPicker(index: SheetIndex, zoneIndex: number) {
|
||||
if (!activeObs) return
|
||||
const outcome = index.ops.vertebraInitial(activeObs, zoneIndex)
|
||||
if (!outcome.ok) return window.alert(t('core.action_failed'))
|
||||
setVertebraTarget({ zoneIndex, initial: outcome.value })
|
||||
}
|
||||
|
||||
function removeZone(index: SheetIndex, i: number, zoneIndex: number) {
|
||||
const obs = report?.observations[i]
|
||||
if (!obs) return
|
||||
const outcome = index.ops.removeZoneAt(obs, zoneIndex)
|
||||
if (outcome.ok) store.updateObservation(i, outcome.value)
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
|
||||
function acknowledgeDisclaimer() {
|
||||
sessionStorage?.setItem(DISCLAIMER_FLAG, '1')
|
||||
setDisclaimer(null)
|
||||
@@ -190,6 +232,12 @@ export default function EditorRoute() {
|
||||
}
|
||||
}
|
||||
|
||||
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet') {
|
||||
return <CoreUnavailable onRetry={sheet.retry} />
|
||||
}
|
||||
if (restoreFailed) {
|
||||
return <CoreUnavailable onRetry={() => window.location.reload()} />
|
||||
}
|
||||
if (!report) return null
|
||||
if (sheet.status === 'loading') {
|
||||
return (
|
||||
@@ -218,7 +266,7 @@ export default function EditorRoute() {
|
||||
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
|
||||
<AnatomyCanvas
|
||||
index={index}
|
||||
viewId={index.mainView.id}
|
||||
viewId={index.mainViewId}
|
||||
states={states}
|
||||
onZoneClick={onZoneClick}
|
||||
className="flex-1"
|
||||
@@ -241,19 +289,16 @@ export default function EditorRoute() {
|
||||
onToggle={(i) =>
|
||||
store.setActiveObservation(activeIndex === i ? -1 : i)
|
||||
}
|
||||
onAdd={store.addObservation}
|
||||
onDelete={store.removeObservation}
|
||||
onMoveUp={store.moveObservationUp}
|
||||
onMoveDown={store.moveObservationDown}
|
||||
onAdd={() => guarded(store.addObservation())}
|
||||
onDelete={(i) => guarded(store.removeObservation(i))}
|
||||
onMoveUp={(i) => guarded(store.moveObservationUp(i))}
|
||||
onMoveDown={(i) => guarded(store.moveObservationDown(i))}
|
||||
sheet={index}
|
||||
onChange={store.updateObservation}
|
||||
onOpenVertebraPicker={(_i, zoneIndex) =>
|
||||
setVertebraTarget(zoneIndex)
|
||||
openVertebraPicker(index, zoneIndex)
|
||||
}
|
||||
onRemoveZone={(i, zoneIndex) => {
|
||||
const obs = report.observations[i]
|
||||
if (obs) store.updateObservation(i, removeZoneAt(obs, zoneIndex))
|
||||
}}
|
||||
onRemoveZone={(i, zoneIndex) => removeZone(index, i, zoneIndex)}
|
||||
/>
|
||||
<ConclusionPanel
|
||||
conclusion={report.conclusion}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useRef, useState } from 'react'
|
||||
import {
|
||||
rebaseReportOnSheet,
|
||||
type ArchiveReadOutcome,
|
||||
type RebaseOutcome,
|
||||
} from '@faunosteo/domain'
|
||||
import type {
|
||||
ArchiveReadOutcome,
|
||||
RebaseOutcome,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Card from '@/components/ui/Card'
|
||||
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
|
||||
import {
|
||||
importAttachment,
|
||||
ImportError,
|
||||
MAX_PDF_BYTES,
|
||||
readAttachment,
|
||||
} from '@/pdf/import'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useSheet } from '@/sheets/useSheet'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
@@ -100,6 +103,8 @@ function importErrorMessage(err: unknown, t: Translate): string {
|
||||
return t('home.import.error_attachment_stripped')
|
||||
case 'no_attachment':
|
||||
return t('home.import.error_no_attachment')
|
||||
case 'core_unavailable':
|
||||
return t('home.import.error_core_unavailable')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,22 +112,21 @@ export default function HomeRoute() {
|
||||
const navigate = useNavigate()
|
||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||||
const hydrateImport = useReportStore((s) => s.hydrateImport)
|
||||
const sheet = useSheet(DEFAULT_SPECIES_ID)
|
||||
// The page only needs to know a sheet exists; the core loads when a file is picked.
|
||||
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const t = useT()
|
||||
|
||||
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
|
||||
async function importFile(file: File, index: SheetIndex) {
|
||||
async function importFile(file: File) {
|
||||
// The engine refuses the same size; checking first keeps a huge file out of memory.
|
||||
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
|
||||
const bytes = new Uint8Array(await file.arrayBuffer())
|
||||
const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap)
|
||||
const rebase = rebaseReportOnSheet(
|
||||
outcome.report,
|
||||
index,
|
||||
outcome.archive?.sheetSnapshot ?? null,
|
||||
)
|
||||
const attachment = await readAttachment(bytes)
|
||||
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
|
||||
if (!index) throw new ImportError('core_unavailable')
|
||||
const { read: outcome, rebase } = importAttachment(attachment, index)
|
||||
hydrateImport({ report: rebase.report, archive: outcome.archive })
|
||||
const lines = importMessages(outcome, rebase, t)
|
||||
if (lines.length > 0) window.alert(lines.join('\n\n'))
|
||||
@@ -135,7 +139,7 @@ export default function HomeRoute() {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await importFile(file, sheet.index)
|
||||
await importFile(file)
|
||||
} catch (err) {
|
||||
setError(importErrorMessage(err, t))
|
||||
} finally {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
|
||||
import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
|
||||
import PractitionerForm from '@/components/report/PractitionerForm'
|
||||
import AnimalForm from '@/components/report/AnimalForm'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
@@ -13,7 +13,8 @@ import {
|
||||
writeCachedPractitioner,
|
||||
} from '@/state/practitionerCache'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useSheet } from '@/sheets/useSheet'
|
||||
import { useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** The one species this build ships a sheet for. */
|
||||
@@ -23,7 +24,8 @@ export default function NewReportRoute() {
|
||||
const navigate = useNavigate()
|
||||
const initReport = useReportStore((s) => s.initReport)
|
||||
const t = useT()
|
||||
const sheet = useSheet(DEFAULT_SPECIES_ID)
|
||||
// The form needs the sheet's reference and name only; the core loads on submit.
|
||||
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
|
||||
|
||||
const [practitioner, setPractitioner] = useState<Practitioner>({ name: '' })
|
||||
const [animal, setAnimal] = useState<Animal>({
|
||||
@@ -44,10 +46,14 @@ export default function NewReportRoute() {
|
||||
owner.name.trim() &&
|
||||
sheet.status === 'ready'
|
||||
|
||||
function submit() {
|
||||
async function submit() {
|
||||
if (!canSubmit || sheet.status !== 'ready') return
|
||||
writeCachedPractitioner(practitioner)
|
||||
initReport(
|
||||
if (!(await coreRuntime().ready())) {
|
||||
window.alert(t('sheet.core_unavailable'))
|
||||
return
|
||||
}
|
||||
const created = initReport(
|
||||
{
|
||||
date,
|
||||
practitioner,
|
||||
@@ -57,9 +63,10 @@ export default function NewReportRoute() {
|
||||
conclusion: '',
|
||||
recommendations: '',
|
||||
},
|
||||
sheet.index.sheet.ref,
|
||||
sheet.sheet.ref,
|
||||
)
|
||||
navigate('/editor')
|
||||
if (created.ok) navigate('/editor')
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -91,8 +98,8 @@ export default function NewReportRoute() {
|
||||
sheet.status === 'ready'
|
||||
? [
|
||||
{
|
||||
id: sheet.index.sheet.speciesId,
|
||||
name: sheet.index.sheet.document.name,
|
||||
id: sheet.sheet.speciesId,
|
||||
name: sheet.sheet.name,
|
||||
},
|
||||
]
|
||||
: [
|
||||
|
||||
@@ -7,9 +7,9 @@ import type {
|
||||
FindingZone,
|
||||
LateralSide,
|
||||
LocalizedOptionalText,
|
||||
} from '@faunosteo/domain'
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { pickLabel } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
@@ -25,7 +25,11 @@ export interface FindingsTreePickerProps {
|
||||
zone: FindingZone
|
||||
side?: LateralSide
|
||||
selected: Finding[]
|
||||
onChange: (next: Finding[]) => void
|
||||
/**
|
||||
* A leaf was ticked or unticked: its path and its position among the siblings shown.
|
||||
* The parent has the core build or remove the finding (R2).
|
||||
*/
|
||||
onToggle: (leafPath: string[], leafPosition: number) => void
|
||||
}
|
||||
|
||||
function isLeaf(node: TreeNode): boolean {
|
||||
@@ -69,13 +73,14 @@ function descriptionOf(node: TreeNode, locale: Locale): string | undefined {
|
||||
|
||||
/**
|
||||
* Drill-down picker over one finding zone of the sheet. A finding is keyed
|
||||
* by `(findingZoneId, path, side)`; labels are snapshotted at selection.
|
||||
* by `(findingZoneId, path, side)`; the core snapshots its labels when it
|
||||
* builds it. The selection predicates below only decide what is shown.
|
||||
*/
|
||||
export default function FindingsTreePicker({
|
||||
zone,
|
||||
side,
|
||||
selected,
|
||||
onChange,
|
||||
onToggle,
|
||||
}: FindingsTreePickerProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
@@ -125,25 +130,6 @@ export default function FindingsTreePicker({
|
||||
selected.filter((f) => matches(f) && pathStartsWith(f.path, nodePath))
|
||||
.length
|
||||
|
||||
function toggleLeaf(leafPath: string[], leaf: TreeNode) {
|
||||
if (isLeafSelected(leafPath)) {
|
||||
onChange(
|
||||
selected.filter((f) => !(matches(f) && samePath(f.path, leafPath))),
|
||||
)
|
||||
return
|
||||
}
|
||||
const next: Finding = {
|
||||
findingZoneId: zone.id,
|
||||
path: leafPath,
|
||||
labelFrSnapshot: leaf.name.fr,
|
||||
labelEnSnapshot: leaf.name.en,
|
||||
}
|
||||
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 (
|
||||
@@ -202,7 +188,7 @@ export default function FindingsTreePicker({
|
||||
{t('findings.no_options')}
|
||||
</li>
|
||||
) : (
|
||||
currentNodes.map((node) => {
|
||||
currentNodes.map((node, position) => {
|
||||
const nodePath = [...path, node.id]
|
||||
const nodeLabel = pickLabel(node.name, locale)
|
||||
const nodeDesc = descriptionOf(node, locale)
|
||||
@@ -215,7 +201,7 @@ export default function FindingsTreePicker({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isLeafSelected(nodePath)}
|
||||
onChange={() => toggleLeaf(nodePath, node)}
|
||||
onChange={() => onToggle(nodePath, position)}
|
||||
className="mt-1 accent-[var(--color-accent)]"
|
||||
aria-label={nodeLabel}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { LateralSide } from '@faunosteo/domain'
|
||||
import type { LateralSide } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface LateralityPickerProps {
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
LateralSide,
|
||||
Observation,
|
||||
ReportZone,
|
||||
} from '@faunosteo/domain'
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import { AnimatePresence, motion } from 'motion/react'
|
||||
import Card from '@/components/ui/Card'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
@@ -15,7 +15,8 @@ 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 { 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'
|
||||
@@ -96,7 +97,7 @@ function unresolvedFindings(
|
||||
sheet: SheetIndex,
|
||||
): Finding[] {
|
||||
return observation.findings.filter(
|
||||
(f) => !sheet.nodeAt(f.findingZoneId, f.path),
|
||||
(f) => !sheet.hasNode(f.findingZoneId, f.path),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -152,6 +153,23 @@ export default function ObservationCard({
|
||||
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(t('core.action_failed'))
|
||||
}
|
||||
const removeFinding = (target: Finding) =>
|
||||
onChange({
|
||||
...observation,
|
||||
@@ -379,11 +397,8 @@ export default function ObservationCard({
|
||||
zone={zone}
|
||||
side={side}
|
||||
selected={observation.findings}
|
||||
onChange={(next) =>
|
||||
onChange({
|
||||
...observation,
|
||||
findings: next,
|
||||
})
|
||||
onToggle={(path, leafPosition) =>
|
||||
toggleFinding(zone.id, side, path, leafPosition)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Observation } from '@faunosteo/domain'
|
||||
import type { Observation } from '@faunosteo/core-wasm/types'
|
||||
import ObservationCard from './ObservationCard'
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
|
||||
@@ -1,29 +1,39 @@
|
||||
import type { LateralSide, Observation } from '@faunosteo/domain'
|
||||
import type {
|
||||
LateralSide,
|
||||
Observation,
|
||||
Vertebra,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import VertebraPicker from '@/components/observation/VertebraPicker'
|
||||
import LateralityPicker from '@/components/observation/LateralityPicker'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
addSides,
|
||||
collectVertebrae,
|
||||
sidesPresent,
|
||||
syncVertebrae,
|
||||
type ZoneRef,
|
||||
} from '@/services/zoneInteraction'
|
||||
import { isObservable, type SheetIndex } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** The zone the vertebra picker edits, with its initial selection (computed on open). */
|
||||
export interface VertebraTarget {
|
||||
zoneIndex: number
|
||||
initial: Vertebra[]
|
||||
}
|
||||
|
||||
/** The bilateral annotation the laterality picker records sides for. */
|
||||
export interface LateralTarget {
|
||||
annotationId: string
|
||||
sidesPresent: LateralSide[]
|
||||
}
|
||||
|
||||
export interface ObservationPickersProps {
|
||||
sheet: SheetIndex
|
||||
activeIndex: number
|
||||
activeObs: Observation | undefined
|
||||
vertebraTarget: number | null
|
||||
lateralTarget: ZoneRef | null
|
||||
vertebraTarget: VertebraTarget | null
|
||||
lateralTarget: LateralTarget | null
|
||||
onCloseVertebra: () => void
|
||||
onCloseLateral: () => void
|
||||
}
|
||||
|
||||
/** Vertebra and laterality pickers of the active observation. */
|
||||
/** Vertebra and laterality pickers of the active observation; the core applies the result. */
|
||||
export default function ObservationPickers({
|
||||
sheet,
|
||||
activeIndex,
|
||||
@@ -37,12 +47,25 @@ export default function ObservationPickers({
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const updateObservation = useReportStore((s) => s.updateObservation)
|
||||
const vertebraZone =
|
||||
vertebraTarget !== null ? activeObs?.zones[vertebraTarget] : undefined
|
||||
vertebraTarget !== null
|
||||
? activeObs?.zones[vertebraTarget.zoneIndex]
|
||||
: undefined
|
||||
const vertebraAnnotation =
|
||||
vertebraZone && sheet.annotation(vertebraZone.annotationId)
|
||||
const lateralAnnotation =
|
||||
lateralTarget && sheet.annotation(lateralTarget.annotationId)
|
||||
|
||||
/** Applies a core-built observation to the fresh active one; alerts on failure. */
|
||||
function apply(
|
||||
run: (fresh: Observation) => ReturnType<SheetIndex['ops']['addSides']>,
|
||||
) {
|
||||
const fresh = useReportStore.getState().report?.observations[activeIndex]
|
||||
if (!fresh) return
|
||||
const outcome = run(fresh)
|
||||
if (outcome.ok) updateObservation(activeIndex, outcome.value)
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{vertebraTarget !== null &&
|
||||
@@ -53,17 +76,12 @@ export default function ObservationPickers({
|
||||
open
|
||||
onClose={onCloseVertebra}
|
||||
onConfirm={(vertebrae) => {
|
||||
const fresh =
|
||||
useReportStore.getState().report?.observations[activeIndex]
|
||||
if (fresh) {
|
||||
updateObservation(
|
||||
activeIndex,
|
||||
syncVertebrae(fresh, vertebrae, sheet, vertebraZone.viewId),
|
||||
)
|
||||
}
|
||||
apply((fresh) =>
|
||||
sheet.ops.syncVertebrae(fresh, vertebrae, vertebraZone.viewId),
|
||||
)
|
||||
onCloseVertebra()
|
||||
}}
|
||||
initial={collectVertebrae(activeObs, sheet, vertebraTarget)}
|
||||
initial={vertebraTarget.initial}
|
||||
regions={sheet.regions()}
|
||||
title={`${t('vertebra.title_prefix')}${pickLabel(vertebraAnnotation.name, locale)}`}
|
||||
initialRegion={
|
||||
@@ -77,15 +95,11 @@ export default function ObservationPickers({
|
||||
open
|
||||
onClose={onCloseLateral}
|
||||
title={pickLabel(sheet.name(lateralAnnotation), locale)}
|
||||
existingSides={sidesPresent(activeObs, lateralTarget)}
|
||||
existingSides={lateralTarget.sidesPresent}
|
||||
onSelect={(sides: LateralSide[]) => {
|
||||
const fresh =
|
||||
useReportStore.getState().report?.observations[activeIndex]
|
||||
if (fresh)
|
||||
updateObservation(
|
||||
activeIndex,
|
||||
addSides(fresh, lateralAnnotation, sides),
|
||||
)
|
||||
apply((fresh) =>
|
||||
sheet.ops.addSides(fresh, lateralTarget.annotationId, sides),
|
||||
)
|
||||
onCloseLateral()
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Severity } from '@faunosteo/domain'
|
||||
import type { Severity } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface SeveritySelectorProps {
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import type { Vertebra, VertebralRegion } from '@faunosteo/domain'
|
||||
import type {
|
||||
Vertebra,
|
||||
VertebraAction,
|
||||
VertebralRegion,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Chip from '@/components/ui/Chip'
|
||||
import { pickLabel } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { reportOps } from '@/core/reportOps'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
@@ -26,6 +31,8 @@ const sameVertebra = (a: Vertebra, r: string, i: number) =>
|
||||
* 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.
|
||||
* The selection rules (tap, check all, uncheck all) run in the core; the
|
||||
* grid extent and the chip state are display.
|
||||
*/
|
||||
export default function VertebraPicker({
|
||||
open,
|
||||
@@ -57,19 +64,17 @@ export default function VertebraPicker({
|
||||
|
||||
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) => !sameVertebra(v, r, i))
|
||||
: [...cur, { region: r, index: i }],
|
||||
)
|
||||
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))
|
||||
/** One tap, applied by the core to the selection the picker shows (R2). */
|
||||
const apply = (action: VertebraAction) => {
|
||||
const outcome = reportOps.selectVertebrae(selected, action)
|
||||
if (outcome.ok) setSelected(outcome.value)
|
||||
else window.alert(t('core.action_failed'))
|
||||
}
|
||||
const toggle = (region: string, index: number) =>
|
||||
apply({ kind: 'toggle', region, index })
|
||||
const all = (region: string, count: number) =>
|
||||
apply({ kind: 'all', region, count })
|
||||
const none = (region: string) => apply({ kind: 'none', region })
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={title} size="lg">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Animal, LocalizedText, Owner } from '@faunosteo/domain'
|
||||
import type { Animal, LocalizedText, Owner } from '@faunosteo/core-wasm/types'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Select from '@/components/ui/Select'
|
||||
import { pickLabel } from '@/services/sheetIndex'
|
||||
import { pickLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Textarea from '@/components/ui/Textarea'
|
||||
import NextAppointmentPicker from './NextAppointmentPicker'
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface CoreUnavailableProps {
|
||||
onRetry: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Degraded state of the sheet pages when the core module cannot run (CSP, network, an old
|
||||
* browser, a refused sheet): the session data stays where it is, the practitioner retries.
|
||||
*/
|
||||
export default function CoreUnavailable({ onRetry }: CoreUnavailableProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<main className="p-6 space-y-3 max-w-xl">
|
||||
<Notice tone="error">{t('sheet.core_unavailable')}</Notice>
|
||||
<Button onClick={onRetry}>{t('sheet.core_retry')}</Button>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
|
||||
import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import PractitionerForm from '@/components/report/PractitionerForm'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Label from '@/components/ui/Label'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Practitioner } from '@faunosteo/domain'
|
||||
import type { Practitioner } from '@faunosteo/core-wasm/types'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Input from '@/components/ui/Input'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { CoreOutcome } from '@faunosteo/core-wasm'
|
||||
import type {
|
||||
MoveDirection,
|
||||
NewReportDraft,
|
||||
Report,
|
||||
SheetRef,
|
||||
Vertebra,
|
||||
VertebraAction,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import { coreRuntime } from './runtime'
|
||||
|
||||
/**
|
||||
* The report rules that need no sheet (R2): creation and the observation list operations
|
||||
* of the store, the vertebra picker's selection. Ids and time come from the caller.
|
||||
*/
|
||||
|
||||
function run<T>(op: string, input: unknown): CoreOutcome<T> {
|
||||
return coreRuntime().call<T>(op, JSON.stringify(input))
|
||||
}
|
||||
|
||||
export interface NewReportInput {
|
||||
draft: NewReportDraft
|
||||
sheet: SheetRef
|
||||
id: string
|
||||
createdAt: string
|
||||
/** Id of the empty observation a draft without any starts with. */
|
||||
observationId: string
|
||||
}
|
||||
|
||||
export const reportOps = {
|
||||
newReport: (input: NewReportInput): CoreOutcome<Report> =>
|
||||
run('report.new', input),
|
||||
addObservation: (report: Report, id: string): CoreOutcome<Report> =>
|
||||
run('report.add_observation', { report, id }),
|
||||
removeObservation: (report: Report, index: number): CoreOutcome<Report> =>
|
||||
run('report.remove_observation', { report, index }),
|
||||
moveObservation: (
|
||||
report: Report,
|
||||
index: number,
|
||||
direction: MoveDirection,
|
||||
): CoreOutcome<Report> =>
|
||||
run('report.move_observation', { report, index, direction }),
|
||||
selectVertebrae: (
|
||||
selection: readonly Vertebra[],
|
||||
action: VertebraAction,
|
||||
): CoreOutcome<Vertebra[]> => run('vertebra.select', { selection, action }),
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import glueUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js?url'
|
||||
import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url'
|
||||
import {
|
||||
CoreRuntime,
|
||||
type CoreSource,
|
||||
type GlueModule,
|
||||
} from '@faunosteo/core-wasm'
|
||||
|
||||
/**
|
||||
* The application's core runtime (Rust compiled to WebAssembly, R2). Vite emits the glue
|
||||
* and the `.wasm` as hashed assets that no route chunk imports: nothing is fetched until a
|
||||
* sheet path or an import asks `ready()` (review III.3 rule 6). The production CSP must
|
||||
* carry `'wasm-unsafe-eval'` (DEPLOY.md); without it the load fails and the editor shows
|
||||
* the degraded state.
|
||||
*/
|
||||
|
||||
async function compileModule(): Promise<WebAssembly.Module> {
|
||||
const response = await fetch(wasmUrl)
|
||||
if (!response.ok) throw new Error(`core module HTTP ${response.status}`)
|
||||
try {
|
||||
// Needs `Content-Type: application/wasm`; any other type falls back to bytes.
|
||||
return await WebAssembly.compileStreaming(response.clone())
|
||||
} catch {
|
||||
return WebAssembly.compile(await response.arrayBuffer())
|
||||
}
|
||||
}
|
||||
|
||||
const browserSource: CoreSource = {
|
||||
compile: compileModule,
|
||||
// A distinct query per instance gives a new glue module record (R0 finding).
|
||||
importGlue: (instance) =>
|
||||
import(/* @vite-ignore */ `${glueUrl}?instance=${instance}`) as Promise<GlueModule>,
|
||||
}
|
||||
|
||||
let runtime: CoreRuntime | null = null
|
||||
|
||||
/** The page's runtime, created on first use. */
|
||||
export function coreRuntime(): CoreRuntime {
|
||||
runtime ??= new CoreRuntime(browserSource)
|
||||
return runtime
|
||||
}
|
||||
|
||||
/** Test seam: run the application on another runtime (the Node source in vitest). */
|
||||
export function setCoreRuntime(next: CoreRuntime): void {
|
||||
runtime = next
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { CoreOutcome, SheetSession } from '@faunosteo/core-wasm'
|
||||
import type {
|
||||
ArchiveImport,
|
||||
DraftRestore,
|
||||
LateralSide,
|
||||
Observation,
|
||||
Report,
|
||||
SheetSnapshot,
|
||||
Vertebra,
|
||||
ZoneClick,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* The sheet-bound rules of the editor, run by the core on the session's sheet (R2): one
|
||||
* call per user action or load, never in a render. Each returns the core's outcome; the
|
||||
* caller stops on `ok: false` (nothing is written, the action shows `core.action_failed`).
|
||||
*/
|
||||
|
||||
export interface FindingToggle {
|
||||
observation: Observation
|
||||
findingZoneId: string
|
||||
path: readonly string[]
|
||||
/** Position of the clicked leaf among the siblings the picker rendered. */
|
||||
leafPosition: number
|
||||
side?: LateralSide
|
||||
}
|
||||
|
||||
export class SheetOps {
|
||||
constructor(private readonly session: SheetSession) {}
|
||||
|
||||
private run<T>(op: string, input: unknown): CoreOutcome<T> {
|
||||
return this.session.call<T>(op, JSON.stringify(input))
|
||||
}
|
||||
|
||||
/** What a click on an annotation does to the active observation (the whole click chain). */
|
||||
zoneClick(
|
||||
observation: Observation | null,
|
||||
annotationId: string,
|
||||
): CoreOutcome<ZoneClick> {
|
||||
return this.run('zone.click', { observation, annotationId })
|
||||
}
|
||||
|
||||
addSides(
|
||||
observation: Observation,
|
||||
annotationId: string,
|
||||
sides: readonly LateralSide[],
|
||||
): CoreOutcome<Observation> {
|
||||
return this.run('zone.add_sides', { observation, annotationId, sides })
|
||||
}
|
||||
|
||||
removeZoneAt(observation: Observation, index: number): CoreOutcome<Observation> {
|
||||
return this.run('zone.remove_at', { observation, index })
|
||||
}
|
||||
|
||||
/** The vertebra picker's initial selection, the zone at `index` first. */
|
||||
vertebraInitial(
|
||||
observation: Observation,
|
||||
index: number,
|
||||
): CoreOutcome<Vertebra[]> {
|
||||
return this.run('vertebra.initial', { observation, index })
|
||||
}
|
||||
|
||||
syncVertebrae(
|
||||
observation: Observation,
|
||||
selection: readonly Vertebra[],
|
||||
viewId: string,
|
||||
): CoreOutcome<Observation> {
|
||||
return this.run('vertebra.sync', { observation, selection, viewId })
|
||||
}
|
||||
|
||||
toggleFinding(toggle: FindingToggle): CoreOutcome<Observation> {
|
||||
return this.run('finding.toggle', toggle)
|
||||
}
|
||||
|
||||
/** Reads the tab's draft (and the archive kept beside it) and rebases it on this sheet. */
|
||||
restoreDraft(
|
||||
draft: string,
|
||||
archive: string | null,
|
||||
): CoreOutcome<DraftRestore> {
|
||||
return this.run('draft.restore', { draft, archive })
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a PDF attachment (any supported shape, as the byte scan parsed it) and rebases
|
||||
* it on this sheet. Failures: `incompatible_version` (with `found`), `no_attachment`.
|
||||
*/
|
||||
importArchive(attachment: unknown): CoreOutcome<ArchiveImport> {
|
||||
return this.run('archive.import', attachment)
|
||||
}
|
||||
|
||||
/** The snapshot of this sheet an archive of `report` carries. */
|
||||
snapshot(report: Report): CoreOutcome<SheetSnapshot> {
|
||||
return this.run('archive.snapshot', { report })
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ export const en: Dict = {
|
||||
'Reopen a previous report generated by this app to follow up.',
|
||||
'home.import.cta': 'Choose a PDF',
|
||||
'home.import.loading': 'Reading…',
|
||||
'home.import.error_core_unavailable':
|
||||
'The reading engine could not be loaded. Try the import again.',
|
||||
'home.import.error_generic': 'Failed to read the PDF.',
|
||||
'home.import.error_invalid_pdf': 'This file is not a readable PDF.',
|
||||
'home.import.error_no_attachment':
|
||||
@@ -76,6 +78,8 @@ export const en: Dict = {
|
||||
'PDF exported with missing elements: {items}. Check the browser console.',
|
||||
'editor.draft_rebased':
|
||||
'Draft restored on an anatomical sheet different from the one it was created on. Items not found: {count} (kept with their labels).',
|
||||
'editor.draft_quarantined':
|
||||
"This tab's draft could not be read by this version of Faunosteo. It was set aside, not deleted.",
|
||||
'editor.edit_infos': 'Edit info',
|
||||
'editor.edit_dialog_title': 'Edit information',
|
||||
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
|
||||
@@ -152,6 +156,11 @@ export const en: Dict = {
|
||||
'Anatomical sheet: reference draft, not medically validated',
|
||||
'sheet.status.published': 'Official anatomical sheet',
|
||||
'sheet.loading': 'Loading the anatomical sheet…',
|
||||
'sheet.core_unavailable':
|
||||
"Faunosteo's computation engine could not be loaded. Your session data is kept.",
|
||||
'sheet.core_retry': 'Retry',
|
||||
'core.action_failed':
|
||||
'This action could not be applied. Try again; your report was not changed.',
|
||||
|
||||
// unresolved (migrated) data
|
||||
'observation.unresolved_short': 'inherited',
|
||||
|
||||
@@ -26,6 +26,8 @@ export const fr: Dict = {
|
||||
'Reprendre un bilan précédent généré par cette application pour effectuer un suivi.',
|
||||
'home.import.cta': 'Choisir un PDF',
|
||||
'home.import.loading': 'Lecture…',
|
||||
'home.import.error_core_unavailable':
|
||||
"Le moteur de lecture n'a pas pu être chargé. Réessayez l'import.",
|
||||
'home.import.error_generic': 'Erreur de lecture du PDF.',
|
||||
'home.import.error_invalid_pdf': "Ce fichier n'est pas un PDF lisible.",
|
||||
'home.import.error_no_attachment':
|
||||
@@ -82,6 +84,8 @@ export const fr: Dict = {
|
||||
'PDF exporté avec des éléments manquants : {items}. Vérifiez la console du navigateur.',
|
||||
'editor.draft_rebased':
|
||||
'Brouillon restauré sur une fiche anatomique différente de celle où il a été créé. Éléments non retrouvés : {count} (conservés avec leurs libellés).',
|
||||
'editor.draft_quarantined':
|
||||
"Le brouillon de cet onglet n'a pas pu être relu par cette version de Faunosteo. Il a été mis de côté, pas supprimé.",
|
||||
'editor.edit_infos': 'Modifier les infos',
|
||||
'editor.edit_dialog_title': 'Modifier les informations',
|
||||
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
|
||||
@@ -166,6 +170,11 @@ export const fr: Dict = {
|
||||
'Fiche anatomique : brouillon de référence, non validé médicalement',
|
||||
'sheet.status.published': 'Fiche anatomique officielle',
|
||||
'sheet.loading': 'Chargement de la fiche anatomique…',
|
||||
'sheet.core_unavailable':
|
||||
"Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées.",
|
||||
'sheet.core_retry': 'Réessayer',
|
||||
'core.action_failed':
|
||||
"Cette action n'a pas pu être appliquée. Réessayez ; votre bilan n'a pas été modifié.",
|
||||
|
||||
// unresolved (migrated) data
|
||||
'observation.unresolved_short': 'hérité',
|
||||
|
||||
@@ -14,3 +14,11 @@ export function pickLocaleLabel(
|
||||
if (locale === 'en') return en || fr || fallback
|
||||
return fr || en || fallback
|
||||
}
|
||||
|
||||
/** The same rule for a `{ fr, en }` label of the sheet or a snapshot ('' when absent). */
|
||||
export function pickLabel(
|
||||
text: { fr?: string; en?: string } | null | undefined,
|
||||
locale: Locale,
|
||||
): string {
|
||||
return pickLocaleLabel(text?.fr, text?.en, locale)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Branding, ImageAsset } from '@faunosteo/domain'
|
||||
import type { Branding, ImageAsset } from '@faunosteo/core-wasm/types'
|
||||
import headerLogoDataUrl from '@/assets/brand/faunosteo-logo-horizontal-512.png?inline'
|
||||
import footerLogoDataUrl from '@/assets/brand/faunosteo-horizontal-com-512.png?inline'
|
||||
import poweredByLogoDataUrl from '@/assets/brand/zenquality-logo-fr.png?inline'
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
|
||||
import type { Report } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
defaultPdfLabels,
|
||||
exportReportArchive,
|
||||
type ExportInput,
|
||||
type ExportWarning,
|
||||
} from '@faunosteo/pdf'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
@@ -20,19 +21,24 @@ export interface PdfExportResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports the report as an archive PDF through the engine: the loaded sheet
|
||||
* becomes the snapshot the pages are drawn from and the attachment carries,
|
||||
* the branding comes from the bundled logos, the browser rasterises the
|
||||
* views. Warnings are logged and returned for the caller to surface.
|
||||
* Exports the report as an archive PDF through the engine: the core builds
|
||||
* the snapshot of the loaded sheet the pages are drawn from and the
|
||||
* attachment carries (R2), the branding comes from the bundled logos, the
|
||||
* browser rasterises the views, the TypeScript engine writes the file (the
|
||||
* writer moves to the core at R4). The core's report and snapshot are the
|
||||
* same JSON contracts the engine's Zod types describe. Warnings are logged
|
||||
* and returned for the caller to surface.
|
||||
*/
|
||||
export async function exportReportToPdf(
|
||||
report: Report,
|
||||
index: SheetIndex,
|
||||
opts: PdfExportOptions,
|
||||
): Promise<PdfExportResult> {
|
||||
const snapshot = index.ops.snapshot(report)
|
||||
if (!snapshot.ok) throw new Error(`snapshot failed: ${snapshot.kind}`)
|
||||
const result = await exportReportArchive({
|
||||
report,
|
||||
sheet: buildSheetSnapshot(index.sheet, report),
|
||||
report: report as ExportInput['report'],
|
||||
sheet: snapshot.value as ExportInput['sheet'],
|
||||
branding: await loadBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: opts.locale,
|
||||
|
||||
+42
-11
@@ -1,13 +1,14 @@
|
||||
import type { ArchiveReadOutcome, ReportMigrationMap } from '@faunosteo/domain'
|
||||
import type { ArchiveImport } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
ArchiveReadError,
|
||||
readReportArchive,
|
||||
readAttachedDocument,
|
||||
type ArchiveReadErrorKind,
|
||||
} from '@faunosteo/pdf'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
|
||||
export { MAX_PDF_BYTES } from '@faunosteo/pdf'
|
||||
|
||||
export type ImportErrorKind = ArchiveReadErrorKind
|
||||
export type ImportErrorKind = ArchiveReadErrorKind | 'core_unavailable'
|
||||
|
||||
/**
|
||||
* Localization-agnostic import error. Carries a kind discriminant + an
|
||||
@@ -25,17 +26,13 @@ export class ImportError extends Error {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a Faunosteo PDF back through the engine: the report (v3 as is, v2
|
||||
* migrated through the sheet's map) and, when the file is a Step 6 archive,
|
||||
* the validated envelope or the reason its snapshot was dropped. Engine
|
||||
* Step 1, no core needed: the JSON a Faunosteo PDF carries, located by the
|
||||
* engine's byte scan (BLK-009; the scanner moves to the core at R4). Engine
|
||||
* failures become ImportError kinds, one to one.
|
||||
*/
|
||||
export async function importReportFromPdf(
|
||||
pdfBytes: Uint8Array,
|
||||
map: ReportMigrationMap,
|
||||
): Promise<ArchiveReadOutcome> {
|
||||
export async function readAttachment(pdfBytes: Uint8Array): Promise<unknown> {
|
||||
try {
|
||||
return await readReportArchive(pdfBytes, map)
|
||||
return await readAttachedDocument(pdfBytes)
|
||||
} catch (err) {
|
||||
if (err instanceof ArchiveReadError) {
|
||||
throw new ImportError(err.kind, err.foundVersion)
|
||||
@@ -43,3 +40,37 @@ export async function importReportFromPdf(
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 2, in the core on the loaded sheet: the layered reading of the
|
||||
* attachment (report first, v2 migrated through the sheet's map, then the
|
||||
* envelope kept or its snapshot dropped with a reason) and the rebase onto
|
||||
* that sheet. An unknown numeric report version is `incompatible_version`,
|
||||
* any other unreadable content `no_attachment`, as the engine reported them.
|
||||
*/
|
||||
export function importAttachment(
|
||||
attachment: unknown,
|
||||
index: SheetIndex,
|
||||
): ArchiveImport {
|
||||
const outcome = index.ops.importArchive(attachment)
|
||||
if (outcome.ok) return outcome.value
|
||||
switch (outcome.kind) {
|
||||
case 'incompatible_version':
|
||||
throw new ImportError('incompatible_version', outcome.found ?? null)
|
||||
case 'no_attachment':
|
||||
throw new ImportError('no_attachment')
|
||||
case 'core_unavailable':
|
||||
case 'internal':
|
||||
throw new ImportError('core_unavailable')
|
||||
default:
|
||||
throw new Error(`import failed: ${outcome.kind}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Both steps on a sheet already loaded in the core. */
|
||||
export async function importReportFromPdf(
|
||||
pdfBytes: Uint8Array,
|
||||
index: SheetIndex,
|
||||
): Promise<ArchiveImport> {
|
||||
return importAttachment(await readAttachment(pdfBytes), index)
|
||||
}
|
||||
@@ -1,11 +1,109 @@
|
||||
import type { SheetIndex as DomainSheetIndex } from '@faunosteo/domain'
|
||||
import type { LoadedSheet } from '@/sheets/provider'
|
||||
import type {
|
||||
Annotation,
|
||||
AnatomicalSheetDocument,
|
||||
FindingZone,
|
||||
LocalizedText,
|
||||
ObservableAnnotation,
|
||||
SheetIndexData,
|
||||
SheetRef,
|
||||
SheetStatus,
|
||||
SheetView,
|
||||
VertebralRegion,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import type { SheetOps } from '@/core/sheetOps'
|
||||
|
||||
/**
|
||||
* The sheet index lives in @faunosteo/domain since Step 6 (shared with the
|
||||
* PDF engine). This shim keeps the app's import path and binds the index to
|
||||
* the sheet the app loads, so `index.sheet` still carries the migration map.
|
||||
* The loaded sheet as React reads it (R2). Every lookup table is computed once by the
|
||||
* core (`SheetIndexData`): positions by id with the TypeScript `Map` semantics (last
|
||||
* duplicate wins), names, spine ids and the finding paths that exist. This class only reads
|
||||
* them, so no render calls the core; the sheet-bound rules go through `ops`.
|
||||
*/
|
||||
export { buildSheetIndex, isObservable, pickLabel } from '@faunosteo/domain'
|
||||
export type { ObservableAnnotation } from '@faunosteo/domain'
|
||||
export type SheetIndex = DomainSheetIndex<LoadedSheet>
|
||||
|
||||
export type { ObservableAnnotation }
|
||||
|
||||
/** What the screens read about the loaded sheet. */
|
||||
export interface LoadedSheetView {
|
||||
status: SheetStatus
|
||||
ref: SheetRef
|
||||
speciesId: string
|
||||
schemaVersion: number
|
||||
/** The document as the core parsed it (defaults filled in). */
|
||||
document: AnatomicalSheetDocument
|
||||
/** SVG text by `svg_asset_id` (the canvas draws them until R3). */
|
||||
assets: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
function at<T>(
|
||||
list: readonly T[],
|
||||
positions: Readonly<Record<string, number>>,
|
||||
id: string,
|
||||
): T | undefined {
|
||||
return Object.hasOwn(positions, id) ? list[positions[id]!] : undefined
|
||||
}
|
||||
|
||||
export function isObservable(
|
||||
a: Annotation | undefined,
|
||||
): a is ObservableAnnotation {
|
||||
return a !== undefined && a.kind !== 'detail_trigger'
|
||||
}
|
||||
|
||||
export class SheetIndex {
|
||||
readonly sheet: LoadedSheetView
|
||||
/** The first `main` view of the document. */
|
||||
readonly mainViewId: string
|
||||
private readonly spine: ReadonlySet<string>
|
||||
private readonly nodes: ReadonlySet<string>
|
||||
|
||||
constructor(
|
||||
private readonly data: SheetIndexData,
|
||||
assets: Readonly<Record<string, string>>,
|
||||
readonly ops: SheetOps,
|
||||
) {
|
||||
const { document } = data
|
||||
this.sheet = {
|
||||
status: data.status,
|
||||
ref: data.ref,
|
||||
speciesId: data.speciesId,
|
||||
schemaVersion: data.schemaVersion,
|
||||
document,
|
||||
assets,
|
||||
}
|
||||
this.mainViewId = data.mainViewId
|
||||
this.spine = new Set(data.spineIds)
|
||||
this.nodes = new Set(data.nodeKeys)
|
||||
}
|
||||
|
||||
view(id: string): SheetView | undefined {
|
||||
return at(this.data.document.views, this.data.viewById, id)
|
||||
}
|
||||
|
||||
annotation(id: string): Annotation | undefined {
|
||||
return at(this.data.document.annotations, this.data.annotationById, id)
|
||||
}
|
||||
|
||||
findingZone(id: string): FindingZone | undefined {
|
||||
return at(this.data.document.finding_zones, this.data.findingZoneById, id)
|
||||
}
|
||||
|
||||
regions(): VertebralRegion[] {
|
||||
return this.data.document.vertebral_config.regions
|
||||
}
|
||||
|
||||
/** Whether an annotation opens the vertebra picker. */
|
||||
isSpine(annotationId: string): boolean {
|
||||
return this.spine.has(annotationId)
|
||||
}
|
||||
|
||||
/** The name the sheet gives an annotation (a trigger: its own or its view's). */
|
||||
name(annotation: Annotation): LocalizedText {
|
||||
const names = this.data.names
|
||||
return Object.hasOwn(names, annotation.id)
|
||||
? names[annotation.id]!
|
||||
: { fr: '', en: '' }
|
||||
}
|
||||
|
||||
/** Whether the finding zone holds this category or node path. */
|
||||
hasNode(zoneId: string, path: readonly string[]): boolean {
|
||||
return this.nodes.has(JSON.stringify([zoneId, ...path]))
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,17 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
ReportMigrationMapSchema,
|
||||
type AnatomicalSheetDocument,
|
||||
type ReportMigrationMap,
|
||||
type SheetRef,
|
||||
} from '@faunosteo/domain'
|
||||
import type { LocalizedText, SheetRef } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* Where the application gets the anatomical sheet it works on. Step 5 ships
|
||||
* one implementation, the sheet bundled at build time (virtual module, see
|
||||
* vite/sheet-bundle.ts); the Supabase implementation of Step 13 sits behind
|
||||
* the same interface. A loaded sheet is immutable for the session.
|
||||
* the same interface. The payload is handed to the core as it is: the core
|
||||
* parses the document and the migration map (R2). A loaded sheet is
|
||||
* immutable for the session.
|
||||
*/
|
||||
|
||||
export type SheetStatus = 'draft' | 'published'
|
||||
|
||||
/** Raw payload of the virtual module, validated here before use. */
|
||||
/** Raw payload of the virtual module, parsed by the core (`SheetHandle`). */
|
||||
export interface BundledSheetData {
|
||||
status: SheetStatus
|
||||
ref: {
|
||||
@@ -32,56 +28,53 @@ export interface BundledSheetData {
|
||||
assetHashes: Record<string, string>
|
||||
}
|
||||
|
||||
export interface LoadedSheet {
|
||||
status: SheetStatus
|
||||
export interface SheetProvider {
|
||||
/** The reference sheet payload of a species, or null when none is available. */
|
||||
getReferenceSheet(speciesId: string): Promise<BundledSheetData | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* What the pages that only offer to start or import a report show, read from the payload
|
||||
* without the core: the reference a new report is stamped with and the species name.
|
||||
*/
|
||||
export interface SheetAvailability {
|
||||
ref: SheetRef
|
||||
speciesId: string
|
||||
/** Document schema version of the sheet (`ref.schema_version`). */
|
||||
schemaVersion: number
|
||||
document: AnatomicalSheetDocument
|
||||
/** SVG text by `svg_asset_id`. */
|
||||
assets: Readonly<Record<string, string>>
|
||||
/** sha256 by `svg_asset_id`; carried into a report archive as provenance. */
|
||||
assetHashes: Readonly<Record<string, string>>
|
||||
migrationMap: ReportMigrationMap
|
||||
name: LocalizedText
|
||||
}
|
||||
|
||||
export interface SheetProvider {
|
||||
/** The reference sheet of a species, or null when none is available. */
|
||||
getReferenceSheet(speciesId: string): Promise<LoadedSheet | null>
|
||||
}
|
||||
|
||||
export function parseBundledSheet(data: BundledSheetData): LoadedSheet {
|
||||
const document = AnatomicalSheetDocumentSchema.parse(data.document)
|
||||
const migrationMap = ReportMigrationMapSchema.parse(data.migrationMap)
|
||||
export function availabilityOf(data: BundledSheetData): SheetAvailability {
|
||||
const document = data.document as { name: LocalizedText }
|
||||
return {
|
||||
status: data.status,
|
||||
ref: {
|
||||
sheetId: data.ref.sheet_id,
|
||||
versionId: data.ref.version_id,
|
||||
documentSha256: data.ref.document_sha256,
|
||||
},
|
||||
speciesId: data.ref.species_id,
|
||||
schemaVersion: data.ref.schema_version,
|
||||
document,
|
||||
assets: data.assets,
|
||||
assetHashes: data.assetHashes,
|
||||
migrationMap,
|
||||
name: document.name,
|
||||
}
|
||||
}
|
||||
|
||||
let cached: Promise<LoadedSheet | null> | null = null
|
||||
let cached: Promise<BundledSheetData | null> | null = null
|
||||
|
||||
async function loadBundled(): Promise<LoadedSheet | null> {
|
||||
async function loadBundled(): Promise<BundledSheetData | null> {
|
||||
const mod = await import('virtual:faunosteo-sheet')
|
||||
return mod.bundledSheet ? parseBundledSheet(mod.bundledSheet) : null
|
||||
return mod.bundledSheet
|
||||
}
|
||||
|
||||
export const bundledSheetProvider: SheetProvider = {
|
||||
async getReferenceSheet(speciesId) {
|
||||
cached ??= loadBundled()
|
||||
const sheet = await cached
|
||||
return sheet && sheet.speciesId === speciesId ? sheet : null
|
||||
let sheet: BundledSheetData | null
|
||||
try {
|
||||
sheet = await cached
|
||||
} catch (error) {
|
||||
// A failed chunk load is not remembered: the next attempt fetches again.
|
||||
cached = null
|
||||
throw error
|
||||
}
|
||||
return sheet && sheet.ref.species_id === speciesId ? sheet : null
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+105
-12
@@ -1,20 +1,40 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { buildSheetIndex, type SheetIndex } from '@/services/sheetIndex'
|
||||
import { bundledSheetProvider, type SheetProvider } from './provider'
|
||||
import type { SheetIndexData } from '@faunosteo/core-wasm/types'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import { SheetOps } from '@/core/sheetOps'
|
||||
import { SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
availabilityOf,
|
||||
bundledSheetProvider,
|
||||
type SheetAvailability,
|
||||
type SheetProvider,
|
||||
} from './provider'
|
||||
|
||||
/**
|
||||
* The reference sheet of a species for the current session, loaded once
|
||||
* through the provider and indexed. `none` means the build carries no sheet
|
||||
* (production bundle without SHEET_BUNDLE=draft) or no sheet for the species.
|
||||
* The reference sheet of a species for the current session. `useSheet` loads it into the
|
||||
* core (the editor, the import): `none` means the build carries no sheet (production
|
||||
* bundle without SHEET_BUNDLE=draft) or none for the species; `core_unavailable` means the
|
||||
* module could not be loaded (CSP, network, old browser) and `invalid_sheet` that the
|
||||
* bundled payload was refused, both with a `retry`. `useSheetAvailability` reads the
|
||||
* payload alone, without the core, for the pages that only offer to start a report.
|
||||
*/
|
||||
|
||||
export type SheetLoad =
|
||||
| { status: 'none' }
|
||||
| { status: 'ready'; index: SheetIndex }
|
||||
| { status: 'core_unavailable' }
|
||||
| { status: 'invalid_sheet' }
|
||||
|
||||
export type SheetState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'none' }
|
||||
| { status: 'ready'; index: SheetIndex }
|
||||
| { status: 'core_unavailable'; retry: () => void }
|
||||
| { status: 'invalid_sheet'; retry: () => void }
|
||||
|
||||
let provider: SheetProvider = bundledSheetProvider
|
||||
const cache = new Map<string, Promise<SheetIndex | null>>()
|
||||
/** Settled loads only (`ready`, `none`): a failure is never remembered. */
|
||||
const cache = new Map<string, Promise<SheetLoad>>()
|
||||
|
||||
/** Test seam: swap the provider and forget loaded sheets. */
|
||||
export function setSheetProvider(next: SheetProvider): void {
|
||||
@@ -22,19 +42,48 @@ export function setSheetProvider(next: SheetProvider): void {
|
||||
cache.clear()
|
||||
}
|
||||
|
||||
export function loadSheetIndex(speciesId: string): Promise<SheetIndex | null> {
|
||||
async function loadIntoCore(speciesId: string): Promise<SheetLoad> {
|
||||
const bundle = await provider.getReferenceSheet(speciesId)
|
||||
if (!bundle) return { status: 'none' }
|
||||
if (!(await coreRuntime().ready())) return { status: 'core_unavailable' }
|
||||
const session = coreRuntime().sheet(JSON.stringify(bundle))
|
||||
const data = session.call<SheetIndexData>('index_data', '')
|
||||
if (data.ok) {
|
||||
const index = new SheetIndex(data.value, bundle.assets, new SheetOps(session))
|
||||
return { status: 'ready', index }
|
||||
}
|
||||
return {
|
||||
status: data.kind === 'invalid_sheet' ? 'invalid_sheet' : 'core_unavailable',
|
||||
}
|
||||
}
|
||||
|
||||
/** The species' sheet in the core; failures are retried on the next call. */
|
||||
export function loadSheet(speciesId: string): Promise<SheetLoad> {
|
||||
let pending = cache.get(speciesId)
|
||||
if (!pending) {
|
||||
pending = provider
|
||||
.getReferenceSheet(speciesId)
|
||||
.then((sheet) => (sheet ? buildSheetIndex(sheet) : null))
|
||||
pending = loadIntoCore(speciesId).catch(
|
||||
(): SheetLoad => ({ status: 'core_unavailable' }),
|
||||
)
|
||||
cache.set(speciesId, pending)
|
||||
void pending.then((load) => {
|
||||
const settled = load.status === 'ready' || load.status === 'none'
|
||||
if (!settled) cache.delete(speciesId)
|
||||
})
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
/** The ready index, or null (tests and callers that need the sheet or nothing). */
|
||||
export async function loadSheetIndex(
|
||||
speciesId: string,
|
||||
): Promise<SheetIndex | null> {
|
||||
const load = await loadSheet(speciesId)
|
||||
return load.status === 'ready' ? load.index : null
|
||||
}
|
||||
|
||||
export function useSheet(speciesId: string | undefined): SheetState {
|
||||
const [state, setState] = useState<SheetState>({ status: 'loading' })
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
if (!speciesId) {
|
||||
@@ -42,13 +91,57 @@ export function useSheet(speciesId: string | undefined): SheetState {
|
||||
return
|
||||
}
|
||||
setState({ status: 'loading' })
|
||||
loadSheetIndex(speciesId).then((index) => {
|
||||
const retry = () => {
|
||||
void coreRuntime()
|
||||
.retry()
|
||||
.finally(() => setAttempt((n) => n + 1))
|
||||
}
|
||||
void loadSheet(speciesId).then((load) => {
|
||||
if (cancelled) return
|
||||
setState(index ? { status: 'ready', index } : { status: 'none' })
|
||||
if (load.status === 'ready' || load.status === 'none') setState(load)
|
||||
else if (load.status === 'invalid_sheet') setState({ status: load.status, retry })
|
||||
else setState({ status: 'core_unavailable', retry })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [speciesId, attempt])
|
||||
return state
|
||||
}
|
||||
|
||||
export type SheetAvailabilityState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'none' }
|
||||
| { status: 'ready'; sheet: SheetAvailability }
|
||||
|
||||
/** Whether the build carries a sheet for the species, without loading the core. */
|
||||
export function useSheetAvailability(
|
||||
speciesId: string | undefined,
|
||||
): SheetAvailabilityState {
|
||||
const [state, setState] = useState<SheetAvailabilityState>({
|
||||
status: 'loading',
|
||||
})
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
if (!speciesId) {
|
||||
setState({ status: 'none' })
|
||||
return
|
||||
}
|
||||
void provider
|
||||
.getReferenceSheet(speciesId)
|
||||
.then((bundle) => {
|
||||
if (cancelled) return
|
||||
setState(
|
||||
bundle
|
||||
? { status: 'ready', sheet: availabilityOf(bundle) }
|
||||
: { status: 'none' },
|
||||
)
|
||||
})
|
||||
// A failed chunk load leaves the page loading, as before R2; a reload fetches again.
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [speciesId])
|
||||
return state
|
||||
}
|
||||
@@ -1,33 +1,39 @@
|
||||
import {
|
||||
readReportDocument,
|
||||
ReportArchiveEnvelopeSchema,
|
||||
type Report,
|
||||
type ReportArchiveEnvelope,
|
||||
type ReportMigrationMap,
|
||||
} from '@faunosteo/domain'
|
||||
import type { Report, ReportArchiveEnvelope } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* Where the session lives between renders. The report draft is mirrored on
|
||||
* every change; the archive an import brought along (the envelope of a
|
||||
* Step 6 PDF) is written only when the session starts or ends, so a stale
|
||||
* draft can still be rebased with the labels of its original sheet. One
|
||||
* implementation today (per-tab sessionStorage); the Supabase and outbox
|
||||
* adapters of later steps implement the same interfaces.
|
||||
* draft can still be rebased with the labels of its original sheet. The
|
||||
* texts are read raw: the core parses them (R2), and a text the running
|
||||
* build cannot read is set aside under a quarantine key instead of being
|
||||
* dropped. One implementation today (per-tab sessionStorage); the Supabase
|
||||
* and outbox adapters of later steps implement the same interfaces.
|
||||
*/
|
||||
|
||||
export interface ReportPersistence {
|
||||
load(map: ReportMigrationMap): Report | null
|
||||
/** The raw draft text, null when there is none. */
|
||||
loadText(): string | null
|
||||
save(report: Report | null): void
|
||||
}
|
||||
|
||||
export interface ArchivePersistence {
|
||||
load(): ReportArchiveEnvelope | null
|
||||
loadText(): string | null
|
||||
save(archive: ReportArchiveEnvelope | null): void
|
||||
}
|
||||
|
||||
export const DRAFT_KEY = 'osteo:draft'
|
||||
export const ARCHIVE_KEY = 'osteo:archive'
|
||||
|
||||
/** Unreadable texts and the pre-rebase draft, newest only (R2 plan rev 2). */
|
||||
export const QUARANTINE_KEYS = {
|
||||
draft: 'osteo:quarantine:draft',
|
||||
archive: 'osteo:quarantine:archive',
|
||||
draftPreRebase: 'osteo:quarantine:draft-pre-rebase',
|
||||
} as const
|
||||
|
||||
export type QuarantineSlot = keyof typeof QUARANTINE_KEYS
|
||||
|
||||
function storage(): Storage | null {
|
||||
return typeof sessionStorage === 'undefined' ? null : sessionStorage
|
||||
}
|
||||
@@ -47,33 +53,37 @@ function writeOrRemove(key: string, value: unknown): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies `raw` into its quarantine slot, then removes `source` (when given)
|
||||
* only if that copy succeeded: a full storage keeps the text where it was.
|
||||
* Returns whether the text is now in quarantine.
|
||||
*/
|
||||
export function quarantine(
|
||||
slot: QuarantineSlot,
|
||||
raw: string,
|
||||
source?: string,
|
||||
): boolean {
|
||||
const store = storage()
|
||||
if (!store) return false
|
||||
try {
|
||||
store.setItem(QUARANTINE_KEYS[slot], raw)
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
|
||||
return false
|
||||
}
|
||||
if (source) store.removeItem(source)
|
||||
return true
|
||||
}
|
||||
|
||||
export const sessionStoragePersistence: ReportPersistence = {
|
||||
load(map) {
|
||||
const raw = storage()?.getItem(DRAFT_KEY)
|
||||
if (!raw) return null
|
||||
try {
|
||||
return readReportDocument(JSON.parse(raw), map).report
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV) console.warn('osteo:draft ignored', err)
|
||||
return null
|
||||
}
|
||||
},
|
||||
loadText: () => storage()?.getItem(DRAFT_KEY) ?? null,
|
||||
save(report) {
|
||||
writeOrRemove(DRAFT_KEY, report)
|
||||
},
|
||||
}
|
||||
|
||||
export const sessionStorageArchivePersistence: ArchivePersistence = {
|
||||
load() {
|
||||
const raw = storage()?.getItem(ARCHIVE_KEY)
|
||||
if (!raw) return null
|
||||
try {
|
||||
const parsed = ReportArchiveEnvelopeSchema.safeParse(JSON.parse(raw))
|
||||
return parsed.success ? parsed.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
loadText: () => storage()?.getItem(ARCHIVE_KEY) ?? null,
|
||||
save(archive) {
|
||||
writeOrRemove(ARCHIVE_KEY, archive)
|
||||
},
|
||||
|
||||
@@ -1,4 +1,17 @@
|
||||
import { PractitionerSchema, type Practitioner } from '@faunosteo/domain'
|
||||
import { z } from 'zod'
|
||||
import type { Practitioner } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* Prefill of the practitioner form (D-R7: form validation stays TypeScript, the core is
|
||||
* not loaded on the new-report page): the cached value is used only when it still has the
|
||||
* shape of the report's practitioner (name required, the rest optional text).
|
||||
*/
|
||||
const CachedPractitionerSchema: z.ZodType<Practitioner> = z.object({
|
||||
name: z.string().min(1),
|
||||
cabinet: z.string().optional(),
|
||||
contact: z.string().optional(),
|
||||
siret: z.string().optional(),
|
||||
})
|
||||
|
||||
const STORAGE_KEY = 'osteo:lastPractitioner'
|
||||
|
||||
@@ -8,7 +21,7 @@ export function readCachedPractitioner(): Practitioner | undefined {
|
||||
if (!raw) return undefined
|
||||
try {
|
||||
const data = JSON.parse(raw)
|
||||
const parsed = PractitionerSchema.safeParse(data)
|
||||
const parsed = CachedPractitionerSchema.safeParse(data)
|
||||
return parsed.success ? parsed.data : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
|
||||
+149
-123
@@ -1,21 +1,25 @@
|
||||
import { create } from 'zustand'
|
||||
import {
|
||||
rebaseReportOnSheet,
|
||||
REPORT_VERSION,
|
||||
type Animal,
|
||||
type NextAppointment,
|
||||
type Observation,
|
||||
type Owner,
|
||||
type Practitioner,
|
||||
type RebaseOutcome,
|
||||
type Report,
|
||||
type ReportArchiveEnvelope,
|
||||
type SheetRef,
|
||||
} from '@faunosteo/domain'
|
||||
import type {
|
||||
Animal,
|
||||
NewReportDraft,
|
||||
NextAppointment,
|
||||
Observation,
|
||||
Owner,
|
||||
Practitioner,
|
||||
RebaseOutcome,
|
||||
Report,
|
||||
ReportArchiveEnvelope,
|
||||
SheetRef,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import type { CoreOutcome } from '@faunosteo/core-wasm'
|
||||
import { reportOps } from '@/core/reportOps'
|
||||
import { generateId } from '@/lib/id'
|
||||
import { nowIso } from '@/lib/dates'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import {
|
||||
ARCHIVE_KEY,
|
||||
DRAFT_KEY,
|
||||
quarantine,
|
||||
sessionStorageArchivePersistence,
|
||||
sessionStoragePersistence,
|
||||
type ArchivePersistence,
|
||||
@@ -23,45 +27,60 @@ import {
|
||||
} from './persistence'
|
||||
|
||||
/**
|
||||
* In-memory report document (v3) and its editing actions. Observation-level
|
||||
* zone rules live in services/zoneInteraction; the store only replaces
|
||||
* documents. The per-tab draft is mirrored through the persistence adapter
|
||||
* and restored once the sheet is known; a draft written on another revision
|
||||
* of the sheet is rebased on restore. The archive an import brought along
|
||||
* (STEP6 §14 "App session") is kept beside the report for later operations
|
||||
* and written only when the session starts or ends.
|
||||
* In-memory report document (v3) and its editing actions. Every report that
|
||||
* enters the store comes from the core (R2): a new report, a restored draft,
|
||||
* an import; the observation list rules (add, remove, move) run in the core
|
||||
* too, and the editor's reducers hand back core-built observations. Form
|
||||
* values (identity, texts, an observation's comment, severity or free
|
||||
* findings) are plain assignments. An action whose core call fails changes
|
||||
* nothing and answers `{ ok: false }`; the caller tells the practitioner.
|
||||
* The per-tab draft is mirrored through the persistence adapter and restored
|
||||
* once the sheet is known; the archive an import brought along is kept
|
||||
* beside the report and written only when the session starts or ends.
|
||||
*/
|
||||
|
||||
/** What a new report needs before the store stamps version, id and dates. */
|
||||
export type NewReportDraft = Omit<
|
||||
Report,
|
||||
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
|
||||
>
|
||||
export type { NewReportDraft }
|
||||
|
||||
export interface ImportedSession {
|
||||
report: Report
|
||||
archive: ReportArchiveEnvelope | null
|
||||
}
|
||||
|
||||
export interface ActionResult {
|
||||
ok: boolean
|
||||
}
|
||||
|
||||
/** What a draft restore did; `null` from the action when there was nothing to restore. */
|
||||
export type RestoreResult =
|
||||
| { kind: 'restored'; rebase: RebaseOutcome }
|
||||
/** The draft is unreadable by this build: set aside under a quarantine key. */
|
||||
| { kind: 'quarantined' }
|
||||
/**
|
||||
* The draft is unreadable but could not be set aside (storage full): it stays in
|
||||
* `osteo:draft`, and the caller must not start anything that would overwrite it.
|
||||
*/
|
||||
| { kind: 'unreadable_kept' }
|
||||
/** The core failed: nothing read, nothing written, the draft is where it was. */
|
||||
| { kind: 'core_unavailable' }
|
||||
|
||||
export interface ReportStore {
|
||||
report: Report | null
|
||||
/** The envelope of the imported archive, as exported; null otherwise. */
|
||||
archive: ReportArchiveEnvelope | null
|
||||
activeObservationIndex: number
|
||||
initReport: (draft: NewReportDraft, sheet: SheetRef) => void
|
||||
hydrateReport: (report: Report) => void
|
||||
/** Opens an imported report (already rebased) with its archive. */
|
||||
initReport: (draft: NewReportDraft, sheet: SheetRef) => ActionResult
|
||||
/** Opens an imported report (read and rebased by the core) with its archive. */
|
||||
hydrateImport: (session: ImportedSession) => void
|
||||
/**
|
||||
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
|
||||
* written on another revision; a no-op when a report is already open.
|
||||
* Returns the rebase outcome, null when nothing was restored.
|
||||
* written on another revision; a no-op (null) when a report is already open
|
||||
* or there is no draft.
|
||||
*/
|
||||
restoreDraft: (index: SheetIndex) => RebaseOutcome | null
|
||||
addObservation: () => void
|
||||
removeObservation: (index: number) => void
|
||||
moveObservationUp: (index: number) => void
|
||||
moveObservationDown: (index: number) => void
|
||||
restoreDraft: (index: SheetIndex) => RestoreResult | null
|
||||
addObservation: () => ActionResult
|
||||
removeObservation: (index: number) => ActionResult
|
||||
moveObservationUp: (index: number) => ActionResult
|
||||
moveObservationDown: (index: number) => ActionResult
|
||||
updateObservation: (index: number, obs: Observation) => void
|
||||
setActiveObservation: (index: number) => void
|
||||
setPractitioner: (next: Practitioner) => void
|
||||
@@ -73,47 +92,68 @@ export interface ReportStore {
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
export function emptyObservation(): Observation {
|
||||
return {
|
||||
id: generateId(),
|
||||
zones: [],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
}
|
||||
}
|
||||
|
||||
/** A fresh v3 document: the store stamps version, id, dates and the sheet. */
|
||||
function newReport(draft: NewReportDraft, sheet: SheetRef): Report {
|
||||
return {
|
||||
...draft,
|
||||
version: REPORT_VERSION,
|
||||
id: generateId(),
|
||||
createdAt: nowIso(),
|
||||
sheet,
|
||||
observations:
|
||||
draft.observations.length === 0
|
||||
? [emptyObservation()]
|
||||
: draft.observations,
|
||||
localAnnotations: [],
|
||||
}
|
||||
}
|
||||
|
||||
function swapped(list: Observation[], i: number, j: number): Observation[] {
|
||||
const next = [...list]
|
||||
;[next[i], next[j]] = [next[j]!, next[i]!]
|
||||
return next
|
||||
}
|
||||
|
||||
type Patch = Partial<
|
||||
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
|
||||
>
|
||||
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
|
||||
type Getter = () => ReportStore
|
||||
|
||||
const OK: ActionResult = { ok: true }
|
||||
const FAILED: ActionResult = { ok: false }
|
||||
|
||||
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
|
||||
set((s) => (s.report ? update(s.report, s) : s))
|
||||
}
|
||||
|
||||
/** Applies a core-built report with its active index; nothing changes on failure. */
|
||||
function applyCore(
|
||||
set: Setter,
|
||||
get: Getter,
|
||||
run: (report: Report) => CoreOutcome<Report>,
|
||||
active: (next: Report, s: ReportStore) => number,
|
||||
): ActionResult {
|
||||
const state = get()
|
||||
if (!state.report) return OK
|
||||
const outcome = run(state.report)
|
||||
if (!outcome.ok) return FAILED
|
||||
set(() => ({
|
||||
report: outcome.value,
|
||||
activeObservationIndex: active(outcome.value, state),
|
||||
}))
|
||||
return OK
|
||||
}
|
||||
|
||||
/** Reads the draft through the core; unreadable content goes to quarantine, never away. */
|
||||
function restore(
|
||||
index: SheetIndex,
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
): { result: RestoreResult; patch?: Patch } | null {
|
||||
const draft = persistence.loadText()
|
||||
if (draft === null) return null
|
||||
const archiveText = archives.loadText()
|
||||
const outcome = index.ops.restoreDraft(draft, archiveText)
|
||||
if (!outcome.ok) {
|
||||
// Only an unreadable draft is set aside; a core or sheet failure leaves it in place.
|
||||
if (outcome.kind !== 'invalid' && outcome.kind !== 'unsupported_version') {
|
||||
return { result: { kind: 'core_unavailable' } }
|
||||
}
|
||||
const setAside = quarantine('draft', draft, DRAFT_KEY)
|
||||
return { result: { kind: setAside ? 'quarantined' : 'unreadable_kept' } }
|
||||
}
|
||||
const { rebase, archive, archiveRejected } = outcome.value
|
||||
if (archiveRejected && archiveText !== null) {
|
||||
quarantine('archive', archiveText, ARCHIVE_KEY)
|
||||
}
|
||||
if (rebase.rebased && rebase.unresolvedZones + rebase.unresolvedFindings > 0) {
|
||||
quarantine('draftPreRebase', draft)
|
||||
}
|
||||
return {
|
||||
result: { kind: 'restored', rebase },
|
||||
patch: { report: rebase.report, archive, activeObservationIndex: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
export function createReportStore(
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
@@ -129,78 +169,64 @@ export function createReportStore(
|
||||
archive: null,
|
||||
activeObservationIndex: 0,
|
||||
|
||||
initReport: (draft, sheet) =>
|
||||
set(
|
||||
withArchive(
|
||||
{ report: newReport(draft, sheet), activeObservationIndex: 0 },
|
||||
null,
|
||||
),
|
||||
),
|
||||
|
||||
hydrateReport: (report) =>
|
||||
set(withArchive({ report, activeObservationIndex: 0 }, null)),
|
||||
initReport: (draft, sheet) => {
|
||||
const outcome = reportOps.newReport({
|
||||
draft,
|
||||
sheet,
|
||||
id: generateId(),
|
||||
createdAt: nowIso(),
|
||||
observationId: generateId(),
|
||||
})
|
||||
if (!outcome.ok) return FAILED
|
||||
set(withArchive({ report: outcome.value, activeObservationIndex: 0 }, null))
|
||||
return OK
|
||||
},
|
||||
|
||||
hydrateImport: ({ report, archive }) =>
|
||||
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
|
||||
|
||||
restoreDraft: (index) => {
|
||||
if (get().report) return null
|
||||
const draft = persistence.load(index.sheet.migrationMap)
|
||||
if (!draft) return null
|
||||
const archive = archives.load()
|
||||
const rebase = rebaseReportOnSheet(
|
||||
draft,
|
||||
index,
|
||||
archive?.sheetSnapshot ?? null,
|
||||
)
|
||||
set({ report: rebase.report, archive, activeObservationIndex: 0 })
|
||||
return rebase
|
||||
const restored = restore(index, persistence, archives)
|
||||
if (!restored) return null
|
||||
if (restored.patch) set(restored.patch)
|
||||
return restored.result
|
||||
},
|
||||
|
||||
addObservation: () =>
|
||||
onReport(set, (r) => {
|
||||
const observations = [...r.observations, emptyObservation()]
|
||||
return {
|
||||
report: { ...r, observations },
|
||||
activeObservationIndex: observations.length - 1,
|
||||
}
|
||||
}),
|
||||
applyCore(
|
||||
set,
|
||||
get,
|
||||
(r) => reportOps.addObservation(r, generateId()),
|
||||
(next) => next.observations.length - 1,
|
||||
),
|
||||
|
||||
removeObservation: (index) =>
|
||||
onReport(set, (r, s) => {
|
||||
const observations = r.observations.filter((_, i) => i !== index)
|
||||
const active = Math.min(
|
||||
s.activeObservationIndex,
|
||||
Math.max(0, observations.length - 1),
|
||||
)
|
||||
return {
|
||||
report: { ...r, observations },
|
||||
activeObservationIndex: active,
|
||||
}
|
||||
}),
|
||||
applyCore(
|
||||
set,
|
||||
get,
|
||||
(r) => reportOps.removeObservation(r, index),
|
||||
(next, s) =>
|
||||
Math.min(
|
||||
s.activeObservationIndex,
|
||||
Math.max(0, next.observations.length - 1),
|
||||
),
|
||||
),
|
||||
|
||||
moveObservationUp: (index) =>
|
||||
onReport(set, (r) =>
|
||||
index <= 0
|
||||
? {}
|
||||
: {
|
||||
report: {
|
||||
...r,
|
||||
observations: swapped(r.observations, index - 1, index),
|
||||
},
|
||||
},
|
||||
applyCore(
|
||||
set,
|
||||
get,
|
||||
(r) => reportOps.moveObservation(r, index, 'up'),
|
||||
(_, s) => s.activeObservationIndex,
|
||||
),
|
||||
|
||||
moveObservationDown: (index) =>
|
||||
onReport(set, (r) =>
|
||||
index >= r.observations.length - 1
|
||||
? {}
|
||||
: {
|
||||
report: {
|
||||
...r,
|
||||
observations: swapped(r.observations, index, index + 1),
|
||||
},
|
||||
},
|
||||
applyCore(
|
||||
set,
|
||||
get,
|
||||
(r) => reportOps.moveObservation(r, index, 'down'),
|
||||
(_, s) => s.activeObservationIndex,
|
||||
),
|
||||
|
||||
updateObservation: (index, obs) =>
|
||||
|
||||
Reference in new issue
Block a user