//! V1-2.2 owner decision 2026-10-29: SVG references and the isolation of views. A local
//! reference to an id the drawing does not define is refused by the reader, the cleaning, the
//! verdict and the preview; the canvas, inlined in the page, scopes every id and reference to
//! its view, so two drawings with the same ids never resolve into each other and a valid
//! reference keeps working; the composition is deterministic.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
use std::collections::{HashMap, HashSet};
use faunosteo_core::anatomy::compose::{ComposeError, compose_canvas, compose_highlight};
use faunosteo_core::anatomy::svg::clean::{CleaningOutcome, clean_svg};
use faunosteo_core::anatomy::svg::sanitize::{local_reference_text, url_targets};
use faunosteo_core::anatomy::svg::tree::parse_svg;
use faunosteo_core::anatomy::svg::{Element, SvgRejection, read_svg};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use faunosteo_core::domain::sheet::preview::{
PreviewDrawing, PreviewDrawingStatus, PreviewInput, PreviewSheet, PreviewStatus,
};
use faunosteo_core::domain::sheet::verdict::{
DrawingResult, VerdictBinding, VerdictDrawing, VerdictInput, codes, compute_verdict, sha256_hex,
};
use faunosteo_core::facade::call_with_preview;
use serde_json::{Value, json};
const MAIN_ASSET: &str = "11111111-2222-4333-8444-555555555555";
const DETAIL_ASSET: &str = "66666666-7777-4888-9999-aaaaaaaaaaaa";
/// The opening of a drawing in its stored form (prolog, then the root as the core writes it).
const OPEN: &str = concat!(
"\n",
r#""#
);
/// Valid references, one id named several times, by `href`, `xlink:href` and `url(…)`.
fn main_drawing() -> String {
format!(
"{OPEN} \
\
"
)
}
/// The same ids as the main drawing, with other content.
fn detail_drawing() -> String {
format!(
"{OPEN}\
"
)
}
/// A detail drawing naming the main drawing's group, which it does not define.
fn cross_view_drawing() -> String {
format!("{OPEN}{}", "".repeat(256))
}
fn name(text: &str) -> Value {
json!({ "fr": text, "en": text })
}
fn document() -> String {
json!({
"schema_version": 2, "species_id": "canine", "name": name("Chien"),
"description": {}, "scope_disclaimer": { "fr": "Outil", "en": "Tool" },
"attribution": { "authors": ["A"], "license": null, "notes": null },
"vertebral_config": { "regions": [] }, "references": [],
"categories": [{ "id": "c", "name": name("C"), "color": null }],
"views": [
{ "id": "main", "kind": "main", "name": name("Vue"), "svg_asset_id": MAIN_ASSET, "view_box": null },
{ "id": "detail", "kind": "detail", "name": name("Tête"), "svg_asset_id": DETAIL_ASSET,
"view_box": null, "parent_view_id": "main" }
],
"annotations": [], "finding_zones": []
})
.to_string()
}
fn drawing(asset_id: &str, text: &str) -> PreviewDrawing {
PreviewDrawing {
asset_id: asset_id.to_owned(),
sha256: sha256_hex(text.as_bytes()),
bytes: text.as_bytes().to_vec(),
}
}
fn preview(detail: &str) -> PreviewSheet {
let input = PreviewInput {
status: PreviewStatus::Draft,
document: document(),
fingerprint: None,
};
let drawings = vec![
drawing(MAIN_ASSET, &main_drawing()),
drawing(DETAIL_ASSET, detail),
];
PreviewSheet::load(input, drawings).unwrap()
}
fn canvas_outcome(preview: &PreviewSheet, view: &str) -> Value {
let input = json!({ "viewId": view }).to_string();
serde_json::from_str(&call_with_preview(preview, "view.canvas", &input)).unwrap()
}
fn canvas(preview: &PreviewSheet, view: &str) -> String {
let outcome = canvas_outcome(preview, view);
assert_eq!(outcome["ok"], json!(true), "{outcome}");
outcome["value"]["svg"].as_str().unwrap().to_owned()
}
/// Ids in document order, and every reference (`href`, `xlink:href`, `url(#…)`).
fn ids_and_references(element: &Element, ids: &mut Vec, refs: &mut Vec) {
for attr in &element.attrs {
match attr.qname.as_str() {
"id" => ids.push(attr.value.clone()),
"href" | "xlink:href" => {
if let Some(id) = local_reference_text(&attr.value).strip_prefix('#') {
refs.push(id.to_owned());
}
}
_ => refs.extend(url_targets(&attr.value)),
}
}
for child in element.element_children() {
ids_and_references(child, ids, refs);
}
}
fn parsed(text: &str) -> (Vec, Vec) {
let (mut ids, mut refs) = (Vec::new(), Vec::new());
ids_and_references(&parse_svg(text).unwrap(), &mut ids, &mut refs);
(ids, refs)
}
#[test]
fn a_valid_local_reference_keeps_working_inside_its_view() {
let preview = preview(&detail_drawing());
let main = canvas(&preview, "main");
let (ids, refs) = parsed(&main);
assert!(ids.iter().all(|id| id.starts_with("fv.main.")), "{ids:?}");
assert!(!refs.is_empty());
for reference in &refs {
assert!(
ids.contains(reference),
"{reference} resolves in its canvas"
);
}
// The canvas reads back through the one reader: no reference dangles, none cycles.
assert!(read_svg(&main).is_ok());
}
#[test]
fn several_references_to_one_id_all_name_its_scoped_id() {
let main = canvas(&preview(&detail_drawing()), "main");
let (_, refs) = parsed(&main);
let count = |id: &str| refs.iter().filter(|r| r.as_str() == id).count();
assert_eq!(count("fv.main.big"), 2);
assert_eq!(count("fv.main.g"), 3);
assert_eq!(refs.len(), 5);
assert!(main.contains("url( '#fv.main.g')") && main.contains("fill:url(#fv.main.g)"));
}
#[test]
fn a_reference_to_an_absent_id_is_refused_everywhere() {
let dangling = format!("{OPEN}");
assert_eq!(
read_svg(&dangling).err(),
Some(SvgRejection::DanglingReference)
);
let cleaning = clean_svg(dangling.as_bytes());
assert_eq!(cleaning.outcome, CleaningOutcome::Rejected);
assert_eq!(cleaning.reason.as_deref(), Some("dangling_reference"));
assert!(cleaning.preview.is_none() && cleaning.sha256.is_none());
// The preview reports the drawing and draws nothing from it; the other view still draws.
let preview = preview(&dangling);
let state = preview.state().unwrap();
let detail = state
.drawings
.iter()
.find(|d| d.asset_id == DETAIL_ASSET)
.unwrap();
assert_eq!(detail.state, PreviewDrawingStatus::Rejected);
assert_eq!(detail.detail.as_deref(), Some("dangling_reference"));
let refused = canvas_outcome(&preview, "detail");
assert_eq!(
(refused["kind"].as_str(), refused["detail"].as_str()),
(Some("svg_rejected"), Some("dangling_reference"))
);
canvas(&preview, "main");
// The verdict refuses the stored drawing.
let main = main_drawing();
let document = document();
let row = |asset_id: &'static str, text: &str| VerdictDrawing {
asset_id,
sha256: Box::leak(sha256_hex(text.as_bytes()).into_boxed_str()),
byte_size: text.len() as u64,
bytes: Some(Box::leak(text.as_bytes().to_vec().into_boxed_slice())),
};
let verdict = compute_verdict(&VerdictInput {
binding: VerdictBinding {
sheet_id: "s".to_owned(),
version_id: "v".to_owned(),
revision: 1,
review_id: "r".to_owned(),
},
document: &document,
base_document: None,
drawings: vec![row(MAIN_ASSET, &main), row(DETAIL_ASSET, &dangling)],
});
assert!(verdict.failures.iter().any(|f| f == codes::SVG_REJECTED));
let checked = verdict
.drawings
.iter()
.find(|d| d.asset_id == DETAIL_ASSET)
.unwrap();
assert_eq!(checked.result, DrawingResult::SvgRejected);
assert_eq!(checked.detail.as_deref(), Some("dangling_reference"));
}
#[test]
fn a_view_cannot_name_an_element_of_another_view() {
let cross = cross_view_drawing();
assert_eq!(
read_svg(&cross).err(),
Some(SvgRejection::DanglingReference)
);
assert_eq!(
clean_svg(cross.as_bytes()).reason.as_deref(),
Some("dangling_reference")
);
let refused = canvas_outcome(&preview(&cross), "detail");
assert_eq!(refused["detail"], json!("dangling_reference"));
}
#[test]
fn identical_ids_in_two_views_resolve_each_in_its_own_view() {
let preview = preview(&detail_drawing());
let canvases = [canvas(&preview, "main"), canvas(&preview, "detail")];
// The page as a browser reads it: both canvases inlined, `#id` naming the first element
// with that id in document order.
let mut first_owner: HashMap = HashMap::new();
let mut references: Vec<(usize, String)> = Vec::new();
for (index, text) in canvases.iter().enumerate() {
let (ids, refs) = parsed(text);
for id in ids {
first_owner.entry(id).or_insert(index);
}
references.extend(refs.into_iter().map(|r| (index, r)));
}
assert!(references.iter().any(|(i, _)| *i == 1));
for (index, reference) in &references {
assert_eq!(first_owner.get(reference), Some(index), "{reference}");
}
let (main_ids, _) = parsed(&canvases[0]);
let (detail_ids, _) = parsed(&canvases[1]);
assert!(main_ids.iter().all(|id| !detail_ids.contains(id)));
assert!(detail_ids.contains(&"fv.detail.g".to_owned()));
}
#[test]
fn composition_is_deterministic_and_repeatable() {
let preview = preview(&detail_drawing());
let first = (canvas(&preview, "main"), canvas(&preview, "detail"));
let again = (canvas(&preview, "detail"), canvas(&preview, "main"));
assert_eq!(first, (again.1, again.0));
let other = self::preview(&detail_drawing());
assert_eq!(canvas(&other, "main"), first.0);
// Scoping is applied once per composition, never compounded.
assert!(!first.0.contains("fv.main.fv.main."));
// The stored bytes are not touched: the drawing still hashes to its row.
let state = preview.state().unwrap();
assert!(
state
.drawings
.iter()
.all(|d| d.state == PreviewDrawingStatus::Ok)
);
assert_eq!(preview.drawing_reads(), 2);
}
/// Every reference of `text` as a browser reads it, written apart from the core's reader:
/// each `href="…"` and each `url(…)` (any case), quotes and CSS whitespace trimmed, tab and
/// newline removed and `%XX` decoded as the URL parser does. Answers the fragment ids.
fn browser_references(text: &str) -> Vec {
let normalise = |raw: &str| {
let trimmed = raw.trim_matches(|c: char| c.is_ascii_whitespace() || c == '\'' || c == '"');
let cleaned: String = trimmed
.chars()
.filter(|c| !matches!(c, '\t' | '\n' | '\r'))
.collect();
let mut bytes = Vec::new();
let raw = cleaned.as_bytes();
let mut i = 0;
while i < raw.len() {
let hex = raw
.get(i + 1..i + 3)
.and_then(|h| std::str::from_utf8(h).ok());
match (raw[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
(b'%', Some(byte)) => {
bytes.push(byte);
i += 3;
}
(byte, _) => {
bytes.push(byte);
i += 1;
}
}
}
String::from_utf8_lossy(&bytes).into_owned()
};
let mut out = Vec::new();
for (index, _) in text.match_indices("href=\"") {
let rest = &text[index + 6..];
out.push(normalise(&rest[..rest.find('"').unwrap()]));
}
let lower = text.to_ascii_lowercase();
for (index, _) in lower.match_indices("url(") {
let rest = &text[index + 4..];
out.push(normalise(&rest[..rest.find(')').unwrap_or(rest.len())]));
}
out.into_iter()
.map(|reference| reference.strip_prefix('#').unwrap_or(&reference).to_owned())
.collect()
}
#[test]
fn every_reference_a_browser_reads_stays_in_its_view() {
let preview = preview(&detail_drawing());
for view in ["main", "detail"] {
let text = canvas(&preview, view);
let references = browser_references(&text);
assert!(references.len() >= 2, "{view}");
for reference in references {
assert!(
reference.starts_with(&format!("fv.{view}.")),
"{view}: {reference}"
);
}
}
// The hostile spellings never reach a canvas: the drawing is refused, nothing composed.
for value in ["url(#%66v.main.g)", "url(\'#\tg\')", "url(#%67)"] {
let hostile =
format!("{OPEN} ");
let refused = canvas_outcome(&self::preview(&hostile), "detail");
assert_eq!(refused["kind"], json!("svg_rejected"), "{value}");
}
}
/// Final review 2026-10-30: a `url(` glued to a longer name (`xurl(#g)`, or after a no-break
/// space) is no reference, and the reader removes it from any attribute, so every drawing the
/// reader keeps composes alike into the canvas, the preview and the PDF view; before, the reader
/// kept it in `class` or `result`, the verdict passed and only the canvas refused.
#[test]
fn the_canvas_the_preview_and_the_pdf_draw_every_drawing_the_reader_keeps() {
let document: AnatomicalSheetDocument = serde_json::from_str(&document()).unwrap();
for (attr, value) in [
("class", "xurl(#g)"),
("class", "-url(#g)"),
("result", "aurl(#g)"),
("values", "_url(#g)"),
("transform", "\u{a0}url(#g)"),
("class", "xurl(#g)"),
] {
let text = format!(
"{OPEN} "
);
let read = read_svg(&text).unwrap();
assert_eq!(read.removed, [format!("g@{attr}")], "{value}");
let cleaning = clean_svg(text.as_bytes());
assert_eq!(cleaning.outcome, CleaningOutcome::Cleanable, "{value}");
compose_canvas(&document, "detail", &read.root).unwrap();
compose_highlight(&document, "detail", read.root, &HashSet::new(), false).unwrap();
canvas(&preview(cleaning.stored.as_deref().unwrap()), "detail");
}
}
/// The composer stays fail-closed on a tree that did not come out of the reader: a glued
/// `url(` or a reference leaving the document is never inlined in the page.
#[test]
fn the_composer_refuses_a_reference_it_does_not_scope() {
let document: AnatomicalSheetDocument = serde_json::from_str(&document()).unwrap();
for (attr, value) in [
("class", "xurl(#g)"),
("fill", "url(#%67)"),
("href", "https://example.org/a.svg#g"),
] {
let mut root = read_svg(&detail_drawing()).unwrap().root;
root.set_attr(attr, value.to_owned());
assert_eq!(
compose_canvas(&document, "detail", &root).unwrap_err(),
ComposeError::UnscopedReference,
"{attr}={value}"
);
}
}