Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(layout): establish filter containing blocks
ldm07f2efded61ce
diff --git a/moli-layout/src/builder.rs b/moli-layout/src/builder.rsindex 003a487ac..cd263e2b5 100644--- a/moli-layout/src/builder.rs+++ b/moli-layout/src/builder.rs@@ -132,7 +132,7 @@ where// `display:none`.root.source = None;}- let mut world = LayoutWorld::new(root);+ let mut world = LayoutWorld::new(root, self.source.root_is_document_element());let root_box = world.root();if root_generates_principal_box {world.map_source(source_root, root_box);diff --git a/moli-layout/src/containment.rs b/moli-layout/src/containment.rsindex d047c0e2b..551dbdfa5 100644--- a/moli-layout/src/containment.rs+++ b/moli-layout/src/containment.rs@@ -5,7 +5,9 @@//! decision here so containing-block selection, stacking, geometry projection,//! hit testing, and paint clipping all consume one Chromium-aligned answer.-use crate::world::{LayoutBox, LayoutBoxKind};+use std::{fmt::Debug, hash::Hash};++use crate::world::{LayoutBox, LayoutBoxId, LayoutBoxKind, LayoutWorld};impl<N> LayoutBox<N> {/// Mirrors Blink's `LayoutObject::IsBox()` boundary.@@ -45,20 +47,6 @@ impl<N> LayoutBox<N> {)}- pub(crate) fn establishes_positioned_containing_block(&self) -> bool {- self.style.establishes_positioned_containing_block(- self.is_css_box(),- self.is_eligible_for_paint_or_layout_containment(),- )- }-- pub(crate) fn establishes_fixed_containing_block(&self) -> bool {- self.style.establishes_fixed_containing_block(- self.is_css_box(),- self.is_eligible_for_paint_or_layout_containment(),- )- }-pub(crate) fn creates_stacking_context(&self,is_root: bool,@@ -77,3 +65,34 @@ impl<N> LayoutBox<N> {&& self.style.applies_paint_containment())}}++impl<N> LayoutWorld<N>+where+ N: Copy + Debug + Eq + Hash,+{+ /// Resolves containing-block capability from both computed style and the+ /// box's identity in this layout tree.+ ///+ /// Filter effects establish containing blocks on inline LayoutObjects too,+ /// but the Filter Effects specifications explicitly exempt the document+ /// element. Keeping that identity-dependent rule on `LayoutWorld` avoids+ /// conflating the root of a subtree layout source with the document+ /// element.+ pub(crate) fn establishes_positioned_containing_block(&self, id: LayoutBoxId) -> bool {+ let layout_box = &self.boxes[id.index()];+ layout_box.style.establishes_positioned_containing_block(+ self.is_document_element(id),+ layout_box.is_css_box(),+ layout_box.is_eligible_for_paint_or_layout_containment(),+ )+ }++ pub(crate) fn establishes_fixed_containing_block(&self, id: LayoutBoxId) -> bool {+ let layout_box = &self.boxes[id.index()];+ layout_box.style.establishes_fixed_containing_block(+ self.is_document_element(id),+ layout_box.is_css_box(),+ layout_box.is_eligible_for_paint_or_layout_containment(),+ )+ }+}diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rsindex dbbc3fb93..063d3ffcd 100644--- a/moli-layout/src/projection.rs+++ b/moli-layout/src/projection.rs@@ -456,9 +456,12 @@ where|| element.is_html_element("td")|| element.is_html_element("th")}),- establishes_positioned_containing_block: layout_box- .establishes_positioned_containing_block(),- establishes_fixed_containing_block: layout_box.establishes_fixed_containing_block(),+ establishes_positioned_containing_block: self+ .world+ .establishes_positioned_containing_block(LayoutBoxId::from_index(index)),+ establishes_fixed_containing_block: self+ .world+ .establishes_fixed_containing_block(LayoutBoxId::from_index(index)),visible: layout_box.style.is_visible(),pointer_events: layout_box.style.accepts_pointer_events(),});diff --git a/moli-layout/src/source.rs b/moli-layout/src/source.rsindex 45922e190..53f24adb4 100644--- a/moli-layout/src/source.rs+++ b/moli-layout/src/source.rs@@ -472,6 +472,16 @@ pub trait LayoutSource {Self: 'a;fn root(&self) -> Self::NodeId;+ /// Whether the view root is the document element associated with its+ /// layout viewport.+ ///+ /// Subtree and synthetic sources also receive an internal viewport-sized+ /// containing block. They must return `false`: document-element CSS+ /// exceptions depend on node identity, not on occupying index zero in a+ /// one-shot layout tree.+ fn root_is_document_element(&self) -> bool {+ false+ }/// Returns the parent in the same flattened tree exposed by [`Self::flat_children`]./// The view root must return `None`, even when it has a DOM parent outside the view.fn flat_parent(&self, node: Self::NodeId) -> Option<Self::NodeId>;diff --git a/moli-layout/src/style.rs b/moli-layout/src/style.rsindex fa28312c1..832de8fa1 100644--- a/moli-layout/src/style.rs+++ b/moli-layout/src/style.rs@@ -521,6 +521,7 @@ pub struct ResolvedLayoutStyle {opacity: f32,blend_mode: PaintBlendMode,has_filter_effect: bool,+ establishes_filter_containing_block: bool,has_clip_path: bool,has_mask: bool,isolation: bool,@@ -577,6 +578,10 @@ impl std::fmt::Debug for ResolvedLayoutStyle {.field("opacity", &self.opacity).field("blend_mode", &self.blend_mode).field("has_filter_effect", &self.has_filter_effect)+ .field(+ "establishes_filter_containing_block",+ &self.establishes_filter_containing_block,+ ).field("has_clip_path", &self.has_clip_path).field("has_mask", &self.has_mask).field("isolation", &self.isolation)@@ -769,6 +774,11 @@ impl ResolvedLayoutStyle {let will_change = computed.clone_will_change().bits;let will_change_containment = will_change.contains(WillChangeBits::CONTAIN);let will_change_position = will_change.contains(WillChangeBits::POSITION);+ // Stylo's FIXPOS_CB_NON_SVG bit is set only for `will-change: filter`+ // and `will-change: backdrop-filter`. It is the same pre-effect hint+ // included by Blink's HasNonInitialFilter* queries.+ let establishes_filter_containing_block =+ has_filter_effect || will_change.contains(WillChangeBits::FIXPOS_CB_NON_SVG);let will_change_stacking_context = will_change.intersects(WillChangeBits::STACKING_CONTEXT_UNCONDITIONAL| WillChangeBits::TRANSFORM@@ -892,6 +902,7 @@ impl ResolvedLayoutStyle {opacity,blend_mode,has_filter_effect,+ establishes_filter_containing_block,has_clip_path,has_mask,isolation,@@ -968,6 +979,7 @@ impl ResolvedLayoutStyle {opacity: 1.0,blend_mode: PaintBlendMode::Normal,has_filter_effect: false,+ establishes_filter_containing_block: false,has_clip_path: false,has_mask: false,isolation: false,@@ -1309,20 +1321,27 @@ impl ResolvedLayoutStyle {pub(crate) fn establishes_positioned_containing_block(&self,+ is_document_element: bool,is_css_box: bool,containment_eligible: bool,) -> bool {self.position.is_positioned()|| self.will_change_position- || self.establishes_fixed_containing_block(is_css_box, containment_eligible)+ || self.establishes_fixed_containing_block(+ is_document_element,+ is_css_box,+ containment_eligible,+ )}pub(crate) fn establishes_fixed_containing_block(&self,+ is_document_element: bool,is_css_box: bool,containment_eligible: bool,) -> bool {- (is_css_box && self.establishes_transform_containing_block)+ (!is_document_element && self.establishes_filter_containing_block)+ || (is_css_box && self.establishes_transform_containing_block)|| (containment_eligible&& (self.layout_containment|| self.paint_containment@@ -1527,6 +1546,7 @@ impl ResolvedLayoutStyle {placeholder.border_colors = PaintBorderColors::all(PaintColor::TRANSPARENT);placeholder.generated_content = GeneratedContent::None;placeholder.establishes_transform_containing_block = false;+ placeholder.establishes_filter_containing_block = false;placeholder.synthetic_transform = None;// This is an internal static-position probe, not the authored CSS// principal box. Do not let copied containment or `will-change`@@ -1966,6 +1986,7 @@ impl ResolvedLayoutStyle {opacity: 1.0,blend_mode: PaintBlendMode::Normal,has_filter_effect: false,+ establishes_filter_containing_block: false,has_clip_path: false,has_mask: false,isolation: false,@@ -2032,6 +2053,7 @@ impl ResolvedLayoutStyle {opacity: 1.0,blend_mode: PaintBlendMode::Normal,has_filter_effect: false,+ establishes_filter_containing_block: false,has_clip_path: false,has_mask: false,isolation: false,diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rsindex aba9e366b..657b1cc47 100644--- a/moli-layout/src/taffy_tree.rs+++ b/moli-layout/src/taffy_tree.rs@@ -816,11 +816,10 @@ whereN: Copy + Debug + Eq + Hash,{while let Some(id) = candidate {- let layout_box = &world.boxes[id.index()];- if layout_box.establishes_positioned_containing_block() {+ if world.establishes_positioned_containing_block(id) {return Some(id);}- candidate = layout_box.parent;+ candidate = world.boxes[id.index()].structural_parent;}None}@@ -833,11 +832,10 @@ whereN: Copy + Debug + Eq + Hash,{while let Some(id) = candidate {- let layout_box = &world.boxes[id.index()];- if layout_box.establishes_fixed_containing_block() {+ if world.establishes_fixed_containing_block(id) {return Some(id);}- candidate = layout_box.parent;+ candidate = world.boxes[id.index()].structural_parent;}None}diff --git a/moli-layout/src/world.rs b/moli-layout/src/world.rsindex d5b176075..c1ded8dac 100644--- a/moli-layout/src/world.rs+++ b/moli-layout/src/world.rs@@ -565,6 +565,9 @@ wherepub(crate) source_mapping: HashMap<N, LayoutBoxId>,pub(crate) display_contents_mapping: HashMap<N, Vec<LayoutBoxId>>,pub(crate) root: LayoutBoxId,+ /// The root is the document element only for a complete document source.+ /// Subtree and synthetic sources still use the same internal root slot.+ pub(crate) root_is_document_element: bool,pub(crate) viewport_scroll_policy: ViewportScrollPolicy,pub(crate) viewport_layout: ViewportLayoutState,pub(crate) css_image_references: Vec<LayoutCssImageReference<N>>,@@ -577,12 +580,13 @@ impl<N> LayoutWorld<N>whereN: Copy + Debug + Eq + Hash,{- pub(crate) fn new(root: LayoutBox<N>) -> Self {+ pub(crate) fn new(root: LayoutBox<N>, root_is_document_element: bool) -> Self {Self {boxes: vec![root],source_mapping: HashMap::new(),display_contents_mapping: HashMap::new(),root: LayoutBoxId::from_index(0),+ root_is_document_element,viewport_scroll_policy: ViewportScrollPolicy::default(),viewport_layout: ViewportLayoutState::default(),css_image_references: Vec::new(),@@ -735,6 +739,10 @@ where.extend_from_slice(child_boxes);}+ pub(crate) fn is_document_element(&self, id: LayoutBoxId) -> bool {+ self.root_is_document_element && id == self.root+ }+pub(crate) fn replace_children(&mut self,parent: LayoutBoxId,diff --git a/moli-renderer-v8/src/layout_renderer/source_view.rs b/moli-renderer-v8/src/layout_renderer/source_view.rsindex ab10e63c9..86b191216 100644--- a/moli-renderer-v8/src/layout_renderer/source_view.rs+++ b/moli-renderer-v8/src/layout_renderer/source_view.rs@@ -57,6 +57,14 @@ impl LayoutSource for NativeLayoutSourceView<'_> {self.root}+ fn root_is_document_element(&self) -> bool {+ self.document.and_then(|document| {+ self.host()+ .dom()+ .document_element_handle_for_document(document)+ }) == Some(self.root)+ }+fn flat_parent(&self, node: Self::NodeId) -> Option<Self::NodeId> {native_flat_parent(self.host(), self.root, node)}diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rsindex ebcdd13b4..d08f24e1b 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs@@ -1247,6 +1247,189 @@ offsets['shadow-action']=shadow.getElementById('shadow-action').offsetParent?.id.expect("containment fixture should run");}+#[tokio::test(flavor = "current_thread")]+async fn filters_establish_containing_blocks_except_on_the_document_element() {+ run_page_vm_async_test(async move {+ let loader =+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");+ let mut page_vm = test_page_vm_with_loader_and_document_url(+ &loader,+ Vec::new(),+ Url::parse("https://example.com/filter-containing-blocks.html")?,+ );+ page_vm.vm_mut().eval(+ r#"+document.head.innerHTML = `<style>+html{filter:opacity(99%);will-change:backdrop-filter}+html,body{margin:0;padding:0}+.case{margin-left:100px;width:160px;height:40px}+#filter{filter:opacity(80%)}+#backdrop{backdrop-filter:blur(0px)}+#will-filter{will-change:filter}+#will-backdrop{will-change:backdrop-filter}+.absolute{position:absolute;left:11px;top:12px;width:10px;height:10px}+.fixed{position:fixed;left:13px;top:14px;width:10px;height:10px}+#inline-owner{margin-left:100px;height:40px}+#inline-filter{filter:opacity(80%)}+#inline-absolute{position:absolute;left:17px;top:18px;width:10px;height:10px}+#root-fixed{position:fixed;left:7px;top:8px;width:10px;height:10px}+</style>`;+document.body.innerHTML = `+<div id=filter class=case><span id=filter-absolute class=absolute></span><span id=filter-fixed class=fixed></span></div>+<div id=backdrop class=case><span id=backdrop-absolute class=absolute></span><span id=backdrop-fixed class=fixed></span></div>+<div id=will-filter class=case><span id=will-filter-absolute class=absolute></span><span id=will-filter-fixed class=fixed></span></div>+<div id=will-backdrop class=case><span id=will-backdrop-absolute class=absolute></span><span id=will-backdrop-fixed class=fixed></span></div>+<div id=inline-owner>prefix <span id=inline-filter>inline<span id=inline-absolute></span></span></div>+<span id=root-fixed></span>`;+'installed'+"#,+ )?;+ page_vm.vm_mut().sync_live_document_style_sources();++ // Geometry queries intentionally consume the last published layout.+ // Publish this mutation through the rendering lifecycle first.+ page_vm+ .vm_mut()+ .screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0))?+ .expect("filter fixture must retain a layout root");++ let result = page_vm.vm_mut().eval(+ r#"JSON.stringify((()=>{+const ids=['filter','backdrop','will-filter','will-backdrop','inline-filter','root-fixed'];+const rect=id=>{const r=document.getElementById(id).getBoundingClientRect();return [r.x,r.y]};+const relative={};+for(const id of ['filter','backdrop','will-filter','will-backdrop']){+ const parent=rect(id);+ for(const suffix of ['absolute','fixed']){+ const child=rect(`${id}-${suffix}`);+ relative[`${id}-${suffix}`]=[child[0]-parent[0],child[1]-parent[1]];+ }+}+const inline=rect('inline-filter');const inlineChild=rect('inline-absolute');+relative['inline-absolute']=[inlineChild[0]-inline[0],inlineChild[1]-inline[1]];+const offsetParents={};+for(const id of Object.keys(relative)) offsetParents[id]=document.getElementById(id).offsetParent?.id??null;+offsetParents['root-fixed']=document.getElementById('root-fixed').offsetParent?.id??null;+return {relative,offsetParents,rootFixed:rect('root-fixed')};+})())"#,+ )?;+ let result: serde_json::Value = serde_json::from_str(&result)?;+ for id in ["filter", "backdrop", "will-filter", "will-backdrop"] {+ for (suffix, expected) in [("absolute", [11.0, 12.0]), ("fixed", [13.0, 14.0])] {+ let child = format!("{id}-{suffix}");+ let actual = result["relative"][&child]+ .as_array()+ .unwrap_or_else(|| panic!("missing relative geometry for {child}: {result}"));+ for (axis, expected) in expected.into_iter().enumerate() {+ let actual = actual[axis].as_f64().expect("numeric geometry") as f32;+ assert!(+ (actual - expected).abs() <= 0.05,+ "{child}[{axis}]: expected {expected}, got {actual}; result={result}"+ );+ }+ assert_eq!(+ result["offsetParents"][&child].as_str(),+ Some(id),+ "unexpected offsetParent for {child}: {result}"+ );+ }+ }+ for (id, expected) in [+ ("inline-absolute", [17.0, 18.0]),+ ("root-fixed", [7.0, 8.0]),+ ] {+ let source = if id == "root-fixed" {+ &result["rootFixed"]+ } else {+ &result["relative"][id]+ };+ let actual = source+ .as_array()+ .unwrap_or_else(|| panic!("missing geometry for {id}: {result}"));+ for (axis, expected) in expected.into_iter().enumerate() {+ let actual = actual[axis].as_f64().expect("numeric geometry") as f32;+ assert!(+ (actual - expected).abs() <= 0.05,+ "{id}[{axis}]: expected {expected}, got {actual}; result={result}"+ );+ }+ }+ assert_eq!(+ result["offsetParents"]["inline-absolute"].as_str(),+ Some("inline-filter"),+ "filter must apply before Blink's IsBox gate: {result}"+ );+ assert_eq!(+ result["offsetParents"]["root-fixed"].as_str(),+ None,+ "the document element is excluded by Filter Effects: {result}"+ );++ // The same filtered element can also be the root of a one-shot+ // subtree source. It is still an ordinary element in its owner+ // document, so occupying LayoutWorld's root slot must not grant the+ // document-element exception.+ let subtree_root = page_vm+ .vm()+ .element_handle_by_id_for_test("filter")+ .expect("filtered subtree root");+ let subtree_children = [+ (+ page_vm+ .vm()+ .element_handle_by_id_for_test("filter-absolute")+ .expect("absolute subtree child"),+ [11.0, 12.0],+ ),+ (+ page_vm+ .vm()+ .element_handle_by_id_for_test("filter-fixed")+ .expect("fixed subtree child"),+ [13.0, 14.0],+ ),+ ];+ let subtree_pass = page_vm.vm().build_layout_pass_for_subtree_for_test(+ subtree_root,+ moli_layout::LayoutPassRequest::new(+ moli_layout::LayoutViewport::new(800, 600, 1.0),+ moli_layout::LayoutFlushReason::Test,+ ),+ )?;+ let subtree_answers = subtree_pass.answer_queries(&moli_layout::LayoutQueryBatch::new(+ subtree_children+ .iter()+ .map(|(source, _)| moli_layout::LayoutQuery::ElementMetrics { source: *source })+ .collect(),+ ));+ for ((source, expected), answer) in subtree_children+ .into_iter()+ .zip(subtree_answers.answers)+ {+ let moli_layout::LayoutQueryAnswer::ElementMetrics(Some(metrics)) = answer else {+ panic!("missing subtree metrics for {source:?}");+ };+ assert_eq!(+ metrics.offset_parent,+ Some(subtree_root),+ "a filtered subtree root must remain an ordinary containing block"+ );+ for (actual, expected) in [metrics.offset_position.x, metrics.offset_position.y]+ .into_iter()+ .zip(expected)+ {+ assert!(+ (actual - expected).abs() <= 0.05,+ "subtree child {source:?}: expected offset {expected}, got {actual}"+ );+ }+ }+ Ok::<_, anyhow::Error>(())+ })+ .await+ .expect("filter containing-block fixture should run");+}+#[tokio::test(flavor = "current_thread")]async fn fixed_flex_auto_margin_consumes_free_space_once() {run_page_vm_async_test(async move {diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rsindex ee5dbc124..72f94d612 100644--- a/moli-renderer-v8/src/script_vm.rs+++ b/moli-renderer-v8/src/script_vm.rs@@ -2824,6 +2824,24 @@ impl ScriptVm {.map_err(anyhow::Error::new)}+ #[cfg(test)]+ pub(crate) fn build_layout_pass_for_subtree_for_test(+ &self,+ root: DomHandle,+ request: moli_layout::LayoutPassRequest,+ ) -> Result<moli_layout::LayoutPassResult<DomHandle>, moli_layout::LayoutError> {+ let context_host = self._context_host.borrow();+ let mut services = moli_layout::DocumentLayoutServices::new();+ let mut embedded_document_services = HashMap::new();+ crate::layout_renderer::build_native_layout_pass(+ &context_host,+ root,+ &mut services,+ &mut embedded_document_services,+ request,+ )+ }+pub(super) fn computed_style_properties_for_inspector_handle(&self,handle: DomHandle,