Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(svg): compute live geometry bounds with kurbo

ldm0ece25ddf9f09
diff --git a/moli-renderer-v8/src/context_bootstrap/svg_runtime/builders.rs b/moli-renderer-v8/src/context_bootstrap/svg_runtime/builders.rs
index 20158bce5..b8ce2f663 100644
--- a/moli-renderer-v8/src/context_bootstrap/svg_runtime/builders.rs
+++ b/moli-renderer-v8/src/context_bootstrap/svg_runtime/builders.rs
@@ -496,74 +496,90 @@ pub(super) fn svg_geometry_element<'s>(
scope: &mut v8::PinScope<'s, '_>,
element: v8::Local<'s, v8::Object>,
) -> Option<SvgGeometryElement> {
- let local_name = svg_geometry_element_local_name(scope, element)?;
- svg_geometry_element_from_attributes(scope, element, &local_name)
+ let (runtime_ptr, handle) =
+ crate::native_bridge::node_runtime_and_handle_from_object(scope, element).ok()?;
+ svg_geometry_element_for_handle(unsafe { &*runtime_ptr }, handle)
}
-pub(super) fn svg_geometry_element_from_attributes<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- element: v8::Local<'s, v8::Object>,
- local_name: &str,
+pub(super) fn svg_geometry_element_for_handle(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
) -> Option<SvgGeometryElement> {
- match local_name {
+ let local_name = runtime
+ .dom_host()
+ .node(handle)?
+ .local_name()?
+ .to_ascii_lowercase();
+ match local_name.as_str() {
"circle" => Some(SvgGeometryElement::Circle {
- cx: svg_geometry_length_attribute(scope, element, "cx"),
- cy: svg_geometry_length_attribute(scope, element, "cy"),
- r: svg_geometry_length_attribute(scope, element, "r"),
+ cx: svg_geometry_length_attribute_for_handle(runtime, handle, "cx"),
+ cy: svg_geometry_length_attribute_for_handle(runtime, handle, "cy"),
+ r: svg_geometry_length_attribute_for_handle(runtime, handle, "r"),
}),
"ellipse" => Some(SvgGeometryElement::Ellipse {
- cx: svg_geometry_length_attribute(scope, element, "cx"),
- cy: svg_geometry_length_attribute(scope, element, "cy"),
- rx: svg_geometry_length_attribute(scope, element, "rx"),
- ry: svg_geometry_length_attribute(scope, element, "ry"),
+ cx: svg_geometry_length_attribute_for_handle(runtime, handle, "cx"),
+ cy: svg_geometry_length_attribute_for_handle(runtime, handle, "cy"),
+ rx: svg_geometry_length_attribute_for_handle(runtime, handle, "rx"),
+ ry: svg_geometry_length_attribute_for_handle(runtime, handle, "ry"),
}),
"line" => Some(SvgGeometryElement::Line {
- x1: svg_geometry_length_attribute(scope, element, "x1"),
- y1: svg_geometry_length_attribute(scope, element, "y1"),
- x2: svg_geometry_length_attribute(scope, element, "x2"),
- y2: svg_geometry_length_attribute(scope, element, "y2"),
+ x1: svg_geometry_length_attribute_for_handle(runtime, handle, "x1"),
+ y1: svg_geometry_length_attribute_for_handle(runtime, handle, "y1"),
+ x2: svg_geometry_length_attribute_for_handle(runtime, handle, "x2"),
+ y2: svg_geometry_length_attribute_for_handle(runtime, handle, "y2"),
}),
"path" => Some(SvgGeometryElement::Path {
- d: svg_owner_attribute_value(scope, element, "d").unwrap_or_default(),
+ d: svg_computed_path_data(runtime, handle)
+ .or_else(|| runtime.dom_host().get_attribute(handle, "d"))
+ .unwrap_or_default(),
}),
"polygon" => Some(SvgGeometryElement::Polygon {
- points: svg_owner_attribute_value(scope, element, "points").unwrap_or_default(),
+ points: runtime
+ .dom_host()
+ .get_attribute(handle, "points")
+ .unwrap_or_default(),
}),
"polyline" => Some(SvgGeometryElement::Polyline {
- points: svg_owner_attribute_value(scope, element, "points").unwrap_or_default(),
+ points: runtime
+ .dom_host()
+ .get_attribute(handle, "points")
+ .unwrap_or_default(),
}),
"rect" => Some(SvgGeometryElement::Rect {
- x: svg_geometry_length_attribute(scope, element, "x"),
- y: svg_geometry_length_attribute(scope, element, "y"),
- width: svg_geometry_length_attribute(scope, element, "width"),
- height: svg_geometry_length_attribute(scope, element, "height"),
- rx: svg_geometry_rect_radius_attribute(scope, element, "rx", "ry"),
- ry: svg_geometry_rect_radius_attribute(scope, element, "ry", "rx"),
+ x: svg_geometry_length_attribute_for_handle(runtime, handle, "x"),
+ y: svg_geometry_length_attribute_for_handle(runtime, handle, "y"),
+ width: svg_geometry_length_attribute_for_handle(runtime, handle, "width"),
+ height: svg_geometry_length_attribute_for_handle(runtime, handle, "height"),
+ rx: svg_geometry_rect_radius_attribute_for_handle(runtime, handle, "rx", "ry"),
+ ry: svg_geometry_rect_radius_attribute_for_handle(runtime, handle, "ry", "rx"),
}),
_ => None,
}
}
-pub(super) fn svg_geometry_element_local_name<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- element: v8::Local<'s, v8::Object>,
+fn svg_computed_path_data(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
) -> Option<String> {
- let (runtime_ptr, handle) =
- crate::native_bridge::node_runtime_and_handle_from_object(scope, element).ok()?;
- let runtime = unsafe { &*runtime_ptr };
- runtime
- .dom_host()
- .node(handle)?
- .local_name()
- .map(|name| name.to_ascii_lowercase())
+ let computed =
+ crate::native_bridge::element::computed_style_property_for_handle(runtime, handle, "d");
+ let value = computed.trim();
+ let inner = value.strip_prefix("path(")?.strip_suffix(')')?.trim();
+ let quote = inner.chars().next()?;
+ if !matches!(quote, '\'' | '"') || !inner.ends_with(quote) {
+ return None;
+ }
+ Some(inner[quote.len_utf8()..inner.len() - quote.len_utf8()].to_owned())
}
-pub(super) fn svg_geometry_length_attribute<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- element: v8::Local<'s, v8::Object>,
+fn svg_geometry_length_attribute_for_handle(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
attribute: &str,
) -> f64 {
- svg_owner_attribute_value(scope, element, attribute)
+ runtime
+ .dom_host()
+ .get_attribute(handle, attribute)
.as_deref()
.and_then(parse_svg_length_value)
.filter(|parsed| parsed.value.is_finite())
@@ -571,29 +587,376 @@ pub(super) fn svg_geometry_length_attribute<'s>(
.unwrap_or(0.0)
}
-pub(super) fn svg_geometry_rect_radius_attribute<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- element: v8::Local<'s, v8::Object>,
+fn svg_geometry_rect_radius_attribute_for_handle(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
attribute: &str,
fallback_attribute: &str,
) -> f64 {
- svg_geometry_optional_length_attribute(scope, element, attribute)
- .or_else(|| svg_geometry_optional_length_attribute(scope, element, fallback_attribute))
+ svg_geometry_optional_length_attribute_for_handle(runtime, handle, attribute)
+ .or_else(|| {
+ svg_geometry_optional_length_attribute_for_handle(runtime, handle, fallback_attribute)
+ })
.unwrap_or(0.0)
}
-pub(super) fn svg_geometry_optional_length_attribute<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- element: v8::Local<'s, v8::Object>,
+fn svg_geometry_optional_length_attribute_for_handle(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
attribute: &str,
) -> Option<f64> {
- svg_owner_attribute_value(scope, element, attribute)
+ runtime
+ .dom_host()
+ .get_attribute(handle, attribute)
.as_deref()
.and_then(parse_svg_length_value)
.filter(|parsed| parsed.value.is_finite())
.map(|parsed| parsed.value)
}
+pub(super) fn svg_graphics_bounding_box<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ element: v8::Local<'s, v8::Object>,
+) -> Option<SvgGeometryBox> {
+ let (runtime_ptr, handle) =
+ crate::native_bridge::node_runtime_and_handle_from_object(scope, element).ok()?;
+ let runtime = unsafe { &*runtime_ptr };
+ let node = runtime.dom_host().node(handle)?;
+ if !node.is_connected() || svg_bbox_has_non_rendered_ancestor(runtime, handle) {
+ return None;
+ }
+ svg_bbox_for_handle(
+ runtime,
+ handle,
+ SvgMatrixComponents::identity(),
+ false,
+ &mut Vec::new(),
+ )
+}
+
+fn svg_bbox_for_handle(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+ transform: SvgMatrixComponents,
+ referenced: bool,
+ reference_stack: &mut Vec<crate::document_runtime::DomHandle>,
+) -> Option<SvgGeometryBox> {
+ let local_name = runtime.dom_host().node(handle)?.local_name()?;
+ if svg_element_has_display_none(runtime, handle)
+ || (!referenced && svg_local_name_is_non_rendered_container(local_name))
+ {
+ return None;
+ }
+
+ if let Some(geometry) = svg_geometry_element_for_handle(runtime, handle) {
+ return svg_geometry::bounding_box_for_transformed_element(&geometry, transform);
+ }
+
+ match local_name {
+ "text" => None,
+ "tspan" => svg_text_bounding_box(runtime, handle, transform),
+ "image" => {
+ let (width, height) = svg_image_dimensions(runtime, handle);
+ let geometry = SvgGeometryElement::Rect {
+ x: svg_geometry_length_attribute_for_handle(runtime, handle, "x"),
+ y: svg_geometry_length_attribute_for_handle(runtime, handle, "y"),
+ width,
+ height,
+ rx: 0.0,
+ ry: 0.0,
+ };
+ svg_geometry::bounding_box_for_transformed_element(&geometry, transform)
+ }
+ "foreignObject" => {
+ let geometry = SvgGeometryElement::Rect {
+ x: svg_geometry_length_attribute_for_handle(runtime, handle, "x"),
+ y: svg_geometry_length_attribute_for_handle(runtime, handle, "y"),
+ width: svg_geometry_length_attribute_for_handle(runtime, handle, "width"),
+ height: svg_geometry_length_attribute_for_handle(runtime, handle, "height"),
+ rx: 0.0,
+ ry: 0.0,
+ };
+ svg_geometry::bounding_box_for_transformed_element(&geometry, transform)
+ }
+ "use" => svg_use_bounding_box(runtime, handle, transform, reference_stack),
+ _ => {
+ let mut result: Option<SvgGeometryBox> = None;
+ for child in runtime.dom_host().child_handles(handle) {
+ let Some(child_name) = runtime
+ .dom_host()
+ .node(child)
+ .and_then(|node| node.local_name())
+ else {
+ continue;
+ };
+ let child_transform = transform.multiply(svg_transform_for_handle(runtime, child));
+ let child_transform = if child_name == "svg" {
+ child_transform.multiply(SvgMatrixComponents::translate(
+ svg_geometry_length_attribute_for_handle(runtime, child, "x"),
+ svg_geometry_length_attribute_for_handle(runtime, child, "y"),
+ ))
+ } else {
+ child_transform
+ };
+ if let Some(child_box) = svg_bbox_for_handle(
+ runtime,
+ child,
+ child_transform,
+ referenced,
+ reference_stack,
+ ) {
+ result = Some(result.map_or(child_box, |current| current.union(child_box)));
+ }
+ }
+ result
+ }
+ }
+}
+
+fn svg_image_dimensions(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+) -> (f64, f64) {
+ let width =
+ svg_geometry_optional_length_attribute_for_handle(runtime, handle, "width").unwrap_or(0.0);
+ let height =
+ svg_geometry_optional_length_attribute_for_handle(runtime, handle, "height").unwrap_or(0.0);
+ let Some((intrinsic_width, intrinsic_height)) = runtime.image_resource_intrinsic_size(handle)
+ else {
+ return (width, height);
+ };
+ let intrinsic_width = intrinsic_width as f64;
+ let intrinsic_height = intrinsic_height as f64;
+ if intrinsic_width <= 0.0 || intrinsic_height <= 0.0 {
+ return (width, height);
+ }
+ match (width.is_sign_negative(), height.is_sign_negative()) {
+ (true, false) if height > 0.0 => (height * intrinsic_width / intrinsic_height, height),
+ (false, true) if width > 0.0 => (width, width * intrinsic_height / intrinsic_width),
+ _ => (width, height),
+ }
+}
+
+fn svg_text_bounding_box(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+ transform: SvgMatrixComponents,
+) -> Option<SvgGeometryBox> {
+ let text_root = svg_text_root(runtime, handle)?;
+ let text = runtime.dom_host().text_content(handle)?;
+ let character_count = svg_rendered_text_character_count(&text);
+ if character_count == 0 {
+ return None;
+ }
+
+ let font_size = crate::native_bridge::element::computed_style_property_for_handle(
+ runtime,
+ handle,
+ "font-size",
+ );
+ let font_size = parse_svg_length_value(font_size.trim())
+ .map(|length| length.value)
+ .filter(|value| value.is_finite() && *value > 0.0)
+ .unwrap_or(16.0);
+ let font_family = crate::native_bridge::element::computed_style_property_for_handle(
+ runtime,
+ handle,
+ "font-family",
+ );
+ let is_ahem = font_family.split(',').any(|family| {
+ family
+ .trim_matches([' ', '\'', '"'])
+ .eq_ignore_ascii_case("Ahem")
+ });
+ let glyph_advance = if is_ahem { font_size } else { font_size * 0.6 };
+
+ let explicit_x = svg_geometry_optional_length_attribute_for_handle(runtime, handle, "x");
+ let preceding_characters = if handle == text_root || explicit_x.is_some() {
+ 0
+ } else {
+ svg_text_characters_before(runtime, text_root, handle).unwrap_or(0)
+ };
+ let x = explicit_x
+ .or_else(|| svg_inherited_text_position(runtime, handle, text_root, "x"))
+ .unwrap_or(0.0)
+ + svg_geometry_optional_length_attribute_for_handle(runtime, handle, "dx")
+ .or_else(|| svg_inherited_text_position(runtime, handle, text_root, "dx"))
+ .unwrap_or(0.0)
+ + preceding_characters as f64 * glyph_advance;
+ let baseline = svg_geometry_optional_length_attribute_for_handle(runtime, handle, "y")
+ .or_else(|| svg_inherited_text_position(runtime, handle, text_root, "y"))
+ .unwrap_or(0.0)
+ + svg_geometry_optional_length_attribute_for_handle(runtime, handle, "dy")
+ .or_else(|| svg_inherited_text_position(runtime, handle, text_root, "dy"))
+ .unwrap_or(0.0);
+
+ let geometry = SvgGeometryElement::Rect {
+ x,
+ y: baseline - font_size * 0.8,
+ width: character_count as f64 * glyph_advance,
+ height: font_size,
+ rx: 0.0,
+ ry: 0.0,
+ };
+ svg_geometry::bounding_box_for_transformed_element(&geometry, transform)
+}
+
+fn svg_text_root(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+) -> Option<crate::document_runtime::DomHandle> {
+ let mut current = Some(handle);
+ while let Some(candidate) = current {
+ let node = runtime.dom_host().node(candidate)?;
+ if node.local_name() == Some("text") {
+ return Some(candidate);
+ }
+ current = node.parent_node_id();
+ }
+ None
+}
+
+fn svg_inherited_text_position(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+ text_root: crate::document_runtime::DomHandle,
+ attribute: &str,
+) -> Option<f64> {
+ let mut current = runtime.dom_host().node(handle)?.parent_node_id();
+ while let Some(candidate) = current {
+ if let Some(value) =
+ svg_geometry_optional_length_attribute_for_handle(runtime, candidate, attribute)
+ {
+ return Some(value);
+ }
+ if candidate == text_root {
+ break;
+ }
+ current = runtime.dom_host().node(candidate)?.parent_node_id();
+ }
+ None
+}
+
+fn svg_text_characters_before(
+ runtime: &crate::native_bridge::JsContextHost,
+ root: crate::document_runtime::DomHandle,
+ target: crate::document_runtime::DomHandle,
+) -> Option<usize> {
+ fn visit(
+ runtime: &crate::native_bridge::JsContextHost,
+ current: crate::document_runtime::DomHandle,
+ target: crate::document_runtime::DomHandle,
+ count: &mut usize,
+ ) -> bool {
+ for child in runtime.dom_host().child_handles(current) {
+ if child == target {
+ return true;
+ }
+ let Some(node) = runtime.dom_host().node(child) else {
+ continue;
+ };
+ if let Some(value) = node.data_value()
+ && node.is_text()
+ {
+ *count += svg_rendered_text_character_count(value);
+ continue;
+ }
+ if visit(runtime, child, target, count) {
+ return true;
+ }
+ }
+ false
+ }
+
+ let mut count = 0;
+ visit(runtime, root, target, &mut count).then_some(count)
+}
+
+fn svg_rendered_text_character_count(text: &str) -> usize {
+ text.split_whitespace()
+ .map(|chunk| chunk.chars().count())
+ .sum()
+}
+
+fn svg_use_bounding_box(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+ transform: SvgMatrixComponents,
+ reference_stack: &mut Vec<crate::document_runtime::DomHandle>,
+) -> Option<SvgGeometryBox> {
+ if reference_stack.contains(&handle) {
+ return None;
+ }
+ let href = runtime
+ .dom_host()
+ .get_attribute(handle, "href")
+ .or_else(|| runtime.dom_host().get_attribute(handle, "xlink:href"))?;
+ let target = runtime.get_element_by_id(href.trim().strip_prefix('#')?)?;
+ reference_stack.push(handle);
+ let translated = transform.multiply(SvgMatrixComponents::translate(
+ svg_geometry_length_attribute_for_handle(runtime, handle, "x"),
+ svg_geometry_length_attribute_for_handle(runtime, handle, "y"),
+ ));
+ let target_transform = translated.multiply(svg_transform_for_handle(runtime, target));
+ let result = svg_bbox_for_handle(runtime, target, target_transform, true, reference_stack);
+ reference_stack.pop();
+ result
+}
+
+fn svg_transform_for_handle(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+) -> SvgMatrixComponents {
+ runtime
+ .dom_host()
+ .get_attribute(handle, "transform")
+ .as_deref()
+ .and_then(svg_geometry::parse_transform_attribute)
+ .and_then(|transforms| {
+ svg_geometry::consolidate_transform_matrices(
+ transforms.into_iter().map(|transform| transform.matrix),
+ )
+ })
+ .unwrap_or_else(SvgMatrixComponents::identity)
+}
+
+fn svg_bbox_has_non_rendered_ancestor(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+) -> bool {
+ let mut current = Some(handle);
+ while let Some(candidate) = current {
+ let Some(node) = runtime.dom_host().node(candidate) else {
+ return true;
+ };
+ if node
+ .local_name()
+ .is_some_and(svg_local_name_is_non_rendered_container)
+ || svg_element_has_display_none(runtime, candidate)
+ {
+ return true;
+ }
+ current = node.parent_node_id();
+ }
+ false
+}
+
+fn svg_local_name_is_non_rendered_container(local_name: &str) -> bool {
+ matches!(
+ local_name,
+ "clipPath" | "defs" | "marker" | "mask" | "pattern" | "symbol"
+ )
+}
+
+fn svg_element_has_display_none(
+ runtime: &crate::native_bridge::JsContextHost,
+ handle: crate::document_runtime::DomHandle,
+) -> bool {
+ crate::native_bridge::element::computed_style_property_for_handle(runtime, handle, "display")
+ .trim()
+ .eq_ignore_ascii_case("none")
+}
+
pub(super) fn svg_fill_allows_paint<'s>(
scope: &mut v8::PinScope<'s, '_>,
element: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/svg_runtime/callbacks.rs b/moli-renderer-v8/src/context_bootstrap/svg_runtime/callbacks.rs
index 433ccfce1..cf5eeab47 100644
--- a/moli-renderer-v8/src/context_bootstrap/svg_runtime/callbacks.rs
+++ b/moli-renderer-v8/src/context_bootstrap/svg_runtime/callbacks.rs
@@ -1698,13 +1698,12 @@ pub(super) fn svg_graphics_get_bbox_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
- let bbox = svg_geometry::bounding_box_for_segments(&svg_geometry_segments(scope, args.this()))
- .unwrap_or(SvgGeometryBox {
- x: 0.0,
- y: 0.0,
- width: 0.0,
- height: 0.0,
- });
+ let bbox = svg_graphics_bounding_box(scope, args.this()).unwrap_or(SvgGeometryBox {
+ x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0,
+ });
rv.set(build_dom_rect_like(scope, bbox.x, bbox.y, bbox.width, bbox.height).into());
}
diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs
index e58eeee38..d47c8fd17 100644
--- a/moli-renderer-v8/src/native_bridge/element.rs
+++ b/moli-renderer-v8/src/native_bridge/element.rs
@@ -624,6 +624,14 @@ pub(crate) use stylesheets::{
detach_cached_style_sheet_for_element, detach_cached_style_sheet_if_live_stylesheet_changed,
style_sheet_for_element, style_sheet_getter_function, sync_cached_style_sheet_media_from_owner,
};
+
+pub(crate) fn computed_style_property_for_handle(
+ runtime: &JsContextHost,
+ handle: DomHandle,
+ property: &str,
+) -> String {
+ styles::ComputedStyleRead::new(runtime, handle).property(property)
+}
use stylesheets::{
link_disabled_getter_function, link_disabled_setter_function, style_blocking_getter_function,
style_blocking_setter_function, style_disabled_getter_function, style_disabled_setter_function,
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document.rs
index e4049ff65..a64358911 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/live_document.rs
@@ -1065,6 +1065,84 @@ fn svg_specialized_accessors_live_on_owner_prototypes() {
assert_eq!(result, "ok");
}
+#[test]
+fn svg_geometry_queries_use_computed_paths_live_tree_and_kurbo_bounds() {
+ let mut vm = new_parsed_test_vm(
+ "https://svg-geometry-wiring.test/",
+ r##"<!doctype html>
+ <style>#css_path { d: path("M 0 0 t 0 100"); }</style>
+ <svg xmlns="http://www.w3.org/2000/svg">
+ <defs><rect id="definition" x="10" y="20" width="30" height="40"/></defs>
+ <path id="css_path"/>
+ <circle id="circle" cx="50" cy="50" r="5"/>
+ <ellipse id="ellipse_rx_invalid" cx="1" cy="12" rx="-5" ry="10"/>
+ <ellipse id="ellipse_ry_invalid" cx="6" cy="2" rx="5" ry="-10"/>
+ <g id="aggregate">
+ <path id="move" d="M 40 20 h0"/>
+ <rect id="aggregate_rect" x="50" y="50" width="50" height="50"/>
+ </g>
+ <g id="child_transform"><rect x="1" y="2" width="3" height="4" transform="translate(10 20)"/></g>
+ <g id="own_transform" transform="translate(100 200)"><rect x="1" y="2" width="3" height="4"/></g>
+ <g style="display:none"><rect id="hidden_child" x="10" y="20" width="30" height="40"/></g>
+ <rect id="hidden" x="10" y="20" width="30" height="40" display="none"/>
+ <image id="image_box" x="2" y="3" width="4" height="5"/>
+ <foreignObject id="foreign_box" x="6" y="7" width="8" height="9"/>
+ <use id="use_box" href="#definition" x="5" y="7"/>
+ <text y="180" font-size="100" font-family="Ahem" transform="translate(0 -100)">X<tspan id="span">X</tspan></text>
+ </svg>"##,
+ );
+
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const byId = id => document.getElementById(id);
+ const clean = value => Math.abs(value - Math.round(value)) < 1e-12
+ ? Math.round(value)
+ : value;
+ const box = id => {
+ const value = byId(id).getBBox();
+ return [value.x, value.y, value.width, value.height].map(clean);
+ };
+ const before = box("aggregate");
+ const rect = byId("aggregate_rect");
+ rect.remove();
+ const afterRemove = box("aggregate");
+ byId("aggregate").appendChild(rect);
+ return JSON.stringify({
+ cssLength: byId("css_path").getTotalLength(),
+ circleRadius: byId("circle").r.baseVal.value,
+ circleLength: Math.round(byId("circle").getTotalLength()),
+ move: box("move"),
+ aggregate: before,
+ afterRemove,
+ afterAppend: box("aggregate"),
+ childTransform: box("child_transform"),
+ ownTransform: box("own_transform"),
+ hidden: box("hidden"),
+ hiddenChild: box("hidden_child"),
+ definition: box("definition"),
+ image: box("image_box"),
+ foreign: box("foreign_box"),
+ use: box("use_box"),
+ ellipseRxInvalid: box("ellipse_rx_invalid"),
+ ellipseRyInvalid: box("ellipse_ry_invalid"),
+ tspan: box("span"),
+ foreignInterface: byId("foreign_box") instanceof SVGForeignObjectElement,
+ tspanInterface: byId("span") instanceof SVGTSpanElement,
+ tspanHasBBox: typeof byId("span").getBBox === "function"
+ });
+ })()
+ "#,
+ )
+ .expect("SVG geometry wiring probe should evaluate");
+
+ assert_eq!(
+ result,
+ r#"{"cssLength":100,"circleRadius":5,"circleLength":31,"move":[40,20,0,0],"aggregate":[40,20,60,80],"afterRemove":[40,20,0,0],"afterAppend":[40,20,60,80],"childTransform":[11,22,3,4],"ownTransform":[1,2,3,4],"hidden":[0,0,0,0],"hiddenChild":[0,0,0,0],"definition":[0,0,0,0],"image":[2,3,4,5],"foreign":[6,7,8,9],"use":[15,27,30,40],"ellipseRxInvalid":[-9,2,20,20],"ellipseRyInvalid":[1,-3,10,10],"tspan":[100,100,100,100],"foreignInterface":true,"tspanInterface":true,"tspanHasBBox":true}"#,
+ );
+}
+
#[test]
fn element_methods_and_dataset_live_on_owner_prototypes() {
let mut vm = new_storage_test_vm("https://example.com/");
diff --git a/moli-svg/src/geometry.rs b/moli-svg/src/geometry.rs
index 449d6959d..9ee8df8a9 100644
--- a/moli-svg/src/geometry.rs
+++ b/moli-svg/src/geometry.rs
@@ -1,4 +1,5 @@
use crate::helpers::svg_number_list;
+use crate::matrix::SvgMatrixComponents;
use crate::path::path_geometry;
use kurbo::{
Arc, BezPath, Circle, Ellipse, ParamCurve, ParamCurveArclen, ParamCurveExtrema,
@@ -44,6 +45,21 @@ pub struct SvgGeometryBox {
pub height: f64,
}
+impl SvgGeometryBox {
+ pub fn union(self, other: Self) -> Self {
+ let x0 = self.x.min(other.x);
+ let y0 = self.y.min(other.y);
+ let x1 = (self.x + self.width).max(other.x + other.width);
+ let y1 = (self.y + self.height).max(other.y + other.height);
+ Self {
+ x: x0,
+ y: y0,
+ width: x1 - x0,
+ height: y1 - y0,
+ }
+ }
+}
+
pub enum SvgGeometryElement {
Circle {
cx: f64,
@@ -104,6 +120,63 @@ pub fn bounding_box_for_segments(segments: &[SvgGeometrySegment]) -> Option<SvgG
})
}
+pub fn bounding_box_for_element(element: &SvgGeometryElement) -> Option<SvgGeometryBox> {
+ bounding_box_for_transformed_element(element, SvgMatrixComponents::identity())
+}
+
+pub fn bounding_box_for_transformed_element(
+ element: &SvgGeometryElement,
+ transform: SvgMatrixComponents,
+) -> Option<SvgGeometryBox> {
+ let affine = transform.to_affine();
+ let analytic_bounds = match element {
+ SvgGeometryElement::Circle { cx, cy, r } if *r > 0.0 => {
+ Some((affine * Circle::new(Point::new(*cx, *cy), *r)).bounding_box())
+ }
+ SvgGeometryElement::Ellipse { cx, cy, rx, ry } => {
+ let (rx, ry) = normalized_ellipse_radii(*rx, *ry);
+ (rx > 0.0 && ry > 0.0).then(|| {
+ (affine * Ellipse::new(Point::new(*cx, *cy), (rx, ry), 0.0)).bounding_box()
+ })
+ }
+ _ => None,
+ };
+ if let Some(bounds) = analytic_bounds {
+ return Some(svg_box(bounds));
+ }
+ let path = geometry_path(element)?;
+ if path.elements().is_empty() {
+ return None;
+ }
+ if path.segments().next().is_none() {
+ let point = path
+ .elements()
+ .iter()
+ .rev()
+ .find_map(|element| match element {
+ PathEl::MoveTo(point) => Some(affine * *point),
+ _ => None,
+ })?;
+ return Some(SvgGeometryBox {
+ x: point.x,
+ y: point.y,
+ width: 0.0,
+ height: 0.0,
+ });
+ }
+ let bounds = (affine * path).bounding_box();
+ Some(svg_box(bounds))
+}
+
+fn svg_box(bounds: Rect) -> SvgGeometryBox {
+ SvgGeometryBox {
+ x: bounds.x0,
+ y: bounds.y0,
+ width: bounds.width(),
+ height: bounds.height(),
+ }
+}
+
pub fn is_point_in_fill(element: &SvgGeometryElement, point: SvgGeometryPoint) -> bool {
if matches!(element, SvgGeometryElement::Line { .. }) {
return false;
@@ -151,11 +224,14 @@ fn geometry_path(element: &SvgGeometryElement) -> Option<BezPath> {
} else {
BezPath::new()
}),
- SvgGeometryElement::Ellipse { cx, cy, rx, ry } => Some(if *rx > 0.0 && *ry > 0.0 {
- Ellipse::new(Point::new(*cx, *cy), (*rx, *ry), 0.0).to_path(SHAPE_PATH_TOLERANCE)
- } else {
- BezPath::new()
- }),
+ SvgGeometryElement::Ellipse { cx, cy, rx, ry } => {
+ let (rx, ry) = normalized_ellipse_radii(*rx, *ry);
+ Some(if rx > 0.0 && ry > 0.0 {
+ Ellipse::new(Point::new(*cx, *cy), (rx, ry), 0.0).to_path(SHAPE_PATH_TOLERANCE)
+ } else {
+ BezPath::new()
+ })
+ }
SvgGeometryElement::Line { x1, y1, x2, y2 } => {
let mut path = BezPath::new();
path.move_to((*x1, *y1));
@@ -187,6 +263,14 @@ fn rect_path(x: f64, y: f64, width: f64, height: f64, rx: f64, ry: f64) -> BezPa
Rect::new(x, y, x + width, y + height).to_path(SHAPE_PATH_TOLERANCE)
}
+fn normalized_ellipse_radii(rx: f64, ry: f64) -> (f64, f64) {
+ match (rx.is_sign_negative(), ry.is_sign_negative()) {
+ (true, false) => (ry, ry),
+ (false, true) => (rx, rx),
+ _ => (rx, ry),
+ }
+}
+
fn normalized_rect_radii(width: f64, height: f64, rx: f64, ry: f64) -> (f64, f64) {
if rx <= 0.0 || ry <= 0.0 {
return (0.0, 0.0);
@@ -231,7 +315,7 @@ fn append_quarter_ellipse(
fn poly_points_geometry_path(raw: &str, close: bool) -> Option<BezPath> {
let coordinates = svg_number_list(raw)?;
- if coordinates.len() < 4 || !coordinates.len().is_multiple_of(2) {
+ if coordinates.len() < 2 || !coordinates.len().is_multiple_of(2) {
return None;
}
let mut coordinates = coordinates.chunks_exact(2);
diff --git a/moli-svg/src/lib.rs b/moli-svg/src/lib.rs
index aa235e4e7..79c2f8dfe 100644
--- a/moli-svg/src/lib.rs
+++ b/moli-svg/src/lib.rs
@@ -7,7 +7,8 @@ mod transform;
pub use geometry::{
SvgGeometryBox, SvgGeometryElement, SvgGeometryPoint, SvgGeometrySegment,
- bounding_box_for_segments, is_point_in_fill, point_at_length, segments_for_element,
+ bounding_box_for_element, bounding_box_for_segments, bounding_box_for_transformed_element,
+ is_point_in_fill, point_at_length, segments_for_element,
};
pub use length::{
SvgLength, SvgLengthUnit, parse_length, parse_length_list, parse_number, parse_number_list,
@@ -22,7 +23,8 @@ pub use transform::{
mod tests {
use crate::{
SvgGeometryElement, SvgGeometryPoint, SvgGeometrySegment, SvgLengthUnit,
- SvgMatrixComponents, SvgTransform, SvgTransformKind, bounding_box_for_segments,
+ SvgMatrixComponents, SvgTransform, SvgTransformKind, bounding_box_for_element,
+ bounding_box_for_segments, bounding_box_for_transformed_element,
consolidate_transform_matrices, is_point_in_fill, parse_length, parse_length_list,
parse_number, parse_number_list, parse_transform_attribute, point_at_length,
segments_for_element, serialize_number, serialize_transform_list,
@@ -139,6 +141,68 @@ mod tests {
assert_close(path_box.height, 4.0);
}
+ #[test]
+ fn element_bounding_box_preserves_move_to_only_geometry() {
+ let path = SvgGeometryElement::Path {
+ d: "M 40 20".to_owned(),
+ };
+ let bbox = bounding_box_for_element(&path).unwrap();
+ assert_close(bbox.x, 40.0);
+ assert_close(bbox.y, 20.0);
+ assert_close(bbox.width, 0.0);
+ assert_close(bbox.height, 0.0);
+
+ let polyline = SvgGeometryElement::Polyline {
+ points: "10,20".to_owned(),
+ };
+ let bbox = bounding_box_for_element(&polyline).unwrap();
+ assert_close(bbox.x, 10.0);
+ assert_close(bbox.y, 20.0);
+ assert_close(bbox.width, 0.0);
+ assert_close(bbox.height, 0.0);
+ }
+
+ #[test]
+ fn transformed_element_bounding_box_uses_kurbo_path_geometry() {
+ let path = SvgGeometryElement::Path {
+ d: "M 0 0 L 10 20".to_owned(),
+ };
+ let bbox =
+ bounding_box_for_transformed_element(&path, SvgMatrixComponents::translate(30.0, 40.0))
+ .unwrap();
+ assert_close(bbox.x, 30.0);
+ assert_close(bbox.y, 40.0);
+ assert_close(bbox.width, 10.0);
+ assert_close(bbox.height, 20.0);
+ }
+
+ #[test]
+ fn negative_ellipse_radius_falls_back_to_the_valid_radius() {
+ let rx_invalid = bounding_box_for_element(&SvgGeometryElement::Ellipse {
+ cx: 1.0,
+ cy: 12.0,
+ rx: -5.0,
+ ry: 10.0,
+ })
+ .unwrap();
+ assert_close(rx_invalid.x, -9.0);
+ assert_close(rx_invalid.y, 2.0);
+ assert_close(rx_invalid.width, 20.0);
+ assert_close(rx_invalid.height, 20.0);
+
+ let ry_invalid = bounding_box_for_element(&SvgGeometryElement::Ellipse {
+ cx: 6.0,
+ cy: 2.0,
+ rx: 5.0,
+ ry: -10.0,
+ })
+ .unwrap();
+ assert_close(ry_invalid.x, 1.0);
+ assert_close(ry_invalid.y, -3.0);
+ assert_close(ry_invalid.width, 10.0);
+ assert_close(ry_invalid.height, 10.0);
+ }
+
#[test]
fn rounded_rect_geometry_uses_elliptical_corner_arcs() {
let rect = segments_for_element(SvgGeometryElement::Rect {
diff --git a/moli-svg/src/matrix.rs b/moli-svg/src/matrix.rs
index 3a92492b2..f6c091a6c 100644
--- a/moli-svg/src/matrix.rs
+++ b/moli-svg/src/matrix.rs
@@ -114,7 +114,7 @@ impl SvgMatrixComponents {
)
}
- fn to_affine(self) -> Affine {
+ pub(crate) fn to_affine(self) -> Affine {
Affine::new([self.a, self.b, self.c, self.d, self.e, self.f])
}