Files
faunosteo/apps/app/tests/unit/r2.editor-characterisation.test.ts
T
bchanot 3639c8778e 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.
2026-10-14 00:17:22 +02:00

715 lines
20 KiB
TypeScript

/**
* 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'))
})
})