From 22fea8736dc925c8cbceb8b79dd1fb4f12eb1458 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 14 Oct 2026 00:05:26 +0200 Subject: [PATCH] =?UTF-8?q?feat(domain):=20Rust=20sheet=20index=20and=20lo?= =?UTF-8?q?aded=20sheet=20(bundle=20payload=20=E2=86=92=20document,=20migr?= =?UTF-8?q?ation=20map,=20positions)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lookups follow the TypeScript index: by-id maps keep the last duplicate as new Map does, spine annotations and finding paths take the first match as Array.find does; a document without a main view cannot be indexed. --- crates/core/src/domain/sheet/index.rs | 180 +++++++++++++++++++++++++ crates/core/src/domain/sheet/loaded.rs | 106 +++++++++++++++ crates/core/src/domain/sheet/mod.rs | 6 +- crates/core/tests/sheet_contract.rs | 29 ++++ 4 files changed, 320 insertions(+), 1 deletion(-) create mode 100644 crates/core/src/domain/sheet/index.rs create mode 100644 crates/core/src/domain/sheet/loaded.rs diff --git a/crates/core/src/domain/sheet/index.rs b/crates/core/src/domain/sheet/index.rs new file mode 100644 index 00000000..676a930d --- /dev/null +++ b/crates/core/src/domain/sheet/index.rs @@ -0,0 +1,180 @@ +//! Read-only lookups over a sheet document (`anatomical-sheet/sheet-index.ts`). +//! +//! Lookups by id follow the TypeScript `Map` built from the document: the last entry with a +//! given id wins. `spine_annotation` and finding paths walk the document with `find`, so the +//! first match wins there. Both policies only differ on documents the integrity rules reject. + +use std::collections::HashMap; + +use super::schema::{ + AnatomicalSheetDocument, Annotation, FindingTreeItem, FindingZone, LocalizedText, + ObservableAnnotation, SheetView, VertebralRegion, +}; + +/// Positions by id, last entry wins (as `new Map(list.map(x => [x.id, x]))`). +fn positions<'a>(ids: impl Iterator) -> HashMap { + ids.enumerate() + .map(|(position, id)| (id.to_owned(), position)) + .collect() +} + +/// The sheet has no main view: it cannot be indexed (`buildSheetIndex` throws). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NoMainView; + +/// Position maps over one document; borrow it through [`IndexedDocument`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SheetIndex { + views: HashMap, + annotations: HashMap, + zones: HashMap, + regions: HashMap, + main_view: usize, +} + +impl SheetIndex { + pub fn build(document: &AnatomicalSheetDocument) -> Result { + let main_view = document + .views + .iter() + .position(SheetView::is_main) + .ok_or(NoMainView)?; + Ok(Self { + views: positions(document.views.iter().map(SheetView::id)), + annotations: positions(document.annotations.iter().map(Annotation::id)), + zones: positions(document.finding_zones.iter().map(|z| z.id.as_str())), + regions: positions( + document + .vertebral_config + .regions + .iter() + .map(|r| r.code.as_str()), + ), + main_view, + }) + } + + /// Lookups over `document`, which must be the document the index was built from. + pub fn over<'a>(&'a self, document: &'a AnatomicalSheetDocument) -> IndexedDocument<'a> { + IndexedDocument { + document, + index: self, + } + } + + pub fn annotation_positions(&self) -> &HashMap { + &self.annotations + } + + pub fn view_positions(&self) -> &HashMap { + &self.views + } + + pub fn zone_positions(&self) -> &HashMap { + &self.zones + } + + pub fn main_view_position(&self) -> usize { + self.main_view + } +} + +/// A document with its index: the lookups of the TypeScript `SheetIndex`. +#[derive(Clone, Copy)] +pub struct IndexedDocument<'a> { + pub document: &'a AnatomicalSheetDocument, + index: &'a SheetIndex, +} + +impl<'a> IndexedDocument<'a> { + pub fn main_view(&self) -> &'a SheetView { + &self.document.views[self.index.main_view] + } + + pub fn view(&self, id: &str) -> Option<&'a SheetView> { + self.index.views.get(id).map(|&p| &self.document.views[p]) + } + + pub fn annotation(&self, id: &str) -> Option<&'a Annotation> { + self.index + .annotations + .get(id) + .map(|&p| &self.document.annotations[p]) + } + + pub fn annotations_of_view(&self, view_id: &str) -> impl Iterator { + let view_id = view_id.to_owned(); + self.document + .annotations + .iter() + .filter(move |a| a.view_id() == view_id) + } + + pub fn finding_zone(&self, id: &str) -> Option<&'a FindingZone> { + self.index + .zones + .get(id) + .map(|&p| &self.document.finding_zones[p]) + } + + /// The category or node at a path, `None` when absent: each segment is the first child + /// with that id (`Array.prototype.find`). + pub fn node_at(&self, zone_id: &str, path: &[String]) -> Option> { + let zone = self.finding_zone(zone_id)?; + let (first, rest) = path.split_first()?; + let mut node = FindingTreeItem::Category(zone.categories.iter().find(|c| &c.id == first)?); + for segment in rest { + let child = node.children().iter().find(|n| &n.id == segment)?; + node = FindingTreeItem::Node(child); + } + Some(node) + } + + pub fn regions(&self) -> &'a [VertebralRegion] { + &self.document.vertebral_config.regions + } + + pub fn region(&self, code: &str) -> Option<&'a VertebralRegion> { + self.index + .regions + .get(code) + .map(|&p| &self.document.vertebral_config.regions[p]) + } + + /// The annotation that opens the vertebra picker for a region on a view (first match). + pub fn spine_annotation( + &self, + region_code: &str, + view_id: &str, + ) -> Option<&'a ObservableAnnotation> { + self.document + .annotations + .iter() + .filter_map(Annotation::observable) + .find(|a| { + a.view_id == view_id && a.vertebral_region_code.as_deref() == Some(region_code) + }) + } + + /// Whether the annotation with this id opens the vertebra picker. + pub fn is_spine(&self, annotation_id: &str) -> bool { + self.annotation(annotation_id) + .and_then(Annotation::observable) + .is_some_and(|a| a.vertebral_region_code.is_some()) + } + + /// The display name: an observable annotation's own, a trigger's own or its view's. + pub fn name(&self, annotation: &'a Annotation) -> LocalizedText { + match annotation { + Annotation::Observable(a) => a.name.clone(), + Annotation::DetailTrigger(t) => t + .name + .clone() + .or_else(|| self.view(&t.opens_view_id).map(|v| v.name().clone())) + .unwrap_or_else(|| LocalizedText { + fr: String::new(), + en: String::new(), + }), + } + } +} diff --git a/crates/core/src/domain/sheet/loaded.rs b/crates/core/src/domain/sheet/loaded.rs new file mode 100644 index 00000000..dcbdc9aa --- /dev/null +++ b/crates/core/src/domain/sheet/loaded.rs @@ -0,0 +1,106 @@ +//! The sheet the application works on for a session (`apps/app/src/sheets/provider.ts`): +//! read once from the bundled payload, then indexed. Its document and migration map pass the +//! strict schemas; the provenance fields come from the build and are taken as they are. + +use std::collections::HashMap; + +use serde::Deserialize; + +use super::index::{IndexedDocument, NoMainView, SheetIndex}; +use super::schema::AnatomicalSheetDocument; +use crate::domain::archive::SheetStatus; +use crate::domain::js::JsInt; +use crate::domain::report::{ReportMigrationMap, SheetRef}; + +/// The payload of `virtual:faunosteo-sheet` (`BundledSheetData`). +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BundledSheetData { + pub status: SheetStatus, + #[serde(rename = "ref")] + pub reference: BundledRef, + pub document: serde_json::Value, + pub migration_map: serde_json::Value, + pub assets: HashMap, + pub asset_hashes: HashMap, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct BundledRef { + pub sheet_id: String, + pub version_id: Option, + pub document_sha256: String, + pub schema_version: JsInt, + pub species_id: String, +} + +/// A loaded, indexed sheet. +#[derive(Debug, Clone)] +pub struct LoadedSheet { + pub status: SheetStatus, + pub reference: SheetRef, + pub species_id: String, + /// Document schema version of the sheet (`ref.schema_version`). + pub schema_version: JsInt, + pub document: AnatomicalSheetDocument, + /// SVG text by `svg_asset_id`. + pub assets: HashMap, + /// sha256 by `svg_asset_id`; carried into an archive as provenance. + pub asset_hashes: HashMap, + pub migration_map: ReportMigrationMap, + index: SheetIndex, +} + +/// Why a bundled sheet cannot be loaded. +#[derive(Debug)] +pub enum LoadError { + /// The payload, the document or the migration map fails its schema. + Shape(serde_json::Error), + /// The document has no main view. + NoMainView, +} + +impl From for LoadError { + fn from(error: serde_json::Error) -> Self { + Self::Shape(error) + } +} + +impl From for LoadError { + fn from(_: NoMainView) -> Self { + Self::NoMainView + } +} + +impl LoadedSheet { + /// `parseBundledSheet` then `buildSheetIndex`. + pub fn from_bundle(data: BundledSheetData) -> Result { + let document: AnatomicalSheetDocument = serde_json::from_value(data.document)?; + let migration_map: ReportMigrationMap = serde_json::from_value(data.migration_map)?; + let index = SheetIndex::build(&document)?; + let r = data.reference; + Ok(Self { + status: data.status, + reference: SheetRef { + sheet_id: r.sheet_id, + version_id: r.version_id, + document_sha256: r.document_sha256, + }, + species_id: r.species_id, + schema_version: r.schema_version, + document, + assets: data.assets, + asset_hashes: data.asset_hashes, + migration_map, + index, + }) + } + + pub fn indexed(&self) -> IndexedDocument<'_> { + self.index.over(&self.document) + } + + pub fn index(&self) -> &SheetIndex { + &self.index + } +} diff --git a/crates/core/src/domain/sheet/mod.rs b/crates/core/src/domain/sheet/mod.rs index 5f22909a..9ee4ee18 100644 --- a/crates/core/src/domain/sheet/mod.rs +++ b/crates/core/src/domain/sheet/mod.rs @@ -1,5 +1,9 @@ -//! The anatomical sheet: document contract, integrity rules, index. +//! The anatomical sheet: document contract, index, the loaded sheet of a session. +pub mod index; +pub mod loaded; pub mod schema; +pub use index::{IndexedDocument, NoMainView, SheetIndex}; +pub use loaded::{BundledSheetData, LoadError, LoadedSheet}; pub use schema::*; diff --git a/crates/core/tests/sheet_contract.rs b/crates/core/tests/sheet_contract.rs index 51edf2d8..ea5459cc 100644 --- a/crates/core/tests/sheet_contract.rs +++ b/crates/core/tests/sheet_contract.rs @@ -24,3 +24,32 @@ fn the_curated_draft_prints_as_zod_outputs_it() { fn the_legacy_import_baseline_prints_as_zod_outputs_it() { assert_like_zod("sheet.legacy-import.json"); } + +#[test] +fn the_bundled_payload_loads_and_indexes_the_draft() { + use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet}; + let seed = "supabase/seed/anatomical-sheets/equine/draft"; + let payload = serde_json::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(); + let sheet = LoadedSheet::from_bundle(data).unwrap(); + let indexed = sheet.indexed(); + assert_eq!(indexed.main_view().id(), "main"); + assert!( + indexed.is_spine("c7-t1") + || indexed + .document + .annotations + .iter() + .any(|a| indexed.is_spine(a.id())) + ); + assert!(indexed.annotation("hip").is_some()); +}