feat(domain): R2.3 editor rules in Rust — zone click chain, reducers, finding toggle, vertebra selection, report operations

zoneInteraction (decision + reducers, collectVertebrae concatenated-key
dedup, syncVertebrae Map order), FindingsTreePicker.toggleLeaf (clicked
leaf by position, parents first-wins), VertebraPicker toggle/all/none and
the store's newReport/add/remove/move, checked against 49 cases frozen
from the TypeScript (41 byte-equal, 8 equal up to key order: contract
order replaces insertion order, D-R11) and the 13-case service suite.
Typed error kinds where the TypeScript would throw or corrupt a list.
This commit is contained in:
bchanot committed 2026-10-14 00:17:22 +02:00
1 parent 0c47d0f837
commit 3639c8778e
9 files changed
+4465

No files matched your search

@@ -0,0 +1,714 @@
/**
* R2 freeze of the editor rules (RUST_ARCHITECTURE_REVIEW VI.1, R2 plan §5 oracles b):
* every reducer and click decision of `services/zoneInteraction.ts`, the findings picker's
* `toggleLeaf`, the vertebra picker's toggle / all / none and the store's report rules,
* computed by the TypeScript code on the bundled draft sheet and written once to
* `crates/core/tests/oracles/editor.json`. The Rust port (`crates/core/src/domain/editor`)
* is checked case by case against that file (`crates/core/tests/editor_rules.rs`).
* `MAKE_R2_ORACLES=1` writes the file; otherwise the TypeScript output is asserted equal to
* it. The picker and store closures live inside a component or a store factory: they are
* copied below verbatim from VertebraPicker.tsx, FindingsTreePicker.tsx and reportStore.ts.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { beforeAll, describe, expect, it } from 'vitest'
import {
REPORT_VERSION,
type Annotation,
type Finding,
type FindingCategory,
type FindingNode,
type LateralSide,
type Observation,
type Report,
type SheetRef,
type Vertebra,
} from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
import {
addSides,
collectVertebrae,
decideZoneClick,
ensureZone,
refOf,
removeAllSides,
removeZoneAt,
sidesPresent,
syncVertebrae,
toggleZone,
} from '@/services/zoneInteraction'
import {
emptyObservation,
loadTestSheet,
minimalReport,
} from '../helpers/sheet'
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../..')
const ORACLE = resolve(ROOT, 'crates/core/tests/oracles/editor.json')
const MAKE = process.env.MAKE_R2_ORACLES === '1'
interface Case {
name: string
fn: string
input: unknown
output: unknown
}
let sheet: SheetIndex
const a = (id: string): Annotation => {
const annotation = sheet.annotation(id)
if (!annotation) throw new Error(`no annotation ${id}`)
return annotation
}
/** EditorRoute.onZoneClick, with the follow-up data the pickers read. */
function zoneClick(obs: Observation | null, annotationId: string): unknown {
const annotation = sheet.annotation(annotationId)
const decision = decideZoneClick(annotation, obs ?? undefined)
if (!annotation) return { kind: decision.kind }
switch (decision.kind) {
case 'open_view':
return { kind: decision.kind, viewId: decision.viewId }
case 'ignore':
case 'activate_fallback':
return { kind: decision.kind }
case 'open_vertebra_picker': {
const { observation, index } = ensureZone(obs!, annotation)
const out: Record<string, unknown> = { kind: decision.kind }
if (observation !== obs) out.observation = observation
out.zoneIndex = index
out.vertebrae = collectVertebrae(observation, sheet, index)
return out
}
case 'open_laterality_picker':
return {
kind: decision.kind,
sidesPresent: sidesPresent(obs!, refOf(annotation)),
}
case 'remove_both_sides':
return {
kind: decision.kind,
observation: removeAllSides(obs!, refOf(annotation)),
}
case 'toggle':
return { kind: decision.kind, observation: toggleZone(obs!, annotation) }
}
}
// --- FindingsTreePicker.tsx (verbatim) ---------------------------------------
type TreeNode = FindingCategory | FindingNode
function samePath(x: readonly string[], y: readonly string[]): boolean {
return x.length === y.length && x.every((seg, i) => seg === y[i])
}
function findNode(
categories: readonly FindingCategory[],
path: readonly string[],
): TreeNode | undefined {
let nodes: readonly TreeNode[] = categories
let node: TreeNode | undefined
for (const segment of path) {
node = nodes.find((n) => n.id === segment)
if (!node) return undefined
nodes = node.children
}
return node
}
/** The picker on `findingZoneId`, its `toggleLeaf` on the leaf at `leafPosition`, then the card's onChange. */
function toggleFinding(
obs: Observation,
findingZoneId: string,
path: string[],
leafPosition: number,
side: LateralSide | undefined,
): Observation {
const zone = sheet.findingZone(findingZoneId)!
const parentPath = path.slice(0, -1)
const currentNodes =
parentPath.length === 0
? zone.categories
: (findNode(zone.categories, parentPath)?.children ?? [])
const leaf: TreeNode = currentNodes[leafPosition]!
const selected = obs.findings
let result = obs
const onChange = (next: Finding[]) => {
result = { ...obs, findings: next }
}
const matches = (f: Finding) => f.findingZoneId === zone.id && f.side === side
const isLeafSelected = (leafPath: string[]) =>
selected.some((f) => matches(f) && samePath(f.path, leafPath))
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])
}
toggleLeaf(path, leaf)
return result
}
// --- VertebraPicker.tsx (verbatim closures, `selected` = `cur`) ---------------
type VertebraAction =
| { kind: 'toggle'; region: string; index: number }
| { kind: 'all'; region: string; count: number }
| { kind: 'none'; region: string }
const sameVertebra = (v: Vertebra, r: string, i: number) =>
v.region === r && v.index === i
function selectVertebrae(cur: Vertebra[], action: VertebraAction): Vertebra[] {
const has = (r: string, i: number) => cur.some((v) => sameVertebra(v, r, i))
switch (action.kind) {
case 'toggle': {
const { region: r, index: i } = action
return has(r, i)
? cur.filter((v) => !sameVertebra(v, r, i))
: [...cur, { region: r, index: i }]
}
case 'all':
return [
...cur.filter((v) => v.region !== action.region),
...Array.from({ length: action.count }, (_, k) => ({
region: action.region,
index: k + 1,
})),
]
case 'none':
return cur.filter((v) => v.region !== action.region)
}
}
// --- reportStore.ts (verbatim expressions, ids and time injected) -------------
type NewReportDraft = Omit<
Report,
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
>
function newReport(
draft: NewReportDraft,
sheetRef: SheetRef,
id: string,
createdAt: string,
observationId: string,
): Report {
return {
...draft,
version: REPORT_VERSION,
id,
createdAt,
sheet: sheetRef,
observations:
draft.observations.length === 0
? [emptyObservation(observationId)]
: 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
}
function moveObservation(r: Report, index: number, direction: 'up' | 'down') {
if (direction === 'up') {
return index <= 0
? r
: { ...r, observations: swapped(r.observations, index - 1, index) }
}
return index >= r.observations.length - 1
? r
: { ...r, observations: swapped(r.observations, index, index + 1) }
}
// --- fixtures -----------------------------------------------------------------
const C7T1 = ['c7-t1-dysfunctions', 'segmental', 'restriction-flexion']
const HIP = ['hip-dysfunctions', 'articular', 'restriction-flexion']
const VET = ['frontal-consultation-reasons', 'head-rubbing']
function obsWith(
zones: Observation['zones'],
findings: Finding[] = [],
): Observation {
return { ...emptyObservation(), zones, findings }
}
function zoneCases(): Case[] {
const empty = emptyObservation()
const withC7 = toggleZone(empty, a('c7-t1'))
const left = addSides(empty, a('hip'), ['left'])
const both = addSides(left, a('hip'), ['right'])
const spines = obsWith([
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 2 }],
},
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{ annotationId: 'c7-t1', viewId: 'main' },
])
const click = (
name: string,
observation: Observation | null,
annotationId: string,
): Case => ({
name,
fn: 'zone_click',
input: { observation, annotationId },
output: zoneClick(observation, annotationId),
})
return [
click('click plain zone adds it', empty, 'c7-t1'),
click('click plain zone removes it', withC7, 'c7-t1'),
click(
'click bilateral zone without side opens the side picker',
empty,
'hip',
),
click(
'click bilateral zone with one side opens the side picker',
left,
'hip',
),
click('click bilateral zone with both sides removes them', both, 'hip'),
click(
'click spine zone absent adds it and opens the picker',
empty,
'cervical',
),
click(
'click spine zone present opens the picker on it',
spines,
'cervical',
),
click(
'click detail trigger with an observation opens the view',
empty,
'head-trigger',
),
click(
'click detail trigger without an observation opens the view',
null,
'head-trigger',
),
click('click unknown annotation is ignored', empty, 'no-such-annotation'),
click('click without an active observation activates one', null, 'c7-t1'),
click('click head view zone toggles it', empty, 'atm'),
]
}
function sideAndIndexCases(): Case[] {
const empty = emptyObservation()
const left = addSides(empty, a('hip'), ['left'])
const withFinding = {
...toggleZone(empty, a('c7-t1')),
findings: [
{
findingZoneId: 'c7-t1',
path: C7T1,
labelFrSnapshot: 'F',
labelEnSnapshot: 'F',
},
],
}
const sides = (
name: string,
observation: Observation,
id: string,
s: LateralSide[],
): Case => ({
name,
fn: 'add_sides',
input: { observation, annotationId: id, sides: s },
output: addSides(observation, a(id), s),
})
const removeAt = (
name: string,
observation: Observation,
index: number,
): Case => ({
name,
fn: 'remove_zone_at',
input: { observation, index },
output: removeZoneAt(observation, index),
})
return [
sides('add left side', empty, 'hip', ['left']),
sides('add both sides to left', left, 'hip', ['left', 'right']),
sides('add an existing side changes nothing', left, 'hip', ['left']),
sides(
'add a side to a detail trigger records no label',
empty,
'head-trigger',
['left'],
),
removeAt('remove zone keeps findings', withFinding, 0),
removeAt('remove zone outside the list changes nothing', withFinding, 5),
]
}
function vertebraCases(): Case[] {
const initial = (
name: string,
observation: Observation,
zoneIndex: number,
): Case => ({
name,
fn: 'vertebra_initial',
input: { observation, zoneIndex },
output: collectVertebrae(observation, sheet, zoneIndex),
})
const sync = (
name: string,
observation: Observation,
selection: Vertebra[],
viewId: string,
): Case => ({
name,
fn: 'sync_vertebrae',
input: { observation, selection, viewId },
output: syncVertebrae(observation, selection, sheet, viewId),
})
const spines = obsWith([
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 2 }],
},
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{
annotationId: 'c7-t1',
viewId: 'main',
vertebrae: [{ region: 'C', index: 9 }],
},
])
const collision = obsWith([
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [{ region: 'C1', index: 1 }],
},
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'C', index: 11 }],
},
])
const cervical = ensureZone(emptyObservation(), a('cervical')).observation
const twoCervical = obsWith([
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [{ region: 'C', index: 1 }],
},
{
annotationId: 'cervical',
viewId: 'head',
vertebrae: [{ region: 'C', index: 5 }],
},
])
const cervicalThoracic = obsWith([
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [{ region: 'C', index: 1 }],
},
{ annotationId: 'c7-t1', viewId: 'main' },
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 1 }],
},
])
return [
initial(
'initial selection, priority zone first, non-spine zone ignored',
spines,
1,
),
initial('initial selection keys on region + index text', collision, 0),
initial('initial selection with an index outside the list', spines, 9),
sync(
'sync spawns zones for new regions and prunes the emptied one',
cervical,
[
{ region: 'L', index: 3 },
{ region: 'L', index: 4 },
{ region: 'Cd', index: 20 },
],
'main',
),
sync(
'sync with an empty selection prunes every spine zone',
spines,
[],
'main',
),
sync(
'sync ignores unknown regions and keeps non-spine zones',
toggleZone(emptyObservation(), a('c7-t1')),
[{ region: 'XX', index: 1 }],
'main',
),
sync(
'sync prunes a second zone of a served region',
twoCervical,
[{ region: 'C', index: 2 }],
'main',
),
sync(
'sync replaces per region and prunes a region left empty',
cervicalThoracic,
[{ region: 'T', index: 3 }],
'main',
),
sync(
'sync falls back to the main view spine annotation',
emptyObservation(),
[{ region: 'C', index: 5 }],
'head',
),
sync(
'sync spawns zones in first-seen region order',
emptyObservation(),
[
{ region: 'Cd', index: 1 },
{ region: 'C', index: 2 },
{ region: 'Cd', index: 3 },
],
'main',
),
]
}
function findingCases(): Case[] {
const empty = emptyObservation()
const toggle = (
name: string,
observation: Observation,
findingZoneId: string,
path: string[],
leafPosition: number,
side?: LateralSide,
): Case => {
const input: Record<string, unknown> = {
observation,
findingZoneId,
path,
leafPosition,
}
if (side) input.side = side
return {
name,
fn: 'toggle_finding',
input,
output: toggleFinding(
observation,
findingZoneId,
path,
leafPosition,
side,
),
}
}
const added = toggleFinding(empty, 'c7-t1', C7T1, 0, undefined)
const hipLeft = toggleFinding(empty, 'hip', HIP, 0, 'left')
const twice = { ...empty, findings: [...added.findings, ...added.findings] }
return [
toggle('toggle adds a leaf', empty, 'c7-t1', C7T1, 0),
toggle('toggle removes a selected leaf', added, 'c7-t1', C7T1, 0),
toggle('toggle adds a leaf with a side', empty, 'hip', HIP, 0, 'left'),
toggle('toggle adds the other side', hipLeft, 'hip', HIP, 0, 'right'),
toggle(
'toggle without side ignores a sided finding',
hipLeft,
'hip',
HIP,
0,
),
toggle('toggle a vet-referral leaf flags it', empty, 'frontal', VET, 1),
toggle('toggle removes every duplicate', twice, 'c7-t1', C7T1, 0),
]
}
function selectCases(): Case[] {
const select = (
name: string,
selection: Vertebra[],
action: VertebraAction,
): Case => ({
name,
fn: 'vertebra_select',
input: { selection, action },
output: selectVertebrae(selection, action),
})
const c1 = { region: 'C', index: 1 }
const t2 = { region: 'T', index: 2 }
const c3 = { region: 'C', index: 3 }
return [
select('select toggles a vertebra on', [], {
kind: 'toggle',
region: 'C',
index: 1,
}),
select('select toggles a vertebra off', [c1, t2], {
kind: 'toggle',
region: 'C',
index: 1,
}),
select('select toggles off every duplicate', [c1, c1], {
kind: 'toggle',
region: 'C',
index: 1,
}),
select('select all replaces the region at the end', [t2, c3], {
kind: 'all',
region: 'C',
count: 7,
}),
select('select none removes the region', [c1, t2, c3], {
kind: 'none',
region: 'C',
}),
]
}
function reportCases(): Case[] {
const ref = sheet.sheet.ref
const draft = (
observations: Observation[],
next = false,
): NewReportDraft => ({
date: '2026-10-14',
practitioner: { name: 'Dr. Dupont', cabinet: 'Cabinet' },
animal: { speciesId: 'equine', name: 'Mistral', age: '9 ans' },
owner: { name: 'Jean Martin' },
observations,
conclusion: '',
recommendations: 'Repos',
...(next
? { nextAppointment: { kind: 'period' as const, text: '3 semaines' } }
: {}),
})
const make = (name: string, d: NewReportDraft): Case => ({
name,
fn: 'new_report',
input: {
draft: d,
sheet: ref,
id: 'report-1',
createdAt: '2026-10-14T08:00:00.000Z',
observationId: 'obs-new',
},
output: newReport(
d,
ref,
'report-1',
'2026-10-14T08:00:00.000Z',
'obs-new',
),
})
const three = minimalReport(sheet, {
observations: [
emptyObservation('o1'),
emptyObservation('o2'),
emptyObservation('o3'),
],
})
const add: Case = {
name: 'add observation appends an empty one',
fn: 'add_observation',
input: { report: three, id: 'o4' },
output: {
...three,
observations: [...three.observations, emptyObservation('o4')],
},
}
const remove = (name: string, index: number): Case => ({
name,
fn: 'remove_observation',
input: { report: three, index },
output: {
...three,
observations: three.observations.filter((_, i) => i !== index),
},
})
const move = (
name: string,
index: number,
direction: 'up' | 'down',
): Case => ({
name,
fn: 'move_observation',
input: { report: three, index, direction },
output: moveObservation(three, index, direction),
})
return [
make('new report starts with one empty observation', draft([])),
make(
'new report keeps the draft observations',
draft([emptyObservation('o9')], true),
),
add,
remove('remove observation by index', 1),
remove('remove observation outside the list', 5),
move('move observation up', 1, 'up'),
move('move the first observation up changes nothing', 0, 'up'),
move('move observation down', 1, 'down'),
move('move the last observation down changes nothing', 2, 'down'),
]
}
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('editor rules characterisation (TypeScript side of the R2 switch)', () => {
it('matches the frozen oracle file', () => {
const cases = [
...zoneCases(),
...sideAndIndexCases(),
...vertebraCases(),
...findingCases(),
...selectCases(),
...reportCases(),
]
const text = `${JSON.stringify({ cases }, null, 2)}\n`
if (MAKE) {
mkdirSync(dirname(ORACLE), { recursive: true })
writeFileSync(ORACLE, text)
}
expect(new Set(cases.map((c) => c.name)).size).toBe(cases.length)
expect(text).toBe(readFileSync(ORACLE, 'utf8'))
})
})
+111
View File
@@ -0,0 +1,111 @@
//! The finding builder of the findings picker (`FindingsTreePicker.toggleLeaf` and the
//! card's `onChange`): a finding is keyed by `(findingZoneId, path, side)` and snapshots the
//! labels of the node the practitioner clicked.
use super::EditorError;
use crate::domain::report::{Finding, LateralSide, Observation};
use crate::domain::sheet::{FindingNode, FindingTreeItem, FindingZone, IndexedDocument};
/// What the picker knows about the clicked leaf.
#[derive(Debug, Clone, Copy)]
pub struct LeafClick<'a> {
/// Id of the finding zone the picker shows (last duplicate wins, as `findingZone`).
pub finding_zone_id: &'a str,
/// Node ids from the zone's categories down to the leaf.
pub path: &'a [String],
/// Position of the leaf among its siblings in the list the picker rendered.
pub leaf_position: usize,
pub side: Option<LateralSide>,
}
fn matches(finding: &Finding, click: &LeafClick<'_>) -> bool {
finding.finding_zone_id == click.finding_zone_id
&& finding.side == click.side
&& finding.path.as_slice() == click.path
}
/// Toggles the leaf in the observation's findings: every finding with the same zone, side
/// and path is removed when one exists; otherwise the finding built from the clicked node is
/// appended.
pub fn toggle_finding(
sheet: &IndexedDocument<'_>,
observation: &Observation,
click: &LeafClick<'_>,
) -> Result<Observation, EditorError> {
let zone = sheet
.finding_zone(click.finding_zone_id)
.ok_or(EditorError::UnknownZone)?;
let mut findings = observation.findings.clone();
if findings.iter().any(|f| matches(f, click)) {
findings.retain(|f| !matches(f, click));
} else {
findings.push(build_finding(zone, click)?);
}
Ok(Observation {
findings,
..observation.clone()
})
}
/// The finding the picker records for a leaf: labels snapshotted, the vet flag only when a
/// node (never a category) carries it, the side when the zone has one.
fn build_finding(zone: &FindingZone, click: &LeafClick<'_>) -> Result<Finding, EditorError> {
let leaf = clicked_node(zone, click)?;
let name = leaf.name();
Ok(Finding {
finding_zone_id: zone.id.clone(),
path: click.path.to_vec(),
label_fr_snapshot: name.fr.clone(),
label_en_snapshot: name.en.clone(),
requires_vet_referral: leaf.requires_vet_referral().then_some(true),
side: click.side,
unresolved: None,
})
}
/// The node at `leaf_position` of the list the picker rendered: the zone's categories at the
/// root, else the children of the parent reached by the first-wins walk (`findNode`).
fn clicked_node<'a>(
zone: &'a FindingZone,
click: &LeafClick<'_>,
) -> Result<FindingTreeItem<'a>, EditorError> {
let (last, parents) = click.path.split_last().ok_or(EditorError::UnknownNode)?;
let leaf = match parents.split_first() {
None => zone
.categories
.get(click.leaf_position)
.map(FindingTreeItem::Category),
Some((first, rest)) => parent_children(zone, first, rest)?
.get(click.leaf_position)
.map(FindingTreeItem::Node),
}
.ok_or(EditorError::UnknownNode)?;
if leaf.id() == last {
Ok(leaf)
} else {
Err(EditorError::UnknownNode)
}
}
/// Children of the node at `[first, ...rest]`, each segment the first sibling with that id.
fn parent_children<'a>(
zone: &'a FindingZone,
first: &str,
rest: &[String],
) -> Result<&'a [FindingNode], EditorError> {
let category = zone
.categories
.iter()
.find(|c| c.id == first)
.ok_or(EditorError::UnknownNode)?;
let mut node = FindingTreeItem::Category(category);
for segment in rest {
let child = node
.children()
.iter()
.find(|n| &n.id == segment)
.ok_or(EditorError::UnknownNode)?;
node = FindingTreeItem::Node(child);
}
Ok(node.children())
}
+51
View File
@@ -0,0 +1,51 @@
//! Editor rules of the report (R2.3): what a click on the drawing does to the active
//! observation, how a finding is built from the sheet, how the vertebra picker edits its
//! selection, and the report-level list operations of the store. Ported from
//! `apps/app/src/services/zoneInteraction.ts`, `FindingsTreePicker.toggleLeaf`,
//! `VertebraPicker` and `reportStore.ts`; every function returns new values and never
//! touches its inputs.
pub mod finding;
pub mod report_ops;
pub mod vertebra;
pub mod zone;
pub use finding::{LeafClick, toggle_finding};
pub use report_ops::{
MoveDirection, NewReportDraft, NewReportStamp, add_observation, move_observation, new_report,
remove_observation,
};
pub use vertebra::{VertebraAction, select_vertebrae};
pub use zone::{
ZoneClick, ZoneClickKind, add_sides, collect_vertebrae, remove_zone_at, sync_vertebrae,
vertebra_initial, zone_click,
};
/// Closed failure kinds of the editor rules: inputs the TypeScript code never produced
/// (it either guarded them in the UI or would have corrupted its own state).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditorError {
/// No annotation of the sheet has this id.
UnknownAnnotation,
/// No finding zone of the sheet has this id.
UnknownZone,
/// The path and position name no node of the finding tree.
UnknownNode,
/// An observation index outside the list.
InvalidIndex,
/// A vertebra count no picker grid can show.
InvalidCount,
}
impl EditorError {
/// The closed kind the facade reports.
pub fn kind(self) -> &'static str {
match self {
Self::UnknownAnnotation => "unknown_annotation",
Self::UnknownZone => "unknown_zone",
Self::UnknownNode => "unknown_node",
Self::InvalidIndex => "invalid_index",
Self::InvalidCount => "invalid_count",
}
}
}
+131
View File
@@ -0,0 +1,131 @@
//! Report-level rules of the store (`apps/app/src/state/reportStore.ts`): a new report is
//! stamped from the form draft, observations are added, removed and moved. The active
//! observation index is screen state and stays in the store.
use serde::{Deserialize, Serialize};
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::EditorError;
use crate::domain::js;
use crate::domain::report::{
Animal, NextAppointment, Observation, Owner, Practitioner, Report, ReportVersion3, SheetRef,
};
/// What a new report needs before version, id, dates and the sheet are stamped
/// (`Omit<Report, 'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'>`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct NewReportDraft {
pub date: String,
pub practitioner: Practitioner,
pub animal: Animal,
pub owner: Owner,
pub observations: Vec<Observation>,
pub conclusion: String,
pub recommendations: String,
#[serde(
default,
deserialize_with = "js::present",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(feature = "ts", ts(optional))]
pub next_appointment: Option<NextAppointment>,
}
/// A fresh observation: nothing recorded yet.
fn empty_observation(id: &str) -> Observation {
Observation {
id: id.to_owned(),
..Observation::default()
}
}
/// The ids and the time a new report is stamped with (the core makes neither).
#[derive(Debug, Clone, Copy)]
pub struct NewReportStamp<'a> {
pub id: &'a str,
pub created_at: &'a str,
/// Id of the observation a draft without any starts with.
pub observation_id: &'a str,
}
/// A fresh v3 document: the draft, stamped with version, id, creation time and sheet; a
/// draft without observations starts with one empty observation.
pub fn new_report(draft: NewReportDraft, sheet: SheetRef, stamp: &NewReportStamp<'_>) -> Report {
let observations = if draft.observations.is_empty() {
vec![empty_observation(stamp.observation_id)]
} else {
draft.observations
};
Report {
version: ReportVersion3,
id: stamp.id.to_owned(),
created_at: stamp.created_at.to_owned(),
date: draft.date,
practitioner: draft.practitioner,
animal: draft.animal,
owner: draft.owner,
sheet,
observations,
conclusion: draft.conclusion,
recommendations: draft.recommendations,
next_appointment: draft.next_appointment,
local_annotations: Vec::new(),
}
}
fn with_observations(report: &Report, observations: Vec<Observation>) -> Report {
Report {
observations,
..report.clone()
}
}
/// Appends an empty observation with the given id.
pub fn add_observation(report: &Report, id: &str) -> Report {
let mut observations = report.observations.clone();
observations.push(empty_observation(id));
with_observations(report, observations)
}
/// Removes the observation at `index`; an index outside the list removes nothing.
pub fn remove_observation(report: &Report, index: usize) -> Report {
let observations = report
.observations
.iter()
.enumerate()
.filter(|(i, _)| *i != index)
.map(|(_, o)| o.clone())
.collect();
with_observations(report, observations)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "lowercase")]
pub enum MoveDirection {
Up,
Down,
}
/// Swaps the observation at `index` with its neighbour; nothing happens at the ends. Moving
/// up from an index past the end is refused (the TypeScript swap would write a hole).
pub fn move_observation(
report: &Report,
index: usize,
direction: MoveDirection,
) -> Result<Report, EditorError> {
let len = report.observations.len();
let (first, second) = match direction {
MoveDirection::Up if index == 0 => return Ok(report.clone()),
MoveDirection::Up if index >= len => return Err(EditorError::InvalidIndex),
MoveDirection::Up => (index - 1, index),
MoveDirection::Down if index.saturating_add(1) >= len => return Ok(report.clone()),
MoveDirection::Down => (index, index + 1),
};
let mut observations = report.observations.clone();
observations.swap(first, second);
Ok(with_observations(report, observations))
}
+97
View File
@@ -0,0 +1,97 @@
//! The vertebra picker's selection rules (`VertebraPicker.tsx` toggle / all / none): what a
//! tap on a chip or on "check all" / "uncheck all" does to the selection being edited.
use serde::Deserialize;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::EditorError;
use crate::domain::js::JsInt;
use crate::domain::report::Vertebra;
/// Largest grid "check all" fills. A region's usual count is a small number; a count beyond
/// this cap is refused instead of allocated (JavaScript would build any array shorter than
/// 2^32 - 1 elements).
const MAX_CHECK_ALL: f64 = 65_535.0;
/// One tap of the picker.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum VertebraAction {
/// A chip: removes that vertebra when selected, appends it otherwise.
Toggle {
region: String,
#[cfg_attr(feature = "ts", ts(type = "number"))]
index: JsInt,
},
/// "Check all": the region's vertebrae 1..=count replace its current ones, appended last.
All {
region: String,
#[cfg_attr(feature = "ts", ts(type = "number"))]
count: JsInt,
},
/// "Uncheck all": every vertebra of the region removed.
None { region: String },
}
fn same(vertebra: &Vertebra, region: &str, index: JsInt) -> bool {
vertebra.region == region && vertebra.index == index
}
fn other_regions(selection: &[Vertebra], region: &str) -> Vec<Vertebra> {
selection
.iter()
.filter(|v| v.region != region)
.cloned()
.collect()
}
/// The selection after one tap; the input is never modified.
pub fn select_vertebrae(
selection: &[Vertebra],
action: &VertebraAction,
) -> Result<Vec<Vertebra>, EditorError> {
match action {
VertebraAction::Toggle { region, index } => Ok(toggled(selection, region, *index)),
VertebraAction::All { region, count } => {
let mut out = other_regions(selection, region);
out.extend(full_region(region, *count)?);
Ok(out)
}
VertebraAction::None { region } => Ok(other_regions(selection, region)),
}
}
fn toggled(selection: &[Vertebra], region: &str, index: JsInt) -> Vec<Vertebra> {
if selection.iter().any(|v| same(v, region, index)) {
return selection
.iter()
.filter(|v| !same(v, region, index))
.cloned()
.collect();
}
let mut out = selection.to_vec();
out.push(Vertebra {
region: region.to_owned(),
index,
});
out
}
/// `Array.from({ length: count }, (_, k) => ({ region, index: k + 1 }))`; a negative count
/// gives an empty array as `ToLength` makes it.
fn full_region(region: &str, count: JsInt) -> Result<Vec<Vertebra>, EditorError> {
let count = count.get().max(0.0);
if count > MAX_CHECK_ALL {
return Err(EditorError::InvalidCount);
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let count = count as u32;
Ok((1..=count)
.map(|index| Vertebra {
region: region.to_owned(),
index: JsInt::from(index),
})
.collect())
}
+379
View File
@@ -0,0 +1,379 @@
//! Zone interaction rules (`apps/app/src/services/zoneInteraction.ts`): what a click on an
//! annotation means for the active observation, and the observation reducers the editor
//! applies. The rules are the legacy ones (click chain of the editor, BDR-019 vertebra sync),
//! keyed by annotation ids.
use serde::Serialize;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::EditorError;
use crate::domain::report::{LateralSide, Observation, ReportZone, Vertebra};
use crate::domain::sheet::{Annotation, IndexedDocument};
use crate::json::js_number;
/// The kind of a click decision (`ZoneClickDecision.kind`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ZoneClickKind {
Ignore,
OpenView,
ActivateFallback,
OpenVertebraPicker,
OpenLateralityPicker,
RemoveBothSides,
Toggle,
}
/// What a click on an annotation did, with what the editor needs to follow it up.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ZoneClick {
pub kind: ZoneClickKind,
/// `open_view`: the detail view to open.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub view_id: Option<String>,
/// The active observation after the click, when the click changed it.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub observation: Option<Observation>,
/// `open_vertebra_picker`: the zone the picker edits.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub zone_index: Option<u32>,
/// `open_laterality_picker`: the sides already recorded.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub sides_present: Option<Vec<LateralSide>>,
/// `open_vertebra_picker`: the picker's initial selection.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub vertebrae: Option<Vec<Vertebra>>,
}
impl ZoneClick {
fn of(kind: ZoneClickKind) -> Self {
Self {
kind,
view_id: None,
observation: None,
zone_index: None,
sides_present: None,
vertebrae: None,
}
}
}
/// The zone a click on `annotation` names: its id on its own view.
fn same_zone(zone: &ReportZone, annotation: &Annotation) -> bool {
zone.annotation_id == annotation.id() && zone.view_id == annotation.view_id()
}
/// Sides already recorded for the annotation's zone, in zone order.
pub fn sides_present(observation: &Observation, annotation: &Annotation) -> Vec<LateralSide> {
observation
.zones
.iter()
.filter(|z| same_zone(z, annotation))
.filter_map(|z| z.side)
.collect()
}
/// Legacy click chain: a detail trigger opens its view and is never added; no active
/// observation → the click only activates one; spine zones always open the picker; bilateral
/// zones go through the side picker, or clear both sides when both are set; anything else
/// toggles.
fn decide(annotation: &Annotation, active: Option<&Observation>) -> ZoneClick {
let observable = match annotation {
Annotation::DetailTrigger(trigger) => {
let mut click = ZoneClick::of(ZoneClickKind::OpenView);
click.view_id = Some(trigger.opens_view_id.clone());
return click;
}
Annotation::Observable(observable) => observable,
};
let Some(active) = active else {
return ZoneClick::of(ZoneClickKind::ActivateFallback);
};
if observable.vertebral_region_code.is_some() {
return ZoneClick::of(ZoneClickKind::OpenVertebraPicker);
}
if observable.laterality == crate::domain::sheet::Laterality::Bilateral {
let sides = sides_present(active, annotation);
let both = sides.contains(&LateralSide::Left) && sides.contains(&LateralSide::Right);
return ZoneClick::of(if both {
ZoneClickKind::RemoveBothSides
} else {
ZoneClickKind::OpenLateralityPicker
});
}
ZoneClick::of(ZoneClickKind::Toggle)
}
/// A new zone for the annotation: its ref, the observable name snapshot, the side if any.
fn new_zone(annotation: &Annotation, side: Option<LateralSide>) -> ReportZone {
let mut zone = ReportZone {
annotation_id: annotation.id().to_owned(),
view_id: annotation.view_id().to_owned(),
side,
..ReportZone::default()
};
if let Some(observable) = annotation.observable() {
zone.label_fr_snapshot = Some(observable.name.fr.clone());
zone.label_en_snapshot = Some(observable.name.en.clone());
}
zone
}
fn with_zones(observation: &Observation, zones: Vec<ReportZone>) -> Observation {
Observation {
zones,
..observation.clone()
}
}
/// Plain zone: removed when present (the first match), added when absent (no side).
pub fn toggle_zone(observation: &Observation, annotation: &Annotation) -> Observation {
let found = observation
.zones
.iter()
.position(|z| same_zone(z, annotation));
let zones = match found {
Some(index) => without(&observation.zones, index),
None => appended(&observation.zones, new_zone(annotation, None)),
};
with_zones(observation, zones)
}
/// The zone exists after the call; returns the observation (unchanged when it existed) and
/// the zone's index.
pub fn ensure_zone(observation: &Observation, annotation: &Annotation) -> (Observation, usize) {
match observation
.zones
.iter()
.position(|z| same_zone(z, annotation))
{
Some(index) => (observation.clone(), index),
None => {
let zones = appended(&observation.zones, new_zone(annotation, None));
let index = zones.len() - 1;
(with_zones(observation, zones), index)
}
}
}
fn without(zones: &[ReportZone], index: usize) -> Vec<ReportZone> {
zones
.iter()
.enumerate()
.filter(|(i, _)| *i != index)
.map(|(_, z)| z.clone())
.collect()
}
fn appended(zones: &[ReportZone], zone: ReportZone) -> Vec<ReportZone> {
let mut out = zones.to_vec();
out.push(zone);
out
}
/// Appends the sides not present yet; never removes one (legacy semantics). Unchanged when
/// every side is already there.
pub fn add_sides(
sheet: &IndexedDocument<'_>,
observation: &Observation,
annotation_id: &str,
sides: &[LateralSide],
) -> Result<Observation, EditorError> {
let annotation = sheet
.annotation(annotation_id)
.ok_or(EditorError::UnknownAnnotation)?;
let present = sides_present(observation, annotation);
let added: Vec<ReportZone> = sides
.iter()
.filter(|side| !present.contains(side))
.map(|side| new_zone(annotation, Some(*side)))
.collect();
let mut zones = observation.zones.clone();
zones.extend(added);
Ok(with_zones(observation, zones))
}
/// Every zone of the annotation's ref, whatever its side.
pub fn remove_all_sides(observation: &Observation, annotation: &Annotation) -> Observation {
let zones = observation
.zones
.iter()
.filter(|z| !same_zone(z, annotation))
.cloned()
.collect();
with_zones(observation, zones)
}
/// One zone by index; an index outside the list removes nothing (as `filter` does).
pub fn remove_zone_at(observation: &Observation, index: usize) -> Observation {
with_zones(observation, without(&observation.zones, index))
}
/// Vertebrae of every spine zone of the observation, the zone at `priority` first (the one
/// the picker was opened from), without duplicates. Duplicates are found on the text
/// `region + index` exactly as the TypeScript key, so `C1`/1 and `C`/11 count as one.
pub fn collect_vertebrae(
sheet: &IndexedDocument<'_>,
observation: &Observation,
priority: usize,
) -> Vec<Vertebra> {
let zones = &observation.zones;
let ordered = zones
.iter()
.enumerate()
.filter(|(i, _)| *i == priority)
.chain(zones.iter().enumerate().filter(|(i, _)| *i != priority))
.map(|(_, zone)| zone)
.filter(|zone| sheet.is_spine(&zone.annotation_id));
let mut seen: Vec<String> = Vec::new();
let mut out = Vec::new();
for vertebra in ordered.flat_map(|zone| zone.vertebrae.iter().flatten()) {
let key = format!("{}{}", vertebra.region, js_number(vertebra.index.get()));
if !seen.contains(&key) {
seen.push(key);
out.push(vertebra.clone());
}
}
out
}
/// The picker's initial selection when it opens from the zone at `zone_index` (chip path).
pub fn vertebra_initial(
sheet: &IndexedDocument<'_>,
observation: &Observation,
zone_index: usize,
) -> Vec<Vertebra> {
collect_vertebrae(sheet, observation, zone_index)
}
/// The selection grouped by region, in first-seen order (a JavaScript `Map`).
fn by_region(selection: &[Vertebra]) -> Vec<(String, Vec<Vertebra>)> {
let mut groups: Vec<(String, Vec<Vertebra>)> = Vec::new();
for vertebra in selection {
match groups
.iter_mut()
.find(|(region, _)| *region == vertebra.region)
{
Some((_, list)) => list.push(vertebra.clone()),
None => groups.push((vertebra.region.clone(), vec![vertebra.clone()])),
}
}
groups
}
/// The region of a spine zone (by its annotation id, last duplicate wins).
fn region_of(sheet: &IndexedDocument<'_>, zone: &ReportZone) -> Option<String> {
if !sheet.is_spine(&zone.annotation_id) {
return None;
}
sheet
.annotation(&zone.annotation_id)
.and_then(Annotation::observable)
.and_then(|a| a.vertebral_region_code.clone())
}
/// BDR-019: the picker edits every region at once. Per region the selection REPLACES the
/// zone's vertebrae; a spine zone left without vertebrae (or a second zone of a region
/// already served) is pruned; a region picked without a zone gets one on the view the
/// picker was opened from, else on the main view.
pub fn sync_vertebrae(
sheet: &IndexedDocument<'_>,
observation: &Observation,
selection: &[Vertebra],
view_id: &str,
) -> Observation {
let mut groups = by_region(selection);
let mut kept = Vec::new();
for zone in &observation.zones {
let Some(region) = region_of(sheet, zone) else {
kept.push(zone.clone());
continue;
};
let Some(position) = groups.iter().position(|(r, _)| *r == region) else {
continue;
};
let (_, picked) = groups.remove(position);
kept.push(ReportZone {
vertebrae: Some(picked),
..zone.clone()
});
}
kept.extend(spawned_zones(sheet, groups, view_id));
with_zones(observation, kept)
}
/// Zones for the regions picked without one, in selection order; a region with no spine
/// annotation on the view nor on the main view is dropped.
fn spawned_zones(
sheet: &IndexedDocument<'_>,
groups: Vec<(String, Vec<Vertebra>)>,
view_id: &str,
) -> Vec<ReportZone> {
let main_view_id = sheet.main_view().id().to_owned();
groups
.into_iter()
.filter_map(|(region, picked)| {
let annotation = spine_annotation(sheet, &region, view_id)
.or_else(|| spine_annotation(sheet, &region, &main_view_id))?;
Some(ReportZone {
vertebrae: Some(picked),
..new_zone(annotation, None)
})
})
.collect()
}
/// `index.spineAnnotation(region, view)` as an `Annotation` (first match in the document).
fn spine_annotation<'a>(
sheet: &IndexedDocument<'a>,
region: &str,
view_id: &str,
) -> Option<&'a Annotation> {
sheet.document.annotations.iter().find(|a| {
a.observable().is_some_and(|o| {
o.view_id == view_id && o.vertebral_region_code.as_deref() == Some(region)
})
})
}
/// One click on `annotation_id` with the active observation (`EditorRoute.onZoneClick`):
/// the decision, then the reducer it names, then what the follow-up picker needs.
pub fn zone_click(
sheet: &IndexedDocument<'_>,
observation: Option<&Observation>,
annotation_id: &str,
) -> ZoneClick {
let Some(annotation) = sheet.annotation(annotation_id) else {
return ZoneClick::of(ZoneClickKind::Ignore);
};
let mut click = decide(annotation, observation);
let Some(active) = observation else {
return click;
};
match click.kind {
ZoneClickKind::OpenVertebraPicker => {
let (ensured, index) = ensure_zone(active, annotation);
click.vertebrae = Some(collect_vertebrae(sheet, &ensured, index));
click.zone_index = u32::try_from(index).ok();
click.observation = (ensured != *active).then_some(ensured);
}
ZoneClickKind::OpenLateralityPicker => {
click.sides_present = Some(sides_present(active, annotation));
}
ZoneClickKind::RemoveBothSides => {
click.observation = Some(remove_all_sides(active, annotation));
}
ZoneClickKind::Toggle => click.observation = Some(toggle_zone(active, annotation)),
_ => {}
}
click
}
+1
View File
@@ -1,6 +1,7 @@
//! Data contracts and business rules of the core (R2: sheet, report, archive, editor rules).
pub mod archive;
pub mod editor;
pub mod js;
pub mod report;
pub mod sheet;
+475
View File
@@ -0,0 +1,475 @@
//! The editor rules against the TypeScript they replace: every case of
//! `tests/oracles/editor.json` (frozen from `zoneInteraction.ts`, the findings picker, the
//! vertebra picker and the store by `apps/app/tests/unit/r2.editor-characterisation.test.ts`)
//! runs through the Rust functions, and the `services.zoneInteraction.test.ts` suite is ported
//! with its exact expectations.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::editor::{
self, EditorError, LeafClick, MoveDirection, NewReportDraft, NewReportStamp, VertebraAction,
ZoneClickKind,
};
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::report::{LateralSide, Observation, Report, SheetRef, Vertebra};
use faunosteo_core::domain::sheet::{BundledSheetData, IndexedDocument, LoadedSheet};
use faunosteo_core::json::to_js_pretty;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value, json};
/// Cases whose TypeScript output only differs from the Rust one by key order (D-R11: the core
/// prints every object in the contract's field order). `newZone` writes `side` after the
/// label snapshots, `syncVertebrae` appends `vertebrae` to a spawned zone, the store's
/// `newReport` spreads the draft before stamping version, id and dates. Every other case is
/// byte-equal; these are equal once keys are sorted.
const ORDER_ONLY: [&str; 8] = [
"add left side",
"add both sides to left",
"add an existing side changes nothing",
"sync spawns zones for new regions and prunes the emptied one",
"sync falls back to the main view spine annotation",
"sync spawns zones in first-seen region order",
"new report starts with one empty observation",
"new report keeps the draft observations",
];
fn draft_sheet() -> LoadedSheet {
let seed = "supabase/seed/anatomical-sheets/equine/draft";
let payload = json!({
"status": "draft",
"ref": {
"sheet_id": "s", "version_id": null, "document_sha256": "0".repeat(64),
"schema_version": 2, "species_id": "equine"
},
"document": parse_json(&common::repo_file(&format!("{seed}/document.json"))).unwrap(),
"migrationMap": parse_json(&common::repo_file(&format!("{seed}/report-migration-map.json"))).unwrap(),
"assets": {}, "assetHashes": {}
});
let data: BundledSheetData = serde_json::from_value(payload).unwrap();
LoadedSheet::from_bundle(data).unwrap()
}
fn field<T: DeserializeOwned>(input: &Value, name: &str) -> T {
serde_json::from_value(input[name].clone()).unwrap_or_else(|e| panic!("{name}: {e}"))
}
fn text<T: Serialize>(value: &T) -> String {
to_js_pretty(value).unwrap()
}
fn run_zone(sheet: &IndexedDocument<'_>, function: &str, input: &Value) -> Option<String> {
let observation = || field::<Observation>(input, "observation");
Some(match function {
"zone_click" => {
let active: Option<Observation> = field(input, "observation");
let id: String = field(input, "annotationId");
text(&editor::zone_click(sheet, active.as_ref(), &id))
}
"add_sides" => {
let sides: Vec<LateralSide> = field(input, "sides");
let id: String = field(input, "annotationId");
text(&editor::add_sides(sheet, &observation(), &id, &sides).unwrap())
}
"remove_zone_at" => text(&editor::remove_zone_at(
&observation(),
field(input, "index"),
)),
"vertebra_initial" => text(&editor::vertebra_initial(
sheet,
&observation(),
field(input, "zoneIndex"),
)),
"sync_vertebrae" => {
let selection: Vec<Vertebra> = field(input, "selection");
let view: String = field(input, "viewId");
text(&editor::sync_vertebrae(
sheet,
&observation(),
&selection,
&view,
))
}
_ => return None,
})
}
fn run_finding(sheet: &IndexedDocument<'_>, input: &Value) -> String {
let path: Vec<String> = field(input, "path");
let zone: String = field(input, "findingZoneId");
let side: Option<LateralSide> = field(input, "side");
let click = LeafClick {
finding_zone_id: &zone,
path: &path,
leaf_position: field(input, "leafPosition"),
side,
};
let observation: Observation = field(input, "observation");
text(&editor::toggle_finding(sheet, &observation, &click).unwrap())
}
fn run_report(function: &str, input: &Value) -> String {
let report = || field::<Report>(input, "report");
match function {
"vertebra_select" => {
let selection: Vec<Vertebra> = field(input, "selection");
let action: VertebraAction = field(input, "action");
text(&editor::select_vertebrae(&selection, &action).unwrap())
}
"new_report" => {
let (id, at, obs): (String, String, String) = (
field(input, "id"),
field(input, "createdAt"),
field(input, "observationId"),
);
let stamp = NewReportStamp {
id: &id,
created_at: &at,
observation_id: &obs,
};
let draft: NewReportDraft = field(input, "draft");
let sheet: SheetRef = field(input, "sheet");
text(&editor::new_report(draft, sheet, &stamp))
}
"add_observation" => {
let id: String = field(input, "id");
text(&editor::add_observation(&report(), &id))
}
"remove_observation" => text(&editor::remove_observation(
&report(),
field(input, "index"),
)),
"move_observation" => {
let direction: MoveDirection = field(input, "direction");
text(&editor::move_observation(&report(), field(input, "index"), direction).unwrap())
}
other => panic!("unknown function {other}"),
}
}
/// Objects with their keys sorted, recursively: equality up to key order.
fn canonical(value: &Value) -> Value {
match value {
Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
let sorted: Map<String, Value> = keys
.into_iter()
.map(|k| (k.clone(), canonical(&map[k])))
.collect();
Value::Object(sorted)
}
Value::Array(items) => Value::Array(items.iter().map(canonical).collect()),
other => other.clone(),
}
}
#[test]
fn every_frozen_typescript_case_gives_the_same_output_in_rust() {
let sheet = draft_sheet();
let indexed = sheet.indexed();
let oracle = parse_json(&common::repo_file("crates/core/tests/oracles/editor.json")).unwrap();
let cases = oracle["cases"].as_array().unwrap();
assert_eq!(cases.len(), 49);
let mut order_only = Vec::new();
for case in cases {
let name = case["name"].as_str().unwrap();
let function = case["fn"].as_str().unwrap();
let input = &case["input"];
let actual = match function {
"toggle_finding" => run_finding(&indexed, input),
_ => run_zone(&indexed, function, input).unwrap_or_else(|| run_report(function, input)),
};
let expected = text(&case["output"]);
if actual == expected {
continue;
}
let same = canonical(&serde_json::from_str(&actual).unwrap())
== canonical(&serde_json::from_str(&expected).unwrap());
assert!(same, "{name}\nrust: {actual}\nts: {expected}");
order_only.push(name);
}
assert_eq!(order_only, ORDER_ONLY);
}
// --- services.zoneInteraction.test.ts, ported one to one ---------------------------------
fn empty() -> Observation {
serde_json::from_value(json!({
"id": "obs-1", "zones": [], "findings": [], "freeTextFindings": [], "comment": ""
}))
.unwrap()
}
fn click(sheet: &IndexedDocument<'_>, obs: Option<&Observation>, id: &str) -> ZoneClickKind {
editor::zone_click(sheet, obs, id).kind
}
fn after(sheet: &IndexedDocument<'_>, obs: &Observation, id: &str) -> Observation {
editor::zone_click(sheet, Some(obs), id)
.observation
.unwrap()
}
#[test]
fn opens_the_detail_view_for_the_trigger_even_without_an_active_observation() {
let sheet = draft_sheet();
let s = sheet.indexed();
for obs in [None, Some(&empty())] {
let out = editor::zone_click(&s, obs, "head-trigger");
assert_eq!(out.kind, ZoneClickKind::OpenView);
assert_eq!(out.view_id.as_deref(), Some("head"));
}
}
#[test]
fn only_activates_a_fallback_observation_when_none_is_active() {
let sheet = draft_sheet();
let s = sheet.indexed();
assert_eq!(click(&s, None, "c7-t1"), ZoneClickKind::ActivateFallback);
assert_eq!(click(&s, Some(&empty()), "nope"), ZoneClickKind::Ignore);
}
#[test]
fn always_opens_the_vertebra_picker_on_a_spine_zone() {
let sheet = draft_sheet();
let s = sheet.indexed();
let obs = editor::zone_click(&s, Some(&empty()), "cervical")
.observation
.unwrap();
assert_eq!(
click(&s, Some(&empty()), "cervical"),
ZoneClickKind::OpenVertebraPicker
);
assert_eq!(
click(&s, Some(&obs), "cervical"),
ZoneClickKind::OpenVertebraPicker
);
}
#[test]
fn routes_bilateral_zones_through_the_side_picker_or_clears_both_sides() {
let sheet = draft_sheet();
let s = sheet.indexed();
assert_eq!(
click(&s, Some(&empty()), "hip"),
ZoneClickKind::OpenLateralityPicker
);
let left = editor::add_sides(&s, &empty(), "hip", &[LateralSide::Left]).unwrap();
assert_eq!(
click(&s, Some(&left), "hip"),
ZoneClickKind::OpenLateralityPicker
);
let both = editor::add_sides(&s, &left, "hip", &[LateralSide::Right]).unwrap();
assert_eq!(
click(&s, Some(&both), "hip"),
ZoneClickKind::RemoveBothSides
);
}
#[test]
fn toggles_plain_zones_and_splits_the_observable_annotations_as_the_sheet_says() {
let sheet = draft_sheet();
let s = sheet.indexed();
assert_eq!(click(&s, Some(&empty()), "c7-t1"), ZoneClickKind::Toggle);
let kinds: Vec<ZoneClickKind> = s
.document
.annotations
.iter()
.filter_map(|a| a.observable())
.map(|a| click(&s, Some(&empty()), &a.id))
.collect();
let count = |k: ZoneClickKind| kinds.iter().filter(|x| **x == k).count();
assert_eq!(count(ZoneClickKind::OpenLateralityPicker), 10);
assert_eq!(count(ZoneClickKind::OpenVertebraPicker), 5);
assert_eq!(count(ZoneClickKind::Toggle), 12);
}
#[test]
fn toggle_zone_adds_a_zone_with_snapshots_then_removes_it() {
let sheet = draft_sheet();
let s = sheet.indexed();
let added = after(&s, &empty(), "c7-t1");
assert_eq!(
serde_json::to_value(&added.zones).unwrap(),
json!([{
"annotationId": "c7-t1",
"viewId": "main",
"labelFrSnapshot": "Charnière C7-T1 (cervico-thoracique)",
"labelEnSnapshot": "C7-T1 junction (cervicothoracic)"
}])
);
assert!(after(&s, &added, "c7-t1").zones.is_empty());
}
#[test]
fn ensure_zone_keeps_an_existing_zone_and_reports_its_index() {
let sheet = draft_sheet();
let s = sheet.indexed();
let base = after(&s, &empty(), "c7-t1");
let base = editor::zone_click(&s, Some(&base), "cervical")
.observation
.unwrap();
let again = editor::zone_click(&s, Some(&base), "cervical");
assert_eq!(again.zone_index, Some(1));
assert!(again.observation.is_none());
let fresh = editor::zone_click(&s, Some(&empty()), "cervical");
assert_eq!(fresh.zone_index, Some(0));
assert_eq!(
fresh.observation.unwrap().zones[0].annotation_id,
"cervical"
);
}
#[test]
fn add_sides_appends_only_the_missing_sides_and_never_removes_one() {
let sheet = draft_sheet();
let s = sheet.indexed();
let left = editor::add_sides(&s, &empty(), "hip", &[LateralSide::Left]).unwrap();
let opened = editor::zone_click(&s, Some(&left), "hip");
assert_eq!(opened.sides_present, Some(vec![LateralSide::Left]));
let same = editor::add_sides(&s, &left, "hip", &[LateralSide::Left]).unwrap();
assert_eq!(same, left);
let both = editor::add_sides(&s, &left, "hip", &[LateralSide::Left, LateralSide::Right]);
let both = both.unwrap();
let sides: Vec<Option<LateralSide>> = both.zones.iter().map(|z| z.side).collect();
assert_eq!(sides, [Some(LateralSide::Left), Some(LateralSide::Right)]);
assert!(after(&s, &both, "hip").zones.is_empty());
}
#[test]
fn remove_zone_at_removes_one_zone_by_index_and_keeps_findings() {
let sheet = draft_sheet();
let s = sheet.indexed();
let mut obs = after(&s, &empty(), "c7-t1");
obs.findings = serde_json::from_value(json!([{
"findingZoneId": "c7-t1",
"path": ["c7-t1-dysfunctions", "segmental", "fixation"],
"labelFrSnapshot": "F",
"labelEnSnapshot": "F"
}]))
.unwrap();
let out = editor::remove_zone_at(&obs, 0);
assert!(out.zones.is_empty());
assert_eq!(out.findings.len(), 1);
}
#[test]
fn detail_view_zones_are_distinct_from_main_view_zones_with_the_same_id() {
let sheet = draft_sheet();
let s = sheet.indexed();
let obs = after(&s, &empty(), "atm");
assert_eq!(obs.zones[0].annotation_id, "atm");
assert_eq!(obs.zones[0].view_id, "head");
assert_eq!(click(&s, Some(&obs), "atm"), ZoneClickKind::Toggle);
}
fn vertebrae(list: Value) -> Vec<Vertebra> {
serde_json::from_value(list).unwrap()
}
#[test]
fn collects_vertebrae_across_spine_zones_the_priority_zone_first() {
let sheet = draft_sheet();
let s = sheet.indexed();
let mut obs = empty();
obs.zones = serde_json::from_value(json!([
{ "annotationId": "thoracic", "viewId": "main", "vertebrae": [{ "region": "T", "index": 2 }] },
{ "annotationId": "cervical", "viewId": "main",
"vertebrae": [{ "region": "C", "index": 3 }, { "region": "C", "index": 4 }] },
{ "annotationId": "c7-t1", "viewId": "main" }
]))
.unwrap();
assert_eq!(
editor::collect_vertebrae(&s, &obs, 1),
vertebrae(json!([
{ "region": "C", "index": 3 }, { "region": "C", "index": 4 }, { "region": "T", "index": 2 }
]))
);
}
#[test]
fn replaces_per_region_prunes_emptied_zones_and_spawns_zones_for_new_regions() {
let sheet = draft_sheet();
let s = sheet.indexed();
let base = editor::zone_click(&s, Some(&empty()), "cervical")
.observation
.unwrap();
let selection = vertebrae(json!([
{ "region": "L", "index": 3 }, { "region": "L", "index": 4 }, { "region": "Cd", "index": 20 }
]));
let out = editor::sync_vertebrae(&s, &base, &selection, "main");
let ids: Vec<&str> = out.zones.iter().map(|z| z.annotation_id.as_str()).collect();
assert_eq!(ids, ["lumbar", "caudal"]);
assert_eq!(out.zones[0].vertebrae.as_deref(), Some(&selection[..2]));
assert_eq!(
out.zones[0].label_fr_snapshot.as_deref(),
Some("Vertèbres lombaires")
);
assert!(
editor::sync_vertebrae(&s, &out, &[], "main")
.zones
.is_empty()
);
}
#[test]
fn keeps_non_spine_zones_untouched_and_ignores_unknown_regions() {
let sheet = draft_sheet();
let s = sheet.indexed();
let base = after(&s, &empty(), "c7-t1");
let selection = vertebrae(json!([{ "region": "XX", "index": 1 }]));
assert_eq!(
editor::sync_vertebrae(&s, &base, &selection, "main").zones,
base.zones
);
}
// --- closed failure kinds (inputs the TypeScript UI never produced) -------------------
#[test]
fn inputs_the_typescript_never_produced_are_closed_failures() {
let sheet = draft_sheet();
let s = sheet.indexed();
let missing = editor::add_sides(&s, &empty(), "nope", &[LateralSide::Left]);
assert_eq!(missing.unwrap_err().kind(), "unknown_annotation");
let path = vec![
"c7-t1-dysfunctions".to_owned(),
"segmental".to_owned(),
"nope".to_owned(),
];
let leaf = |zone: &'static str, position| LeafClick {
finding_zone_id: zone,
path: &path,
leaf_position: position,
side: None,
};
let unknown_zone = editor::toggle_finding(&s, &empty(), &leaf("nope", 0));
assert_eq!(unknown_zone.unwrap_err(), EditorError::UnknownZone);
let wrong_id = editor::toggle_finding(&s, &empty(), &leaf("c7-t1", 0));
assert_eq!(wrong_id.unwrap_err(), EditorError::UnknownNode);
let out_of_list = editor::toggle_finding(&s, &empty(), &leaf("c7-t1", 999));
assert_eq!(out_of_list.unwrap_err().kind(), "unknown_node");
let huge: VertebraAction =
serde_json::from_value(json!({ "kind": "all", "region": "C", "count": 1e9 })).unwrap();
assert_eq!(
editor::select_vertebrae(&[], &huge).unwrap_err().kind(),
"invalid_count"
);
let none: VertebraAction =
serde_json::from_value(json!({ "kind": "all", "region": "C", "count": -2 })).unwrap();
assert!(editor::select_vertebrae(&[], &none).unwrap().is_empty());
let report: Report = serde_json::from_value(
parse_json(&common::repo_file(
"apps/app/tests/fixtures/report-v3.demo.json",
))
.unwrap(),
)
.unwrap();
let past_end = report.observations.len();
let moved = editor::move_observation(&report, past_end, MoveDirection::Up);
assert_eq!(moved.unwrap_err(), EditorError::InvalidIndex);
let down = editor::move_observation(&report, usize::MAX, MoveDirection::Down).unwrap();
assert_eq!(down, report);
}
File diff suppressed because it is too large. Load diff