feat(domain): Rust sheet index and loaded sheet (bundle payload → document, migration map, positions)

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.
This commit is contained in:
bchanot committed 2026-10-14 00:05:26 +02:00
1 parent ee0700887f
commit 22fea8736d
4 files changed
+320 -1

No files matched your search

+180
View File
@@ -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<Item = &'a str>) -> HashMap<String, usize> {
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<String, usize>,
annotations: HashMap<String, usize>,
zones: HashMap<String, usize>,
regions: HashMap<String, usize>,
main_view: usize,
}
impl SheetIndex {
pub fn build(document: &AnatomicalSheetDocument) -> Result<Self, NoMainView> {
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<String, usize> {
&self.annotations
}
pub fn view_positions(&self) -> &HashMap<String, usize> {
&self.views
}
pub fn zone_positions(&self) -> &HashMap<String, usize> {
&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<Item = &'a Annotation> {
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<FindingTreeItem<'a>> {
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(),
}),
}
}
}
+106
View File
@@ -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<String, String>,
pub asset_hashes: HashMap<String, String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct BundledRef {
pub sheet_id: String,
pub version_id: Option<String>,
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<String, String>,
/// sha256 by `svg_asset_id`; carried into an archive as provenance.
pub asset_hashes: HashMap<String, String>,
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<serde_json::Error> for LoadError {
fn from(error: serde_json::Error) -> Self {
Self::Shape(error)
}
}
impl From<NoMainView> for LoadError {
fn from(_: NoMainView) -> Self {
Self::NoMainView
}
}
impl LoadedSheet {
/// `parseBundledSheet` then `buildSheetIndex`.
pub fn from_bundle(data: BundledSheetData) -> Result<Self, LoadError> {
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
}
}
+5 -1
View File
@@ -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::*;
+29
View File
@@ -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());
}