feat(anatomy): canvas and highlight composition in Rust (O1 + O3 tree-equal)
This commit is contained in:
1 parent
67d9af3f79
commit
1ec9316a73
8 files changed
+882
-33
No files matched your search
@@ -0,0 +1,236 @@
|
||||
//! Composition of one view (`docs/ANNOTATION-RENDERING.md`): the sanitised drawing framed on
|
||||
//! the view, with its annotation layer last. Two forms, as the TypeScript has them: the
|
||||
//! editor canvas (`apps/app/src/anatomy/drawing.ts`: a fresh root, `0 0 100 100` when no box
|
||||
//! is known, the interactive layer) and the PDF highlight (`packages/anatomy/src/render/
|
||||
//! compose.ts`: the asset's root framed in place, the selected markers only, recoloured, the
|
||||
//! halo filter on request). Both take a sanitised tree, never text.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::layer::{LayerError, find_view, render_layer, view_box_of};
|
||||
use super::svg::serialize::is_xml_text;
|
||||
use super::svg::{Element, Node};
|
||||
use crate::domain::sheet::AnatomicalSheetDocument;
|
||||
|
||||
pub const HIGHLIGHT_FILL: &str = "#b85a3f";
|
||||
pub const HIGHLIGHT_FILL_OPACITY: &str = "0.85";
|
||||
pub const HALO_FILTER_ID: &str = "osteo-halo";
|
||||
const CANVAS_FALLBACK_VIEW_BOX: &str = "0 0 100 100";
|
||||
|
||||
/// Why a view cannot be composed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ComposeError {
|
||||
UnknownView,
|
||||
/// A label or a path of the layer holds a code point XML 1.0 cannot carry.
|
||||
InvalidCharacter,
|
||||
}
|
||||
|
||||
impl From<LayerError> for ComposeError {
|
||||
fn from(_: LayerError) -> Self {
|
||||
Self::UnknownView
|
||||
}
|
||||
}
|
||||
|
||||
/// The asset a view draws: its own, else the first up its parent chain (cycle-safe).
|
||||
pub fn asset_id_of_view<'a>(
|
||||
document: &'a AnatomicalSheetDocument,
|
||||
view_id: &str,
|
||||
) -> Option<&'a str> {
|
||||
let mut visited: HashSet<&str> = HashSet::new();
|
||||
let mut current = find_view(document, view_id);
|
||||
while let Some(view) = current {
|
||||
if let Some(asset) = view.svg_asset_id() {
|
||||
return Some(asset);
|
||||
}
|
||||
if !visited.insert(view.id()) {
|
||||
return None;
|
||||
}
|
||||
current = view.parent_view_id().and_then(|p| find_view(document, p));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The editor canvas of `view_id` drawn on `asset` (its sanitised drawing), no state: the
|
||||
/// canvas sets `data-state` in place after every build.
|
||||
pub fn compose_canvas(
|
||||
document: &AnatomicalSheetDocument,
|
||||
view_id: &str,
|
||||
asset: &Element,
|
||||
) -> Result<Element, ComposeError> {
|
||||
let view = find_view(document, view_id).ok_or(ComposeError::UnknownView)?;
|
||||
let mut root = Element {
|
||||
qname: "svg".to_owned(),
|
||||
namespace: asset.namespace.clone(),
|
||||
attrs: asset
|
||||
.attrs
|
||||
.iter()
|
||||
.filter(|a| a.qname != "width" && a.qname != "height")
|
||||
.cloned()
|
||||
.collect(),
|
||||
children: asset.children.clone(),
|
||||
};
|
||||
let view_box = view_box_of(view)
|
||||
.or_else(|| asset.attr("viewBox").map(str::to_owned))
|
||||
.unwrap_or_else(|| CANVAS_FALLBACK_VIEW_BOX.to_owned());
|
||||
root.set_attr("viewBox", view_box);
|
||||
let layer = render_layer(document, view_id, &HashSet::new())?;
|
||||
root.children.push(Node::Element(checked(layer)?));
|
||||
Ok(root)
|
||||
}
|
||||
|
||||
/// The PDF view of `view_id`: `asset` (sanitised, consumed) framed on the view, the markers
|
||||
/// of `annotation_ids` only, recoloured, with the halo filter when `halo`.
|
||||
pub fn compose_highlight(
|
||||
document: &AnatomicalSheetDocument,
|
||||
view_id: &str,
|
||||
mut asset: Element,
|
||||
annotation_ids: &HashSet<&str>,
|
||||
halo: bool,
|
||||
) -> Result<Element, ComposeError> {
|
||||
let view = find_view(document, view_id).ok_or(ComposeError::UnknownView)?;
|
||||
if let Some(view_box) = view_box_of(view) {
|
||||
asset.set_attr("viewBox", view_box);
|
||||
}
|
||||
asset.remove_attr("width");
|
||||
asset.remove_attr("height");
|
||||
if halo {
|
||||
ensure_halo_filter(&mut asset);
|
||||
}
|
||||
let layer = render_layer(document, view_id, &HashSet::new())?;
|
||||
let layer = highlight_layer(layer, annotation_ids, halo);
|
||||
asset.children.push(Node::Element(checked(layer)?));
|
||||
Ok(asset)
|
||||
}
|
||||
|
||||
/// The layer reduced to the selected annotations, recoloured, every `data-*` dropped.
|
||||
fn highlight_layer(mut layer: Element, ids: &HashSet<&str>, halo: bool) -> Element {
|
||||
layer.attrs.retain(|a| !a.qname.starts_with("data-"));
|
||||
let children = std::mem::take(&mut layer.children);
|
||||
layer.children = children
|
||||
.into_iter()
|
||||
.filter_map(|child| match child {
|
||||
Node::Element(e) if e.attr("data-anno-id").is_some_and(|id| ids.contains(id)) => {
|
||||
Some(Node::Element(highlight_element(e, halo)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
layer
|
||||
}
|
||||
|
||||
/// `{ ...withoutData(attrs), fill, 'fill-opacity' }` then `filter`: JavaScript keeps an
|
||||
/// existing key in place and appends a new one.
|
||||
fn highlight_element(mut element: Element, halo: bool) -> Element {
|
||||
element.attrs.retain(|a| !a.qname.starts_with("data-"));
|
||||
element.set_attr("fill", HIGHLIGHT_FILL.to_owned());
|
||||
element.set_attr("fill-opacity", HIGHLIGHT_FILL_OPACITY.to_owned());
|
||||
if halo {
|
||||
element.set_attr("filter", format!("url(#{HALO_FILTER_ID})"));
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// One halo filter per root: in the first `<defs>` of the drawing, else in a new `<defs>`
|
||||
/// placed first; nothing when a `filter#osteo-halo` already exists.
|
||||
fn ensure_halo_filter(root: &mut Element) {
|
||||
if has_halo_filter(root) {
|
||||
return;
|
||||
}
|
||||
if !append_to_first_defs(root) {
|
||||
let defs = Element::svg("defs", Vec::new(), vec![Node::Element(halo_filter())]);
|
||||
root.children.insert(0, Node::Element(defs));
|
||||
}
|
||||
}
|
||||
|
||||
fn has_halo_filter(element: &Element) -> bool {
|
||||
element.element_children().any(|c| {
|
||||
(c.qname == "filter" && c.attr("id") == Some(HALO_FILTER_ID)) || has_halo_filter(c)
|
||||
})
|
||||
}
|
||||
|
||||
/// Appends the halo to the first `<defs>` below `element` (document order).
|
||||
fn append_to_first_defs(element: &mut Element) -> bool {
|
||||
for child in &mut element.children {
|
||||
let Node::Element(child) = child else {
|
||||
continue;
|
||||
};
|
||||
if child.qname == "defs" {
|
||||
child.children.push(Node::Element(halo_filter()));
|
||||
return true;
|
||||
}
|
||||
if append_to_first_defs(child) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn halo_filter() -> Element {
|
||||
let blur = |std: &str, result: &str| {
|
||||
Node::Element(Element::svg(
|
||||
"feGaussianBlur",
|
||||
vec![
|
||||
("in", "SourceGraphic".to_owned()),
|
||||
("stdDeviation", std.to_owned()),
|
||||
("result", result.to_owned()),
|
||||
],
|
||||
Vec::new(),
|
||||
))
|
||||
};
|
||||
let inputs = [
|
||||
"haloWide",
|
||||
"haloWide",
|
||||
"haloWide",
|
||||
"haloTight",
|
||||
"haloTight",
|
||||
"SourceGraphic",
|
||||
];
|
||||
let merge = Element::svg(
|
||||
"feMerge",
|
||||
Vec::new(),
|
||||
inputs
|
||||
.iter()
|
||||
.map(|i| {
|
||||
Node::Element(Element::svg(
|
||||
"feMergeNode",
|
||||
vec![("in", (*i).to_owned())],
|
||||
Vec::new(),
|
||||
))
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let attrs = vec![
|
||||
("id", HALO_FILTER_ID.to_owned()),
|
||||
("x", "-100%".to_owned()),
|
||||
("y", "-100%".to_owned()),
|
||||
("width", "300%".to_owned()),
|
||||
("height", "300%".to_owned()),
|
||||
("filterUnits", "userSpaceOnUse".to_owned()),
|
||||
];
|
||||
Element::svg(
|
||||
"filter",
|
||||
attrs,
|
||||
vec![
|
||||
blur("18", "haloWide"),
|
||||
blur("8", "haloTight"),
|
||||
Node::Element(merge),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// The layer carries document strings: refuse one XML cannot carry (never replace it).
|
||||
fn checked(layer: Element) -> Result<Element, ComposeError> {
|
||||
if xml_safe(&layer) {
|
||||
Ok(layer)
|
||||
} else {
|
||||
Err(ComposeError::InvalidCharacter)
|
||||
}
|
||||
}
|
||||
|
||||
fn xml_safe(element: &Element) -> bool {
|
||||
element.attrs.iter().all(|a| is_xml_text(&a.value))
|
||||
&& element.children.iter().all(|c| match c {
|
||||
Node::Element(e) => xml_safe(e),
|
||||
Node::Text(t) => is_xml_text(t),
|
||||
})
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 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 compose;
|
||||
pub mod layer;
|
||||
pub mod svg;
|
||||
Reference in new issue
Block a user