From bfc13d41d3baf9dacb09b650fdef0fa6b981dd7e Mon Sep 17 00:00:00 2001 From: ldm0 Date: Fri, 13 Nov 2026 12:27:05 +0800 Subject: [PATCH] fix(svg): provide graphics client rects for measured charts Resolve SVG object bounds and shaped text through the shared styled SVG scene, then map them through the outer CSS viewport. Project descendant computed styles without mutating the live DOM, preserving use-instance inheritance and outer transform ownership. Cover chart measurement and paint, Chromium-calibrated SVG geometry, referenced shapes, and the formerly empty circle client rectangle. --- .../src/native/html_serialization/engine.rs | 48 ++- moli-dom/src/native/html_serialization/mod.rs | 14 +- .../src/native/html_serialization/tests.rs | 38 +++ .../src/layout_renderer/inline_svg.rs | 278 ++++++++++++------ moli-renderer-v8/src/layout_renderer/mod.rs | 12 +- .../src/layout_renderer/source_view.rs | 25 +- .../src/layout_renderer/style_resolver.rs | 2 +- .../src/layout_renderer/svg_geometry.rs | 158 ++++++++++ .../element/geometry/provider.rs | 17 +- .../runtime/page_vm/tests/inline_svg_paint.rs | 121 ++++++++ .../src/script_vm/tests/dom_xhr/shadow_dom.rs | 5 +- .../fixtures/inline-svg-client-rects.html | 1 + 12 files changed, 607 insertions(+), 112 deletions(-) create mode 100644 moli-renderer-v8/src/layout_renderer/svg_geometry.rs create mode 100644 moli-renderer-v8/tests/fixtures/inline-svg-client-rects.html diff --git a/moli-dom/src/native/html_serialization/engine.rs b/moli-dom/src/native/html_serialization/engine.rs index d4a93d0d878..93dadc7e3bd 100644 --- a/moli-dom/src/native/html_serialization/engine.rs +++ b/moli-dom/src/native/html_serialization/engine.rs @@ -54,6 +54,7 @@ struct HtmlSerializationOptions<'a> { // whose owner Document has different scripting state from the outer tree. scripting_enabled_for_node: &'a dyn Fn(NativeNodeId) -> bool, shadow_root_provider: Option<&'a dyn HtmlShadowRootProvider>, + attribute_overrides: Option<&'a dyn Fn(NativeNodeId) -> Vec<(String, String)>>, } impl<'a> HtmlSerializationOptions<'a> { @@ -65,6 +66,7 @@ impl<'a> HtmlSerializationOptions<'a> { target, scripting_enabled_for_node, shadow_root_provider: None, + attribute_overrides: None, } } @@ -265,6 +267,9 @@ fn serialize_html_node_frame<'a, S>( out.push('>'); } NodeData::Element(element) => { + let overrides = options + .attribute_overrides + .map(|attributes| attributes(node_id)); out.push('<'); out.push_str(element.local_name()); if let Some(is_name) = element.custom_element_is_name() @@ -278,12 +283,31 @@ fn serialize_html_node_frame<'a, S>( if out.limit_exceeded() { return; } + if overrides.as_ref().is_some_and(|attributes| { + attributes + .iter() + .any(|(name, _)| attribute.name_matches(name)) + }) { + continue; + } out.push(' '); attribute.push_html_serialized_name(|part| out.push_str(part)); out.push_str("=\""); escape_html_attribute(attribute.value(), out); out.push('"'); } + if let Some(overrides) = overrides { + for (name, value) in overrides { + if out.limit_exceeded() { + return; + } + out.push(' '); + out.push_str(&name); + out.push_str("=\""); + escape_html_attribute(&value, out); + out.push('"'); + } + } out.push('>'); if !is_void_html_element(element.namespace(), element.local_name()) { @@ -482,18 +506,24 @@ pub(super) fn serialize_html_with_limit( dom: &NativeDom, node_id: NativeNodeId, max_bytes: usize, +) -> Result, HtmlSerializationLimitExceeded> { + serialize_html_with_limit_and_attributes(dom, node_id, max_bytes, None) +} + +pub(super) fn serialize_html_with_limit_and_attributes( + dom: &NativeDom, + node_id: NativeNodeId, + max_bytes: usize, + attributes: Option<&dyn Fn(NativeNodeId) -> Vec<(String, String)>>, ) -> Result, HtmlSerializationLimitExceeded> { let scripting_enabled_for_node = |_: NativeNodeId| true; let mut out = BoundedHtmlSerialization::new(max_bytes); - if !serialize_html_into_sink( - dom, - node_id, - HtmlSerializationOptions::new( - HtmlSerializationTarget::IncludeNode, - &scripting_enabled_for_node, - ), - &mut out, - ) { + let mut options = HtmlSerializationOptions::new( + HtmlSerializationTarget::IncludeNode, + &scripting_enabled_for_node, + ); + options.attribute_overrides = attributes; + if !serialize_html_into_sink(dom, node_id, options, &mut out) { return Ok(None); } out.finish().map(Some) diff --git a/moli-dom/src/native/html_serialization/mod.rs b/moli-dom/src/native/html_serialization/mod.rs index fe7a953a991..331b8c2cd07 100644 --- a/moli-dom/src/native/html_serialization/mod.rs +++ b/moli-dom/src/native/html_serialization/mod.rs @@ -8,7 +8,7 @@ pub(super) use engine::{ HtmlSerializationTarget, HtmlSerializedShadowRoot, escape_html_attribute_into_string, serialize_html_with_shadow_root_provider, }; -use engine::{serialize_html, serialize_html_with_limit}; +use engine::{serialize_html, serialize_html_with_limit, serialize_html_with_limit_and_attributes}; /// A bounded serialization stopped before appending bytes past its limit. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -73,6 +73,18 @@ impl NativeDom { serialize_html_with_limit(self, node_id, max_bytes) } + /// Bounded serialization for derived consumers that need resolved attributes + /// without mutating or cloning the live DOM. Replacement names must be valid + /// qualified attribute names; values are escaped by the serializer. + pub fn outer_html_with_limit_and_attributes( + &self, + node_id: NativeNodeId, + max_bytes: usize, + attributes: &dyn Fn(NativeNodeId) -> Vec<(String, String)>, + ) -> Result, HtmlSerializationLimitExceeded> { + serialize_html_with_limit_and_attributes(self, node_id, max_bytes, Some(attributes)) + } + pub fn inner_html(&self, node_id: NativeNodeId) -> Option { self.inner_html_with_scripting_enabled(node_id, true) } diff --git a/moli-dom/src/native/html_serialization/tests.rs b/moli-dom/src/native/html_serialization/tests.rs index 4bfb450e992..af8b308a6fe 100644 --- a/moli-dom/src/native/html_serialization/tests.rs +++ b/moli-dom/src/native/html_serialization/tests.rs @@ -9,6 +9,44 @@ fn scripting_enabled(_: NativeNodeId) -> bool { true } +#[test] +fn bounded_attribute_projection_preserves_live_dom_and_escapes_values() { + let mut dom = NativeDom::new_html(test_url()); + let root = dom.create_element("div"); + let child = dom.create_element("span"); + dom.set_attribute(root, "style", "color:red"); + dom.append_child(root, child); + let original = dom.outer_html(root).unwrap(); + let attributes = |node| { + if node == root { + vec![("style".into(), "font-family:\"A&B\"".into())] + } else { + vec![("id".into(), "derived".into())] + } + }; + let projected = dom + .outer_html_with_limit_and_attributes(root, 512, &attributes) + .unwrap() + .unwrap(); + assert_eq!( + projected, + "
" + ); + assert_eq!(dom.outer_html(root).unwrap(), original); + assert_eq!( + dom.outer_html_with_limit_and_attributes(root, projected.len(), &attributes) + .unwrap() + .unwrap(), + projected + ); + assert_eq!( + dom.outer_html_with_limit_and_attributes(root, projected.len() - 1, &attributes), + Err(HtmlSerializationLimitExceeded { + max_bytes: projected.len() - 1 + }) + ); +} + #[test] fn template_contents_require_the_exact_html_element_identity() { for (namespace, name, is_template) in [ diff --git a/moli-renderer-v8/src/layout_renderer/inline_svg.rs b/moli-renderer-v8/src/layout_renderer/inline_svg.rs index 86a84b51b6d..9b524ec20c1 100644 --- a/moli-renderer-v8/src/layout_renderer/inline_svg.rs +++ b/moli-renderer-v8/src/layout_renderer/inline_svg.rs @@ -5,13 +5,11 @@ // it into one bounded, immutable `usvg::Tree`. No SVG child layout tree or // cross-pass resource cache is retained here. // -// Because the tree is reparsed in isolation, every inherited input that -// affects paint must be projected onto the serialized root: paint group, -// resolved `currentColor`, root font, and the inherited text longhands. A -// value left behind is not "slightly different styling"; usvg drops nodes it -// cannot resolve, so `` disappears from the output entirely. +// The isolated tree also needs document CSS: sample the computed SVG paint +// and text inputs while serializing, without changing the live DOM. Geometry +// queries use the same decoder and font shaping as paint. -use std::sync::Arc; +use std::{cell::RefCell, collections::HashSet, sync::Arc}; use moli_layout::{LayoutImageResource, PaintColor, ReplacedMetrics, ResolvedLayoutStyle}; use style::color::ColorSpace; @@ -20,7 +18,8 @@ use style_traits::ToCss; use crate::{ document_runtime::DomHandle, - dom::native::{DomHost, Element}, + dom::native::Element, + native_bridge::{PageScriptHost, element::StyleObservation}, }; const SVG_NAMESPACE_ATTRIBUTE: &str = " xmlns=\"http://www.w3.org/2000/svg\""; @@ -42,44 +41,12 @@ pub(super) fn replaced_metrics(element: &Element) -> ReplacedMetrics { } pub(super) fn replaced_resource( - host: &DomHost, + runtime: &PageScriptHost, node: DomHandle, style: &ResolvedLayoutStyle, + reads: &RefCell>, ) -> Option { - let declarations = computed_root_declarations(style); - let source_limit = moli_image::MAX_ENCODED_SVG_BYTES - .saturating_sub(declarations.len()) - .saturating_sub(SERIALIZED_SOURCE_FIXED_INJECTION_RESERVE); - let source = match host.dom().outer_html_with_limit(node, source_limit) { - Ok(Some(source)) => source, - Ok(None) => return None, - Err(error) => { - tracing::debug!( - node = node.index(), - error = ?error, - "fresh inline SVG serialization exceeded its input budget" - ); - return None; - } - }; - let Some(source) = prepare_source(source, &declarations) else { - tracing::debug!( - node = node.index(), - "inline SVG serialization did not produce an SVG root" - ); - return None; - }; - let svg = match moli_image::decode_svg_image(source.as_bytes()) { - Ok(svg) => Arc::new(svg), - Err(error) => { - tracing::debug!( - node = node.index(), - error = ?error, - "fresh inline SVG resource parse failed" - ); - return None; - } - }; + let svg = Arc::new(parse_live_svg(runtime, node, style, reads, None)?); // Inline SVG box sizing comes from Stylo's width/height presentation // hints. The vector object's own dimensions must use the same resolved // root font context, so use the parsed tree size rather than the @@ -93,7 +60,188 @@ pub(super) fn replaced_resource( }) } -fn prepare_source(mut source: String, declarations: &str) -> Option { +pub(super) struct GeometryTarget<'a> { + pub node: DomHandle, + pub id: &'a str, + pub viewport: moli_layout::LayoutSize, +} + +pub(super) fn parse_live_svg( + runtime: &PageScriptHost, + root: DomHandle, + root_style: &ResolvedLayoutStyle, + reads: &RefCell>, + geometry: Option>, +) -> Option { + let host = runtime.dom_host(); + let mut referenced_ids = HashSet::new(); + let mut pending = vec![root]; + while let Some(node) = pending.pop() { + if let Some(element) = host.node(node).and_then(|node| node.as_element()) + && element.is_svg_element("use") + && let Some(id) = element + .attribute("href") + .or_else(|| { + element + .attributes() + .iter() + .find(|attribute| { + attribute.namespace() == "http://www.w3.org/1999/xlink" + && attribute.local_name() == "href" + }) + .map(|attribute| attribute.value()) + }) + .and_then(|href| href.strip_prefix('#')) + { + referenced_ids.insert(id); + } + pending.extend(host.dom().child_ids(node)); + } + let attributes = |node| { + let mut attributes = Vec::new(); + let Some(element) = host.node(node).and_then(|node| node.as_element()) else { + return attributes; + }; + if element.namespace() != "http://www.w3.org/2000/svg" { + return attributes; + } + if let Some(geometry) = geometry.as_ref() + && node == geometry.node + && element.attribute("id").is_none_or(str::is_empty) + { + attributes.push(("id".into(), geometry.id.into())); + } + // A referenced definition inherits at its instance, not at its + // original DOM position. This also applies to references outside + // . Preserve their authored inheritance instead of freezing it. + let mut parent = Some(node); + while let Some(ancestor) = parent { + if host + .node(ancestor) + .and_then(|node| node.as_element()) + .is_some_and(|element| { + element.is_svg_element("defs") + || (ancestor != root + && element + .attribute("id") + .is_some_and(|id| referenced_ids.contains(id))) + }) + { + return attributes; + } + if ancestor == root { + break; + } + parent = host.dom().parent_node(ancestor); + } + let mut declarations = if node == root { + let mut declarations = computed_root_declarations(root_style); + // The CSS replaced-element box applies the outer SVG transform. + // Reapplying it inside the vector resource would transform both + // paint and client geometry twice. Descendant SVG transforms stay. + append_serialized_declaration(&mut declarations, "transform", "none"); + declarations + } else { + let Some(computed) = reads.borrow_mut().read(node).computed_values() else { + return attributes; + }; + let style = ResolvedLayoutStyle::from_stylo(computed); + let mut declarations = computed_root_declarations(&style); + let computed = style.stylo_computed_values().expect("resolved SVG style"); + for (name, value) in [ + ("display", computed.clone_display().to_css_string()), + ("visibility", computed.clone_visibility().to_css_string()), + ("opacity", computed.clone_opacity().to_css_string()), + ("text-anchor", computed.clone_text_anchor().to_css_string()), + ] { + append_serialized_declaration(&mut declarations, name, &value); + } + declarations + }; + if let Some(geometry) = geometry.as_ref() + && node == root + { + for (name, value) in [ + ("width", geometry.viewport.width), + ("height", geometry.viewport.height), + ] { + attributes.push((name.into(), value.to_string())); + append_serialized_declaration(&mut declarations, name, &format!("{value}px")); + } + } + let declarations = merge_computed_declarations( + element.attribute("style").unwrap_or_default(), + &declarations, + ); + attributes.push(("style".into(), declarations)); + attributes + }; + let source_limit = + moli_image::MAX_ENCODED_SVG_BYTES.saturating_sub(SERIALIZED_SOURCE_FIXED_INJECTION_RESERVE); + let source = + match host + .dom() + .outer_html_with_limit_and_attributes(root, source_limit, &attributes) + { + Ok(Some(source)) => source, + Ok(None) => return None, + Err(error) => { + tracing::debug!( + node = root.index(), + error = ?error, + "fresh inline SVG serialization exceeded its input budget" + ); + return None; + } + }; + let Some(source) = prepare_source(source) else { + tracing::debug!( + node = root.index(), + "inline SVG serialization did not produce an SVG root" + ); + return None; + }; + match moli_image::decode_svg_image(source.as_bytes()) { + Ok(svg) => Some(svg), + Err(error) => { + tracing::debug!( + node = root.index(), + error = ?error, + "fresh inline SVG resource parse failed" + ); + None + } + } +} + +fn merge_computed_declarations(authored: &str, computed: &str) -> String { + // usvg's simplecss parser stops at an empty declaration and gives the + // first !important declaration precedence. Normalize authored CSS and + // remove the properties whose final values have already been sampled. + let options = moli_css_parse::DeclarationParseOptions::default(); + let computed = moli_css_parse::parse_declaration_list(computed, options); + let mut declarations = String::new(); + for property in moli_css_parse::parse_declaration_list(authored, options) { + if !computed + .iter() + .any(|projected| projected.name.eq_ignore_ascii_case(&property.name)) + { + declarations.push_str(&property.name); + declarations.push(':'); + declarations.push_str(&property.value); + if property.important { + declarations.push_str(" !important"); + } + declarations.push(';'); + } + } + for property in computed { + append_serialized_declaration(&mut declarations, &property.name, &property.value); + } + declarations +} + +fn prepare_source(mut source: String) -> Option { if !source.starts_with(" Option { source.insert_str(4, SVG_NAMESPACE_ATTRIBUTE); } - // `outerHTML` carries authored SVG presentation attributes and internal - // styles, but external document CSS is not serialized. Project the root's - // already-resolved inherited inputs as final inline declarations so - // descendant `currentColor` paint and relative SVG lengths see the same - // root context as NativeDom/Stylo. - // Appending an important declaration also wins over an earlier authored - // declaration in the same serialized style attribute; the sampled value - // is already the final computed value, so this does not re-run cascade. - let root_end = source.find('>')?; - if let Some(style_start) = source[..root_end].find(" style=\"") { - let value_start = style_start + " style=\"".len(); - let value_end = value_start + source[value_start..root_end].find('"')?; - source.insert_str(value_end, &format!(";{declarations}")); - } else { - source.insert_str(root_end, &format!(" style=\"{declarations}\"")); - } - // HTML serialization uses this named entity while XML has no predefined // `nbsp` entity. Numeric spelling preserves the character for usvg. if source.contains(" ") { @@ -211,10 +342,8 @@ fn computed_root_declarations(style: &ResolvedLayoutStyle) -> String { append_serialized_declaration( &mut declarations, "font-family", - // Stylo quotes a family name with double quotes and these declarations - // land inside a double-quoted `style` attribute of an XML document, so - // the value needs XML escaping; usvg decodes it back to authored text. - &escape_serialized_value(&computed.clone_font_family().to_css_string()), + // Attribute projection escapes quoted family names at serialization. + &computed.clone_font_family().to_css_string(), ); append_serialized_declaration( &mut declarations, @@ -283,27 +412,6 @@ fn append_serialized_declaration(declarations: &mut String, name: &str, value: & declarations.push_str(" !important;"); } -/// Escapes a declaration value for a double-quoted `style` attribute of the -/// serialized XML document. -/// -/// usvg parses the serialized subtree as XML, where an unescaped `"` would end -/// the attribute and a bare `&` would start an entity. Only the characters -/// that can appear in an authored font family (or a quoted CSS value) need -/// this; the other declarations are numeric or identifier-only. -fn escape_serialized_value(value: &str) -> String { - let mut escaped = String::with_capacity(value.len()); - for character in value.chars() { - match character { - '&' => escaped.push_str("&"), - '"' => escaped.push_str("""), - '<' => escaped.push_str("<"), - '>' => escaped.push_str(">"), - other => escaped.push(other), - } - } - escaped -} - fn rgba_css(color: PaintColor) -> String { let channel = |value: f32| { let value = if value.is_finite() { value } else { 0.0 }; diff --git a/moli-renderer-v8/src/layout_renderer/mod.rs b/moli-renderer-v8/src/layout_renderer/mod.rs index 02f8ca81c9f..c7027f42123 100644 --- a/moli-renderer-v8/src/layout_renderer/mod.rs +++ b/moli-renderer-v8/src/layout_renderer/mod.rs @@ -1,6 +1,7 @@ mod inline_svg; mod source_view; mod style_resolver; +mod svg_geometry; use std::collections::HashMap; @@ -11,6 +12,8 @@ use moli_layout::{ use crate::{document_runtime::DomHandle, native_bridge::PageScriptHost}; +pub(crate) use svg_geometry::svg_client_rect; + pub(crate) fn build_native_layout_pass( runtime: &PageScriptHost, root: DomHandle, @@ -52,7 +55,14 @@ fn build_native_layout_pass_recursive( let source = source_view::NativeLayoutSourceView::with_paint_resources( runtime, root, - request.requests_paint(), + request.requests_paint().then(|| { + style_resolver::layout_style_read_scope( + runtime, + document, + request.viewport, + environment_override, + ) + }), ); let source_ready = profile_started.map(|_| std::time::Instant::now()); let mut styles = style_resolver::NativeLayoutStyleResolver::new( diff --git a/moli-renderer-v8/src/layout_renderer/source_view.rs b/moli-renderer-v8/src/layout_renderer/source_view.rs index ef1f45a3fd4..3460f1e7f39 100644 --- a/moli-renderer-v8/src/layout_renderer/source_view.rs +++ b/moli-renderer-v8/src/layout_renderer/source_view.rs @@ -1,4 +1,7 @@ -use std::collections::{HashMap, HashSet}; +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, +}; use moli_layout::{ LayoutElementCategory, LayoutElementMetadata, LayoutElementSemantics, LayoutImageResource, @@ -13,33 +16,33 @@ use crate::{ flat_children, flat_parent, form_control_data, layout_element_classification, list_data, optional_positive_u16_attribute, select_control_data, }, - native_bridge::PageScriptHost, + native_bridge::{PageScriptHost, element::StyleObservation}, }; pub(super) struct NativeLayoutSourceView<'a> { runtime: &'a PageScriptHost, root: DomHandle, document: Option, - include_paint_resources: bool, + paint_styles: Option>>, text_selections: HashMap, } impl<'a> NativeLayoutSourceView<'a> { #[cfg(test)] pub(super) fn new(runtime: &'a PageScriptHost, root: DomHandle) -> Self { - Self::with_paint_resources(runtime, root, false) + Self::with_paint_resources(runtime, root, None) } pub(super) fn with_paint_resources( runtime: &'a PageScriptHost, root: DomHandle, - include_paint_resources: bool, + paint_styles: Option>, ) -> Self { Self { runtime, root, document: runtime.dom_host().owner_document_handle(root), - include_paint_resources, + paint_styles: paint_styles.map(RefCell::new), text_selections: document_text_selections(runtime, root), } } @@ -238,9 +241,7 @@ impl LayoutSource for NativeLayoutSourceView<'_> { node: Self::NodeId, style: &moli_layout::ResolvedLayoutStyle, ) -> Option { - if !self.include_paint_resources { - return None; - } + let paint_styles = self.paint_styles.as_ref()?; let semantics = self .host() .node(node) @@ -257,7 +258,7 @@ impl LayoutSource for NativeLayoutSourceView<'_> { }) } Some(LayoutReplacedKind::Svg) => { - super::inline_svg::replaced_resource(self.host(), node, style) + super::inline_svg::replaced_resource(self.runtime, node, style, paint_styles) } Some(LayoutReplacedKind::Canvas) => { let pixels = self.runtime.canvas_pixels_for_layout(node)?; @@ -273,9 +274,7 @@ impl LayoutSource for NativeLayoutSourceView<'_> { } fn css_image_resource(&self, resolved_url: &str) -> Option { - if !self.include_paint_resources { - return None; - } + self.paint_styles.as_ref()?; let parsed = url::Url::parse(resolved_url).ok()?; // Blink shares the fetched bytes using a fragment-free cache key, but // then applies SVG view/element-fragment semantics separately. Until diff --git a/moli-renderer-v8/src/layout_renderer/style_resolver.rs b/moli-renderer-v8/src/layout_renderer/style_resolver.rs index 8208f68f5f1..1178ae52675 100644 --- a/moli-renderer-v8/src/layout_renderer/style_resolver.rs +++ b/moli-renderer-v8/src/layout_renderer/style_resolver.rs @@ -90,7 +90,7 @@ impl<'a> NativeLayoutStyleResolver<'a> { } } -fn layout_style_read_scope<'a>( +pub(super) fn layout_style_read_scope<'a>( runtime: &'a PageScriptHost, document: DomHandle, viewport: LayoutViewport, diff --git a/moli-renderer-v8/src/layout_renderer/svg_geometry.rs b/moli-renderer-v8/src/layout_renderer/svg_geometry.rs new file mode 100644 index 00000000000..cc9be835ffc --- /dev/null +++ b/moli-renderer-v8/src/layout_renderer/svg_geometry.rs @@ -0,0 +1,158 @@ +use std::cell::RefCell; + +use moli_layout::{ + LayoutError, LayoutPoint, LayoutQuad, LayoutQuery, LayoutQueryAnswer, ResolvedLayoutStyle, +}; + +use crate::{ + document_runtime::DomHandle, + native_bridge::{PageScriptHost, element::StyleObservation}, +}; + +use super::inline_svg::{GeometryTarget, parse_live_svg}; + +/// SVG graphics have object geometry rather than CSS layout boxes. CSSOM View +/// requires a single transformed object rectangle for these elements. +pub(crate) fn svg_client_rect( + runtime: &PageScriptHost, + document: DomHandle, + source: DomHandle, +) -> Result>, LayoutError> { + let host = runtime.dom_host(); + let Some(element) = host.node(source).and_then(|node| node.as_element()) else { + return Ok(None); + }; + if element.namespace() != "http://www.w3.org/2000/svg" { + return Ok(None); + } + let mut root = source; + let mut ancestor = host.dom().parent_node(source); + while let Some(parent) = ancestor { + let Some(parent_element) = host.node(parent).and_then(|node| node.as_element()) else { + break; + }; + if parent_element.namespace() != "http://www.w3.org/2000/svg" { + break; + } + root = parent; + ancestor = host.dom().parent_node(parent); + } + if root == source + || host + .node(root) + .is_none_or(|node| node.local_name() != Some("svg")) + { + // The outer SVG has a CSS replaced-element box, just like . + return Ok(None); + } + let mut reads = StyleObservation::new(runtime); + let mut ancestor = Some(source); + while let Some(node) = ancestor { + if host + .node(node) + .and_then(|node| node.as_element()) + .is_some_and(|element| { + element.namespace() == "http://www.w3.org/2000/svg" + && matches!( + element.local_name(), + "defs" | "symbol" | "marker" | "pattern" | "clipPath" | "mask" + ) + }) + { + return Ok(Some(Vec::new())); + } + if let Some(computed) = reads.read(node).computed_values() + && computed.clone_display().is_none() + { + return Ok(Some(Vec::new())); + } + ancestor = host.dom().parent_node(node); + if ancestor == Some(document) { + break; + } + } + let Some(computed) = reads.read(root).computed_values() else { + return Ok(Some(Vec::new())); + }; + let style = ResolvedLayoutStyle::from_stylo(computed); + let model = match runtime + .answer_layout_query_for_document(document, &LayoutQuery::BoxModel { source: root })? + { + LayoutQueryAnswer::BoxModel(model) => model, + _ => unreachable!("SVG viewport box model query"), + }; + let metrics = match runtime + .answer_layout_query_for_document(document, &LayoutQuery::ElementMetrics { source: root })? + { + LayoutQueryAnswer::ElementMetrics(metrics) => metrics, + _ => unreachable!("SVG viewport metrics query"), + }; + // A newly inserted SVG may not yet have a box in the published layout. + // Its local geometry can still be measured, using its SVG viewport; once + // layout publishes the outer box, include that box's placement/transforms. + let metadata = super::inline_svg::replaced_metrics( + host.node(root) + .and_then(|node| node.as_element()) + .expect("SVG root"), + ); + let viewport = metrics + .as_ref() + .map(|metrics| metrics.content_size) + .unwrap_or_else(|| { + moli_layout::LayoutSize::new( + metadata.intrinsic_width.unwrap_or(300.0), + metadata.intrinsic_height.unwrap_or(150.0), + ) + }); + if viewport.width <= 0.0 || viewport.height <= 0.0 { + return Ok(Some(Vec::new())); + } + let marker = format!("__moli_svg_geometry_{}", source.index()); + let id = element + .attribute("id") + .filter(|id| !id.is_empty()) + .unwrap_or(&marker); + let Some(svg) = parse_live_svg( + runtime, + root, + &style, + &RefCell::new(reads), + Some(GeometryTarget { + node: source, + id, + viewport, + }), + ) else { + return Ok(Some(Vec::new())); + }; + let Some(node) = svg.tree().node_by_id(id) else { + return Ok(Some(Vec::new())); + }; + let bounds = node.bounding_box(); + let transform = node.abs_transform(); + let map = |x, y| { + let x2 = transform.sx * x + transform.kx * y + transform.tx; + let y2 = transform.ky * x + transform.sy * y + transform.ty; + if let Some(model) = model.as_ref() { + let [origin, right, _, bottom] = model.content.points; + LayoutPoint::new( + origin.x + + (right.x - origin.x) * x2 / viewport.width + + (bottom.x - origin.x) * y2 / viewport.height, + origin.y + + (right.y - origin.y) * x2 / viewport.width + + (bottom.y - origin.y) * y2 / viewport.height, + ) + } else { + LayoutPoint::new(x2, y2) + } + }; + Ok(Some(vec![LayoutQuad { + points: [ + map(bounds.left(), bounds.top()), + map(bounds.right(), bounds.top()), + map(bounds.right(), bounds.bottom()), + map(bounds.left(), bounds.bottom()), + ], + }])) +} diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs b/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs index 3c12f881f67..67a6b7ab0fb 100644 --- a/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs +++ b/moli-renderer-v8/src/native_bridge/element/geometry/provider.rs @@ -44,6 +44,12 @@ fn published_geometry_query( query: &LayoutQuery, ) -> Result, LayoutError> { if runtime.layout_policy().uses_real_layout() { + if let LayoutQuery::ClientRects { source } = query + && let Some(rects) = + crate::layout_renderer::svg_client_rect(runtime, document, *source)? + { + return Ok(LayoutQueryAnswer::ClientRects(rects)); + } runtime.answer_layout_query_for_document(document, query) } else { Ok(answer_mock_query(runtime, document, query)) @@ -66,7 +72,16 @@ pub(crate) fn published_geometry_batch( batch: &LayoutQueryBatch, ) -> Result, LayoutError> { if runtime.layout_policy().uses_real_layout() { - runtime.answer_layout_for_document(document, batch) + let mut answers = runtime.answer_layout_for_document(document, batch)?; + for (query, answer) in batch.queries.iter().zip(&mut answers.answers) { + if let LayoutQuery::ClientRects { source } = query + && let Some(rects) = + crate::layout_renderer::svg_client_rect(runtime, document, *source)? + { + *answer = LayoutQueryAnswer::ClientRects(rects); + } + } + Ok(answers) } else { Ok(answer_mock_queries( runtime, diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/inline_svg_paint.rs b/moli-renderer-v8/src/runtime/page_vm/tests/inline_svg_paint.rs index e45706113f3..2ab8e6ccbf1 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/inline_svg_paint.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/inline_svg_paint.rs @@ -1,5 +1,126 @@ use super::*; +#[tokio::test(flavor = "current_thread")] +async fn inline_svg_client_rects_include_graphics_text_and_viewport_transforms() { + run_page_vm_async_test(async move { + let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?; + let mut page_vm = test_page_vm_with_loader_and_document_url( + &loader, Vec::new(), Url::parse("https://example.com/svg-client-rects.html")?, + ); + page_vm.vm_mut().eval(&format!( + "document.documentElement.innerHTML = {}; 'installed'", + serde_json::to_string(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/inline-svg-client-rects.html")))?, + ))?; + page_vm.vm_mut().sync_live_document_style_sources(); + page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(400, 300, 1.0))?; + let result = page_vm.vm_mut().eval(r#"JSON.stringify(Object.fromEntries( + ['scene','shape','axis','hidden','transparent','nested','nested-shape','clipped','label','group'].map(id => { + const e=document.getElementById(id), r=e.getBoundingClientRect(); + return [id, {rect:[r.x,r.y,r.width,r.height],count:e.getClientRects().length}]; + })))"#)?; + let values: serde_json::Value = serde_json::from_str(&result)?; + // Chromium 145.0.7632.116, with the same fixture and installed font. + for (id, expected) in [ + ("scene", [40.0, 30.0, 300.0, 200.0]), + ("shape", [70.0, 84.0, 60.0, 30.0]), + ("axis", [70.0, 144.0, 160.0, 0.0]), + ("transparent", [240.0, 50.0, 40.0, 20.0]), + ("nested", [188.0, 122.0, 40.0, 20.0]), + ("nested-shape", [188.0, 122.0, 40.0, 20.0]), + ("clipped", [60.0, 40.0, 40.0, 20.0]), + ] { + for (actual, expected) in values[id]["rect"].as_array().unwrap().iter().zip(expected) { + assert!((actual.as_f64().unwrap() - expected).abs() < 0.01, "{id}: {values}"); + } + assert_eq!(values[id]["count"], 1); + } + assert_eq!(values["hidden"]["count"], 0, "{values}"); + assert_eq!(values["hidden"]["rect"], json!([0,0,0,0])); + assert!(values["label"]["rect"][2].as_f64().unwrap() > 100.0, "text must be shaped: {values}"); + assert!(values["label"]["rect"][3].as_f64().unwrap() > 30.0, "text must be shaped: {values}"); + assert!(values["group"]["rect"][3].as_f64().unwrap() > 120.0, "group must include text: {values}"); + + assert_eq!(page_vm.vm_mut().eval("document.getElementById('shape').getAttribute('fill')")?, "none", "geometry projection must not change authored paint"); + page_vm.vm_mut().eval("document.getElementById('scene').style.cssText += ';transform:translate(11px,13px) scale(2);transform-origin:0 0'; 'changed'")?; + page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0))?; + assert_eq!(page_vm.vm_mut().eval("JSON.stringify((r=>[r.x,r.y,r.width,r.height])(document.getElementById('shape').getBoundingClientRect()))")?, "[111,151,120,60]"); + page_vm.vm_mut().eval("document.getElementById('scene').style.transform = 'matrix(2,0,0,2,11,13)'; 'changed'")?; + page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0))?; + assert_eq!(page_vm.vm_mut().eval("JSON.stringify((r=>[r.x,r.y,r.width,r.height])(document.getElementById('shape').getBoundingClientRect()))")?, "[111,151,120,60]", "outer CSS transforms must be applied once"); + Ok::<_, anyhow::Error>(()) + }).await.expect("SVG client rects must include object geometry"); +} + +#[tokio::test(flavor = "current_thread")] +async fn inline_svg_chart_can_size_itself_from_group_and_text_client_rects() { + run_page_vm_async_test(async move { + let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?; + let mut page_vm = test_page_vm_with_loader_and_document_url( + &loader, Vec::new(), Url::parse("https://example.com/svg-measured-chart.html")?, + ); + page_vm.vm_mut().eval(r##" + document.head.innerHTML = ``; + document.body.innerHTML = ` + + + + + Code review + Issues + Pull requests + Commits + `; + 'installed' + "##)?; + page_vm.vm_mut().sync_live_document_style_sources(); + let result = page_vm.vm_mut().eval(r#"(() => { + const svg=document.querySelector('svg'), g=svg.querySelector('g'); + const rect=g.getBoundingClientRect(), outer=svg.getBoundingClientRect(); + g.setAttribute('transform', `translate(${-rect.left+outer.left} ${-rect.top+outer.top})`); + svg.setAttribute('width', Math.ceil(rect.width)); + svg.setAttribute('height', Math.ceil(rect.height)); + return JSON.stringify([rect.width,rect.height]); + })()"#)?; + let size: Vec = serde_json::from_str(&result)?; + assert!(size[0] > 280.0 && size[0] < 400.0, "chart width: {result}"); + assert!(size[1] > 250.0 && size[1] < 300.0, "chart height: {result}"); + let snapshot = page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(400, 300, 1.0))?.unwrap(); + let raster = moli_paint::raster_snapshot(&snapshot)?; + // Text bounds give the group a fractional translation. Measure the + // antialiased color coverage over white, without requiring axes and + // glyphs to land on whole pixels in every font rasterizer. + let color_coverage = |color: [u8; 3]| { + raster.rgba.chunks_exact(4).map(|pixel| { + let alpha = f64::from(255 - pixel[0]) / f64::from(255 - color[0]); + if (1..3).all(|channel| { + (f64::from(pixel[channel]) - (255.0 - alpha * f64::from(255 - color[channel]))).abs() < 2.0 + }) { alpha } else { 0.0 } + }).sum::() + }; + assert!(color_coverage([64,196,99]) > 500.0, "measured SVG must paint the area"); + assert!(color_coverage([17,99,41]) > 400.0, "external CSS must paint both axes: {}", color_coverage([17,99,41])); + assert!(color_coverage([89,99,110]) > 50.0, "external CSS must paint the labels"); + assert_eq!(page_vm.vm_mut().eval("document.querySelector('svg g').hasAttribute('id')")?, "false", "query identifiers must not leak into the live DOM"); + + // Referenced shapes outside must still inherit from , + // rather than freezing the source element's original inherited fill. + page_vm.vm_mut().eval(r##"document.body.innerHTML = ''; 'installed'"##)?; + page_vm.vm_mut().sync_live_document_style_sources(); + let snapshot = page_vm.vm_mut().screenshot_layout_snapshot(moli_layout::PaintViewport::new(80,40,1.0))?.unwrap(); + let raster = moli_paint::raster_snapshot(&snapshot)?; + let pixel = |x: usize, y: usize| &raster.rgba[(y * raster.width as usize + x) * 4..][..4]; + assert_eq!(pixel(10,10), [0,0,255,255]); + assert_eq!(pixel(40,10), [255,0,0,255]); + Ok::<_, anyhow::Error>(()) + }).await.expect("SVG chart must measure and paint its group"); +} + #[tokio::test(flavor = "current_thread")] async fn screenshot_sizes_viewbox_only_svg_from_available_inline_space() { run_page_vm_async_test(async move { diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs index 7ec1caf2f76..bc77921216b 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/shadow_dom.rs @@ -2911,6 +2911,9 @@ const rect = span.getBoundingClientRect(); const circle = container.querySelector('circle'); yield; const rect = circle.getBoundingClientRect(); + // Chromium 145: SVG graphics expose their transformed object rectangle, + // even though hit testing still resolves to the outer replaced SVG here. + check('svg-circle-rect', rect.left === 8 && rect.top === 8 && rect.width === 100 && rect.height === 100); const pos = document.caretPositionFromPoint(50, 50); check('svg-circle', pos instanceof CaretPosition && pos.offsetNode === circle && pos.offset === 0, `${labelNode(pos && pos.offsetNode)},${circle.namespaceURI},${rect.left},${rect.top},${rect.width},${rect.height}`); } @@ -3001,7 +3004,7 @@ const rect = span.getBoundingClientRect(); assert_eq!( result, - "bad-options:pass|light-text:pass|light-text-rect:pass|inline-block-text-rect:pass|sheet-inline-block-text-rect:pass|svg-circle:fail:svg#:1,http://www.w3.org/2000/svg,0,0,0,0|post-svg-text-rect:pass|input:pass|textarea-wrap:fail|textarea-forced:fail:10,23.75,28,63,60|closed-allowed:pass|shadow-hidden:pass|shadow-hidden-rect:pass|shadow-allowed:pass|nested-hidden:pass|nested-inner:pass|nested-outer:pass|nested-both:pass" + "bad-options:pass|light-text:pass|light-text-rect:pass|inline-block-text-rect:pass|sheet-inline-block-text-rect:pass|svg-circle-rect:pass|svg-circle:fail:svg#:1,http://www.w3.org/2000/svg,8,8,100,100|post-svg-text-rect:pass|input:pass|textarea-wrap:fail|textarea-forced:fail:10,23.75,28,63,60|closed-allowed:pass|shadow-hidden:pass|shadow-hidden-rect:pass|shadow-allowed:pass|nested-hidden:pass|nested-inner:pass|nested-outer:pass|nested-both:pass" ); } #[test] diff --git a/moli-renderer-v8/tests/fixtures/inline-svg-client-rects.html b/moli-renderer-v8/tests/fixtures/inline-svg-client-rects.html new file mode 100644 index 00000000000..7e22fba5080 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/inline-svg-client-rects.html @@ -0,0 +1 @@ +Review \ No newline at end of file