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:
1 parent
0c47d0f837
commit
3639c8778e
9 files changed
+4465
No files matched your search
@@ -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())
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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, ®ion, view_id)
|
||||
.or_else(|| spine_annotation(sheet, ®ion, &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,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;
|
||||
|
||||
Reference in new issue
Block a user