feat(anatomy): annotation layer in Rust (O2 exact, attribute order kept)

This commit is contained in:
bchanot committed 2026-10-14 23:48:07 +02:00
1 parent ab41084a36
commit 67d9af3f79
3 files changed
+360

No files matched your search

+270
View File
@@ -0,0 +1,270 @@
//! The annotation layer of one view (`packages/anatomy/src/render/layer.ts`, contract
//! `docs/ANNOTATION-RENDERING.md`): markers drawn from the document, in document order, with
//! the TypeScript attribute order (the review drawings are byte goldens of it until R5).
use std::collections::{HashMap, HashSet};
use super::svg::{Element, Node};
use crate::domain::sheet::{AnatomicalSheetDocument, Annotation, Geometry, Laterality, SheetView};
use crate::json::js_number;
pub const FALLBACK_COLOR: &str = "#888888";
/// Why a layer cannot be drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LayerError {
UnknownView,
}
/// The view of that id (first match, as `Array.find`).
pub fn find_view<'a>(
document: &'a AnatomicalSheetDocument,
view_id: &str,
) -> Option<&'a SheetView> {
document.views.iter().find(|v| v.id() == view_id)
}
/// `renderAnnotationLayer({ document, viewId, states })`: `states` holds the ids marked
/// `data-state="current"`.
pub fn render_layer(
document: &AnatomicalSheetDocument,
view_id: &str,
states: &HashSet<&str>,
) -> Result<Element, LayerError> {
let view = find_view(document, view_id).ok_or(LayerError::UnknownView)?;
let context = Context {
twin_opacity: if view.is_main() { "0.65" } else { "0.5" },
categories: document
.categories
.iter()
.map(|c| (c.id.as_str(), c.color.as_deref()))
.collect(),
view_names: document
.views
.iter()
.map(|v| (v.id(), v.name().fr.as_str()))
.collect(),
states,
};
let children = document
.annotations
.iter()
.filter(|a| a.view_id() == view_id)
.flat_map(|a| context.elements(a))
.map(Node::Element)
.collect();
let attrs = vec![
("data-layer", "annotations".to_owned()),
("data-view-id", view_id.to_owned()),
];
Ok(Element::svg("g", attrs, children))
}
struct Context<'a> {
twin_opacity: &'static str,
/// Last duplicate wins, as a JavaScript `Map` built from the list.
categories: HashMap<&'a str, Option<&'a str>>,
view_names: HashMap<&'a str, &'a str>,
states: &'a HashSet<&'a str>,
}
type Attrs = Vec<(&'static str, String)>;
impl Context<'_> {
fn elements(&self, annotation: &Annotation) -> Vec<Element> {
let (geometry, color) = match annotation {
Annotation::Observable(a) => (a.geometry.as_ref(), a.color.as_deref()),
Annotation::DetailTrigger(a) => (a.geometry.as_ref(), a.color.as_deref()),
};
let Some(geometry) = geometry else {
return Vec::new();
};
let color = color
.or_else(|| {
self.categories
.get(annotation.category_id())
.copied()
.flatten()
})
.unwrap_or(FALLBACK_COLOR)
.to_owned();
let data = self.data_attrs(annotation);
let label = format!(
"{} / {}",
value_of(&data, "data-anno-name-fr"),
value_of(&data, "data-anno-name-en")
);
if annotation.trigger().is_some() {
return vec![shape(geometry, &color, trigger_visual(), &data, &label)];
}
match geometry {
Geometry::Circle(c) => self.point(c.cx, c.cy, c.r, &color, &data, &label),
_ => vec![shape(geometry, &color, zone_visual(), &data, &label)],
}
}
fn data_attrs(&self, annotation: &Annotation) -> Attrs {
let mut data: Attrs = vec![("data-anno-id", annotation.id().to_owned())];
match annotation {
Annotation::DetailTrigger(t) => {
let opened = self
.view_names
.get(t.opens_view_id.as_str())
.copied()
.unwrap_or("");
data.push(("data-anno-kind", "detail_trigger".to_owned()));
data.push(("data-anno-lateral", laterality(t.laterality).to_owned()));
data.push(("data-anno-opens-view", t.opens_view_id.clone()));
let names = t
.name
.as_ref()
.map_or((opened, opened), |n| (n.fr.as_str(), n.en.as_str()));
data.push(("data-anno-name-fr", names.0.to_owned()));
data.push(("data-anno-name-en", names.1.to_owned()));
}
Annotation::Observable(o) => {
let kind = match o.kind {
crate::domain::sheet::ObservableKind::Point => "point",
crate::domain::sheet::ObservableKind::Zone => "zone",
};
data.push(("data-anno-kind", kind.to_owned()));
data.push(("data-anno-lateral", laterality(o.laterality).to_owned()));
data.push(("data-anno-name-fr", o.name.fr.clone()));
data.push(("data-anno-name-en", o.name.en.clone()));
if let Some(zone) = o.finding_zone_id.as_deref().filter(|z| !z.is_empty()) {
data.push(("data-anno-zone", zone.to_owned()));
}
if let Some(region) = o.vertebral_region_code.as_deref().filter(|r| !r.is_empty()) {
data.push(("data-anno-region", region.to_owned()));
}
}
}
if self.states.contains(annotation.id()) {
data.push(("data-state", "current".to_owned()));
}
data
}
/// A transparent hitbox, then the visible twin on top.
fn point(
&self,
cx: f64,
cy: f64,
r: f64,
color: &str,
data: &Attrs,
label: &str,
) -> Vec<Element> {
let mut hitbox: Attrs = vec![
("cx", js_number(cx)),
("cy", js_number(cy)),
("r", js_number(r)),
("fill", "transparent".to_owned()),
("pointer-events", "all".to_owned()),
("style", "cursor:pointer".to_owned()),
];
hitbox.extend(data.iter().cloned());
let mut visible: Attrs = vec![
("cx", js_number(cx)),
("cy", js_number(cy)),
("r", js_number(2.0_f64.max(r - 12.0))),
("fill", color.to_owned()),
("fill-opacity", self.twin_opacity.to_owned()),
("stroke", "#000".to_owned()),
("stroke-width", "1.5".to_owned()),
("pointer-events", "none".to_owned()),
];
visible.extend(data.iter().cloned());
vec![
titled("circle", hitbox, label),
titled("circle", visible, label),
]
}
}
fn value_of<'a>(attrs: &'a Attrs, name: &str) -> &'a str {
attrs
.iter()
.find(|(k, _)| *k == name)
.map_or("", |(_, v)| v.as_str())
}
fn laterality(value: Laterality) -> &'static str {
match value {
Laterality::Unpaired => "unpaired",
Laterality::Bilateral => "bilateral",
Laterality::Left => "left",
Laterality::Right => "right",
}
}
fn zone_visual() -> Attrs {
vec![
("fill-opacity", "0.3".to_owned()),
("stroke-width", "2".to_owned()),
("pointer-events", "all".to_owned()),
("style", "cursor:pointer".to_owned()),
]
}
fn trigger_visual() -> Attrs {
vec![
("fill-opacity", "0.06".to_owned()),
("stroke-width", "2".to_owned()),
("stroke-dasharray", "8,4".to_owned()),
("pointer-events", "all".to_owned()),
("style", "cursor:pointer".to_owned()),
("class", "detail-zone".to_owned()),
]
}
/// The tag and geometry attributes of a shape.
fn geometry_attrs(geometry: &Geometry) -> (&'static str, Attrs) {
match geometry {
Geometry::Circle(c) => (
"circle",
vec![
("cx", js_number(c.cx)),
("cy", js_number(c.cy)),
("r", js_number(c.r)),
],
),
Geometry::Polygon(p) => {
let points: Vec<String> = p
.points
.iter()
.map(|pt| format!("{},{}", js_number(pt.0), js_number(pt.1)))
.collect();
("polygon", vec![("points", points.join(" "))])
}
Geometry::Path(path) => ("path", vec![("d", path.d.clone())]),
}
}
/// `{ ...geometry, fill, stroke, ...visual, ...data }` with the title child.
fn shape(geometry: &Geometry, color: &str, visual: Attrs, data: &Attrs, label: &str) -> Element {
let (tag, mut attrs) = geometry_attrs(geometry);
attrs.push(("fill", color.to_owned()));
attrs.push(("stroke", color.to_owned()));
attrs.extend(visual);
attrs.extend(data.iter().cloned());
titled(tag, attrs, label)
}
fn titled(tag: &str, attrs: Attrs, label: &str) -> Element {
let title = Element::svg("title", Vec::new(), vec![Node::Text(label.to_owned())]);
Element::svg(tag, attrs, vec![Node::Element(title)])
}
/// `viewBoxOf(view)`: the view box as the four numbers, JavaScript printing.
pub fn view_box_of(view: &SheetView) -> Option<String> {
view.view_box().map(|b| {
format!(
"{} {} {} {}",
js_number(b.min_x),
js_number(b.min_y),
js_number(b.width),
js_number(b.height)
)
})
}
+1
View File
@@ -1,4 +1,5 @@
//! The anatomy core (R3): SVG reading and sanitising, the annotation layer drawn from the
//! sheet document, and the composition of a view (canvas and highlight).
pub mod layer;
pub mod svg;
+89
View File
@@ -0,0 +1,89 @@
//! R3 O2: the Rust annotation layer equals the TypeScript layer tree frozen by
//! `packages/anatomy/tests/r3.layer-oracles.test.ts`, attribute order included (the review
//! drawings are byte goldens of that order until R5).
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::collections::HashSet;
use faunosteo_core::anatomy::layer::render_layer;
use faunosteo_core::anatomy::svg::{Element, Node};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use serde::Deserialize;
use serde_json::{Map, Value, json};
/// `LayerElement` as the TypeScript writes it: tag, ordered attributes, children, text.
fn layer_value(element: &Element) -> Value {
let attrs: Map<String, Value> = element
.attrs
.iter()
.map(|a| (a.qname.clone(), Value::String(a.value.clone())))
.collect();
let mut text = None;
let mut children = Vec::new();
for child in &element.children {
match child {
Node::Element(e) => children.push(layer_value(e)),
Node::Text(t) => text = Some(t.clone()),
}
}
let mut out = json!({ "tag": element.qname, "attrs": attrs, "children": children });
if let Some(t) = text {
out["text"] = Value::String(t);
}
out
}
/// Attribute names in order, at every level: what `==` on maps would not check.
fn orders(value: &Value, out: &mut Vec<Vec<String>>) {
out.push(
value["attrs"]
.as_object()
.unwrap()
.keys()
.cloned()
.collect(),
);
for child in value["children"].as_array().unwrap() {
orders(child, out);
}
}
#[test]
fn every_frozen_layer_is_reproduced_with_its_attribute_order() {
let (_, oracle) = common::oracle_file("r3/layer.json");
let (_, draft) = common::oracle_file("sheet.draft.json");
let draft = AnatomicalSheetDocument::deserialize(&draft["output"]).unwrap();
let edge = AnatomicalSheetDocument::deserialize(&oracle["edge"]).unwrap();
let cases = oracle["cases"].as_array().unwrap();
assert_eq!(cases.len(), 8);
for case in cases {
let document = if case["doc"] == "draft" {
&draft
} else {
&edge
};
let view = case["viewId"].as_str().unwrap();
let states: HashSet<&str> = case["states"]
.as_array()
.unwrap()
.iter()
.map(|s| s.as_str().unwrap())
.collect();
let layer = layer_value(&render_layer(document, view, &states).unwrap());
let label = format!("{} {} {:?}", case["doc"], view, states.len());
assert_eq!(layer, case["layer"], "{label}");
let (mut ours, mut theirs) = (Vec::new(), Vec::new());
orders(&layer, &mut ours);
orders(&case["layer"], &mut theirs);
assert_eq!(ours, theirs, "{label}: attribute order");
}
}
#[test]
fn an_unknown_view_is_refused() {
let (_, oracle) = common::oracle_file("r3/layer.json");
let edge = AnatomicalSheetDocument::deserialize(&oracle["edge"]).unwrap();
assert!(render_layer(&edge, "nope", &HashSet::new()).is_err());
}