Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(cssom): read used sizes from existing layout snapshots

ldm0e02b58d0dfc6
diff --git a/moli-layout/src/layout_tree/source_query.rs b/moli-layout/src/layout_tree/source_query.rs
index 58d506fd8..c598a3cc1 100644
--- a/moli-layout/src/layout_tree/source_query.rs
+++ b/moli-layout/src/layout_tree/source_query.rs
@@ -11,7 +11,7 @@ use super::{
LayoutSize, LayoutTransform2D,
},
query::{LayoutElementMetrics, LayoutNodeOutput},
- tree::FrozenLayoutTree,
+ tree::{CssSizingBox, FrozenLayoutTree},
};
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -61,6 +61,24 @@ where
self.element_metrics_for_source_with_offset_parent_filter(source, |_| true)
}
+ /// CSSOM width/height from this snapshot's sizing box, without transforms,
+ /// integer rounding, or absolute CSS zoom. A source without an applicable
+ /// principal box has no used size; consumers keep its computed value.
+ pub fn used_size_for_source(&self, source: N) -> Option<LayoutSize> {
+ let layout_box = self
+ .boxes
+ .iter()
+ .find(|layout_box| layout_box.principal_source == Some(source))?;
+ let rect = match layout_box.css_sizing_box? {
+ CssSizingBox::Content => layout_box.content_box,
+ CssSizingBox::Border => layout_box.border_box,
+ };
+ Some(
+ CssomAbsoluteZoom::new(layout_box.effective_zoom)
+ .size(LayoutSize::new(rect.width, rect.height)),
+ )
+ }
+
/// Returns the exact unprojected content box produced for a source's
/// principal layout box.
///
@@ -472,7 +490,7 @@ where
}
/// Converts effective-zoomed layout scalars to the coordinate space exposed
-/// by CSSOM integer box and scroll metrics. Viewport quads intentionally stay
+/// by CSSOM box sizes and scroll metrics. Viewport quads intentionally stay
/// zoomed: their normalized bases map points back into these unzoomed sizes.
#[derive(Clone, Copy)]
struct CssomAbsoluteZoom(f32);
@@ -783,6 +801,7 @@ mod tests {
geometry_source: Some(1),
principal_source: Some(1),
hit_source: Some(1),
+ css_sizing_box: None,
resolved_grid_tracks: None,
control_paint_order: None,
}],
diff --git a/moli-layout/src/layout_tree/tree.rs b/moli-layout/src/layout_tree/tree.rs
index 2e3a42ac3..61cb0008e 100644
--- a/moli-layout/src/layout_tree/tree.rs
+++ b/moli-layout/src/layout_tree/tree.rs
@@ -10,6 +10,12 @@ use super::model::{
LayoutSize, LayoutViewport,
};
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum CssSizingBox {
+ Content,
+ Border,
+}
+
/// One node in the immutable layout tree retained after a full pass.
///
/// `geometry_source` associates ordinary CSSOM geometry with its source. A
@@ -25,6 +31,11 @@ pub struct FrozenLayoutBox<N> {
pub geometry_source: Option<N>,
pub principal_source: Option<N>,
pub hit_source: Option<N>,
+ /// Sizing basis for CSSOM width/height, sampled with the geometry. `None`
+ /// means these properties have no used size (for example, a non-replaced
+ /// inline). Retaining this discriminator avoids consulting live display
+ /// or box-sizing when an ordinary read reuses an older layout snapshot.
+ pub(crate) css_sizing_box: Option<CssSizingBox>,
pub resolved_grid_tracks: Option<super::model::LayoutResolvedGridTracks>,
/// Paint ordinal of this box's scrollbar/corner surface, if any.
pub(crate) control_paint_order: Option<u32>,
diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rs
index 465182805..e470ea328 100644
--- a/moli-layout/src/projection.rs
+++ b/moli-layout/src/projection.rs
@@ -2,7 +2,7 @@ use std::{collections::HashMap, fmt::Debug, hash::Hash, time::Instant};
use taffy::ResolveOrZero;
-use crate::layout_tree::LayoutCoordinateSpace;
+use crate::layout_tree::{CssSizingBox, LayoutCoordinateSpace};
use crate::overflow::{OverflowProjection, inset_rect, offset_rect, outset_rect};
use crate::stacking::{PaintOrderEvent, build_paint_order};
use crate::style::ResolvedLayoutTransform;
@@ -949,9 +949,19 @@ where
),
coordinate_space,
)| {
- let resolved_grid_tracks = world.boxes[geometry.id.index()]
- .resolved_grid_tracks
- .clone();
+ let layout_box = &world.boxes[geometry.id.index()];
+ let display = layout_box.style.display();
+ let css_sizing_box = (principal_source.is_some()
+ && !matches!(
+ display,
+ crate::LayoutDisplay::None | crate::LayoutDisplay::Contents
+ )
+ && (!display.is_inline_flow() || layout_box.is_replaced()))
+ .then_some(match layout_box.style.taffy.box_sizing {
+ taffy::BoxSizing::ContentBox => CssSizingBox::Content,
+ taffy::BoxSizing::BorderBox => CssSizingBox::Border,
+ });
+ let resolved_grid_tracks = layout_box.resolved_grid_tracks.clone();
FrozenLayoutBox {
geometry,
scroll_extent,
@@ -959,6 +969,7 @@ where
geometry_source,
principal_source,
hit_source,
+ css_sizing_box,
resolved_grid_tracks,
control_paint_order,
}
diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rs
index 757f2d208..4a96d730c 100644
--- a/moli-layout/tests/phase5_output_contract.rs
+++ b/moli-layout/tests/phase5_output_contract.rs
@@ -1914,6 +1914,97 @@ fn display_none_root_uses_an_unmapped_internal_carrier() {
assert!(output.source_output(1).is_none());
}
+#[test]
+fn frozen_used_size_keeps_its_sizing_basis_after_style_inputs_are_discarded() {
+ for box_sizing in [BoxSizing::ContentBox, BoxSizing::BorderBox] {
+ let source = Source(vec![
+ Node::element("root", vec![1]),
+ Node::element("sized", Vec::new()),
+ ]);
+ let mut styles = Styles::default();
+ styles
+ .0
+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));
+ styles.0.insert(
+ 1,
+ resolved(
+ LayoutDisplay::Block,
+ Style {
+ box_sizing,
+ size: Size {
+ width: length(100.25),
+ height: length(50.5),
+ },
+ padding: Rect {
+ left: length(10.0),
+ right: length(10.0),
+ top: length(10.0),
+ bottom: length(10.0),
+ },
+ border: Rect {
+ left: length(5.0),
+ right: length(5.0),
+ top: length(5.0),
+ bottom: length(5.0),
+ },
+ ..Style::default()
+ },
+ ),
+ );
+ let output = build(&source, &mut styles);
+ drop(styles);
+ drop(source);
+ assert_eq!(
+ output.used_size_for_source(1),
+ Some(moli_layout::LayoutSize::new(100.25, 50.5))
+ );
+ let model = output.box_model_for_source(1).expect("sized box");
+ let expected_border_width = if box_sizing == BoxSizing::ContentBox {
+ 130.25
+ } else {
+ 100.25
+ };
+ assert_close(model.border.bounding_rect().width, expected_border_width);
+ assert!(output.paint_snapshot().is_none());
+ }
+}
+
+#[test]
+fn frozen_used_size_excludes_non_replaced_inlines_and_suppressed_boxes() {
+ let source = Source(vec![
+ Node::element("root", vec![1, 2, 3]),
+ Node::element("inline", Vec::new()),
+ Node::element("none", Vec::new()),
+ Node::element("contents", vec![4]),
+ Node::element("child", Vec::new()),
+ ]);
+ let mut styles = Styles::default();
+ for (index, display) in [
+ LayoutDisplay::Block,
+ LayoutDisplay::Inline,
+ LayoutDisplay::None,
+ LayoutDisplay::Contents,
+ LayoutDisplay::Block,
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ styles.0.insert(index, fixed_size(display, 60.0, 25.0));
+ }
+ let output = build(&source, &mut styles);
+ for source in [1, 2, 3, usize::MAX] {
+ assert_eq!(
+ output.used_size_for_source(source),
+ None,
+ "source {source} must not have a CSS sizing box"
+ );
+ }
+ assert_eq!(
+ output.used_size_for_source(4),
+ Some(moli_layout::LayoutSize::new(60.0, 25.0))
+ );
+}
+
#[test]
fn pass_result_owns_complete_box_models_and_answers_a_batch_from_one_pass() {
let source = Source(vec![Node::element("root", Vec::new())]);
diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
index 00662b5c0..3f88bc480 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
@@ -5125,6 +5125,16 @@ fn resolve_moli_computed_style_value(
{
return tracks;
}
+ if matches!(property, "width" | "height")
+ && let Some(size) = used_size_from_layout_snapshot(runtime, handle)
+ {
+ let value = if property == "width" {
+ size.width
+ } else {
+ size.height
+ };
+ return format_non_negative_used_css_px(f64::from(value));
+ }
if property == "width"
&& let Some(width) =
resolve_computed_width_with_inline_fallback(runtime, handle, value, context, resolution)
@@ -5171,6 +5181,21 @@ fn resolve_moli_computed_style_value(
value.to_owned()
}
+fn used_size_from_layout_snapshot(
+ runtime: &JsContextHost,
+ handle: DomHandle,
+) -> Option<moli_layout::LayoutSize> {
+ if !runtime.layout_policy().uses_real_layout() || !runtime.dom_host().is_connected(handle) {
+ return None;
+ }
+ let document = runtime.layout_document_for_source(handle)?;
+ // Reading a CSSOM size never creates or refreshes layout. Use the sizing
+ // basis frozen with the existing geometry, or keep the style-only path.
+ runtime
+ .with_latest_layout_tree_for_document(document, |tree| tree.used_size_for_source(handle))
+ .flatten()
+}
+
fn resolved_grid_template_tracks(
runtime: &JsContextHost,
handle: DomHandle,
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rs b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rs
new file mode 100644
index 000000000..9ab9f5098
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rs
@@ -0,0 +1,365 @@
+use super::*;
+
+mod chromium;
+mod lifecycle;
+
+fn page_with_size_fixture(html: &str) -> anyhow::Result<PageVm> {
+ 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/computed-size.html")?,
+ );
+ page_vm
+ .vm_mut()
+ .set_layout_policy(crate::real_layout_test_policy());
+ page_vm.vm_mut().eval(&format!(
+ "document.head.innerHTML='<style>html,body{{margin:0}}</style>';document.body.innerHTML={};'installed'",
+ serde_json::to_string(html)?,
+ ))?;
+ page_vm.vm_mut().sync_live_document_style_sources();
+ Ok(page_vm)
+}
+
+fn read_sizes(page_vm: &mut PageVm, ids: &[&str]) -> anyhow::Result<serde_json::Value> {
+ read_without_layout(
+ page_vm,
+ &format!(
+ "Object.fromEntries({}.map(id=>{{const s=getComputedStyle(document.getElementById(id));return [id,[s.width,s.height]]}}))",
+ serde_json::to_string(ids)?,
+ ),
+ )
+}
+
+// Assert the cost contract as well as the returned values. A cache hit is
+// insufficient: CSSOM must not call the geometry provider at all, even cold.
+fn read_without_layout(
+ page_vm: &mut PageVm,
+ expression: &str,
+) -> anyhow::Result<serde_json::Value> {
+ let passes = page_vm.vm().layout_pass_observability_for_test().1;
+ let cache = page_vm.vm().layout_snapshot_cache_observability_for_test();
+ let values = page_vm
+ .vm_mut()
+ .eval(&format!("JSON.stringify({expression})"))?;
+ assert_eq!(
+ page_vm.vm().layout_pass_observability_for_test().1,
+ passes,
+ "CSSOM read must not execute layout: {expression}"
+ );
+ assert_eq!(
+ page_vm.vm().layout_snapshot_cache_observability_for_test(),
+ cache,
+ "CSSOM read must not request, publish, or retire layout: {expression}"
+ );
+ Ok(serde_json::from_str(&values)?)
+}
+
+fn publish_size_layout(page_vm: &mut PageVm) -> anyhow::Result<()> {
+ publish_size_layout_at(page_vm, 320, 240)
+}
+
+fn publish_size_layout_at(page_vm: &mut PageVm, width: u32, height: u32) -> anyhow::Result<()> {
+ let passes = page_vm.vm().layout_pass_observability_for_test().1;
+ let publishes = page_vm
+ .vm()
+ .layout_snapshot_cache_observability_for_test()
+ .2;
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(moli_layout::LayoutViewport::new(width, height, 1.0))?
+ .expect("fixture Document should publish a layout snapshot");
+ assert_eq!(
+ page_vm.vm().layout_pass_observability_for_test().1,
+ passes + 1
+ );
+ assert_eq!(
+ page_vm
+ .vm()
+ .layout_snapshot_cache_observability_for_test()
+ .2,
+ publishes + 1
+ );
+ Ok(())
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_reads_never_cold_start_layout() {
+ run_page_vm_async_test(async move {
+ for policy in [moli_page_types::LayoutPolicy::Mock, crate::real_layout_test_policy()] {
+ let mut page_vm = page_with_size_fixture(
+ r#"<div id=auto></div><canvas id=canvas></canvas>
+ <div id=clamped style="width:500px;height:400px;max-width:120px;max-height:80px"></div>"#,
+ )?;
+ page_vm.vm_mut().set_layout_policy(policy);
+ let before = page_vm.vm().layout_pass_observability_for_test().1;
+ let cache = page_vm.vm().layout_snapshot_cache_observability_for_test();
+ assert!(cache.3.is_none());
+ assert_eq!(
+ read_sizes(&mut page_vm, &["auto", "canvas", "clamped"] )?,
+ json!({"auto":["auto","auto"],"canvas":["auto","auto"],"clamped":["500px","400px"]}),
+ );
+ assert_eq!(page_vm.vm_mut().eval(r#"
+(() => {
+ const element = document.getElementById('auto');
+ const held = getComputedStyle(element);
+ for (let i = 0; i < 20; i++) {
+ element.style.width = i + 'px';
+ if (held.width !== i + 'px' || held.getPropertyValue('height') !== 'auto') return 'wrong';
+ }
+ return 'read';
+})()
+"#)?, "read");
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, before);
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test(), cache,
+ "CSSOM size reads must not even request a layout pass on a cold Document");
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("cold computed-size reads should stay style-only");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_uses_frozen_box_sizing_constraints_and_replaced_geometry() {
+ run_page_vm_async_test(async move {
+ let mut page_vm = page_with_size_fixture(r#"
+<div id=auto><div style="height:24px"></div></div>
+<div id=empty></div>
+<div id=content style="width:100.25px;height:40.5px;padding:10px;border:5px solid"></div>
+<div id=border style="box-sizing:border-box;width:100.25px;height:70.5px;padding:10px;border:5px solid"></div>
+<div id=empty-border style="box-sizing:border-box;width:100px;padding:10px;border:5px solid"></div>
+<div id=max style="width:500px;height:400px;max-width:120px;max-height:80px"></div>
+<div id=min style="width:10px;height:5px;min-width:150px;min-height:25px"></div>
+<canvas id=canvas></canvas>
+"#)?;
+ publish_size_layout(&mut page_vm)?;
+ let before = page_vm.vm().layout_pass_observability_for_test().1;
+ let cache = page_vm.vm().layout_snapshot_cache_observability_for_test();
+ assert_eq!(
+ read_sizes(&mut page_vm, &["auto", "empty", "content", "border", "empty-border", "max", "min", "canvas"] )?,
+ json!({
+ // This tall fixture reserves a 15px viewport scrollbar.
+ "auto":["305px","24px"], "empty":["305px","0px"],
+ "content":["100.25px","40.5px"], "border":["100.25px","70.5px"],
+ "empty-border":["100px","30px"], "max":["120px","80px"],
+ "min":["150px","25px"], "canvas":["300px","150px"]
+ }),
+ );
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, before);
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test(), cache,
+ "used-size reads consume the snapshot without invoking the layout provider");
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("computed sizes should use the sampled CSS sizing box");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_uses_layout_for_flex_grid_positioned_and_shrink_to_fit_boxes() {
+ run_page_vm_async_test(async move {
+ let mut page_vm = page_with_size_fixture(r#"
+<div style="display:flex;width:200px;height:60px"><div id=flex style="flex:1"></div></div>
+<div style="display:grid;width:210px;height:90px;grid-template-columns:1fr 2fr"><div id=grid-a></div><div id=grid-b></div></div>
+<div id=shrink style="display:inline-block"><div style="width:45px;height:25px"></div></div>
+<div style="position:relative;width:100px;height:80px"><div id=positioned style="position:absolute;left:10px;right:20px;top:5px;bottom:15px"></div></div>
+<div style="width:240px;padding:10px;border:5px solid"><div id=percent style="width:50%;height:20px"></div></div>
+<div id=vertical style="writing-mode:vertical-rl;width:100px;height:80px"></div>
+"#)?;
+ publish_size_layout(&mut page_vm)?;
+ let before = page_vm.vm().layout_pass_observability_for_test().1;
+ assert_eq!(
+ read_sizes(&mut page_vm, &["flex", "grid-a", "grid-b", "shrink", "positioned", "percent", "vertical"] )?,
+ json!({
+ "flex":["200px","60px"], "grid-a":["70px","90px"], "grid-b":["140px","90px"],
+ "shrink":["45px","25px"], "positioned":["70px","60px"],
+ "percent":["120px","20px"], "vertical":["100px","80px"]
+ }),
+ );
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, before);
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("CSSOM should consume the numeric layout algorithm's used sizes");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_preserves_subpixels_and_removes_zoom_and_transforms() {
+ run_page_vm_async_test(async move {
+ let mut page_vm = page_with_size_fixture(r#"
+<div id=zoomed style="zoom:2;width:100.25px;height:50.5px;padding:2px;border:3px solid"></div>
+<div style="zoom:2"><div id=nested style="zoom:2;width:40.25px;height:20.5px"></div></div>
+<div id=transformed style="width:80px;height:25px;transform:scale(2)"></div>
+<div id=border style="zoom:2;box-sizing:border-box;width:100.25px;height:70.5px;padding:10px;border:5px solid"></div>
+"#)?;
+ publish_size_layout(&mut page_vm)?;
+ let cache = page_vm.vm().layout_snapshot_cache_observability_for_test();
+ assert_eq!(
+ read_sizes(&mut page_vm, &["zoomed", "nested", "transformed", "border"] )?,
+ json!({
+ "zoomed":["100.25px","50.5px"], "nested":["40.25px","20.5px"],
+ "transformed":["80px","25px"], "border":["100.25px","70.5px"]
+ }),
+ );
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test(), cache);
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("CSSOM sizes should stay in untransformed, unzoomed CSS pixels");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_uses_the_content_area_after_classic_scrollbar_reservation() {
+ run_page_vm_async_test(async move {
+ let mut page_vm = page_with_size_fixture(r#"
+<div id=content style="width:100px;height:80px;padding:10px;border:5px solid;overflow:scroll;scrollbar-width:auto"></div>
+<div id=border style="box-sizing:border-box;width:130px;height:110px;padding:10px;border:5px solid;overflow:scroll;scrollbar-width:auto"></div>
+"#)?;
+ publish_size_layout(&mut page_vm)?;
+ let cache = page_vm.vm().layout_snapshot_cache_observability_for_test();
+ assert_eq!(read_sizes(&mut page_vm, &["content", "border"] )?,
+ json!({"content":["85px","65px"],"border":["130px","110px"]}),
+ "content-box resolved sizes exclude classic scrollbars, while border-box sizes include them");
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test(), cache);
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("CSSOM should use the sampled scrollport geometry");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_keeps_computed_values_without_an_applicable_snapshot_box() {
+ run_page_vm_async_test(async move {
+ let mut page_vm = page_with_size_fixture(r#"
+<span id=inline style="width:60px;height:30px;max-width:10px;max-height:10px"></span>
+<span id=auto>inline</span>
+<div id=none style="display:none;width:60px;height:30px;max-width:10px;max-height:10px"></div>
+<div id=contents style="display:contents;width:40%;height:20%"><div style="width:50px;height:25px"></div></div>
+<div style="display:none"><div id=hidden-child></div></div>
+<div id=removed style="width:55px;height:25px"></div>
+"#)?;
+ publish_size_layout(&mut page_vm)?;
+ let before = page_vm.vm().layout_pass_observability_for_test().1;
+ page_vm.vm_mut().eval(r#"
+globalThis.removed = document.getElementById('removed');
+removed.remove();
+const added = document.createElement('div');
+added.id = 'added';
+document.body.appendChild(added);
+'changed'
+"#)?;
+ let cache = page_vm.vm().layout_snapshot_cache_observability_for_test();
+ assert_eq!(
+ read_sizes(&mut page_vm, &["inline", "auto", "none", "contents", "hidden-child", "added"] )?,
+ json!({
+ "inline":["60px","30px"], "auto":["auto","auto"], "none":["60px","30px"],
+ "contents":["40%","20%"], "hidden-child":["auto","auto"], "added":["auto","auto"]
+ }),
+ );
+ assert_eq!(page_vm.vm_mut().eval(
+ "JSON.stringify([getComputedStyle(removed).width,getComputedStyle(removed).height])"
+ )?, r#"["",""]"#, "a disconnected element cannot reuse its old box");
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, before);
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test(), cache);
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("missing or inapplicable boxes should keep the style-only fallback");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_keeps_the_sampled_basis_until_explicit_layout_refresh() {
+ run_page_vm_async_test(async move {
+ let mut page_vm = page_with_size_fixture(
+ r#"<div id=target style="width:100px;height:40px;padding:10px;border:5px solid"></div>"#,
+ )?;
+ page_vm.vm_mut().eval("globalThis.held=getComputedStyle(document.getElementById('target'));'held'")?;
+ publish_size_layout(&mut page_vm)?;
+ let before = page_vm.vm().layout_pass_observability_for_test().1;
+ page_vm.vm_mut().eval(r#"
+document.getElementById('target').style.cssText='box-sizing:border-box;width:250px;height:100px;padding:20px;border:5px solid;zoom:2';
+'changed'
+"#)?;
+ let cache = page_vm.vm().layout_snapshot_cache_observability_for_test();
+ assert!(cache.3.is_some(), "style mutation deliberately leaves sampled geometry available");
+ for _ in 0..3 {
+ assert_eq!(read_sizes(&mut page_vm, &["target"] )?, json!({"target":["100px","40px"]}));
+ assert_eq!(page_vm.vm_mut().eval(
+ "JSON.stringify([held.width,held.getPropertyValue('height'),held.boxSizing,held.zoom])"
+ )?, r#"["100px","40px","border-box","2"]"#,
+ "old geometry must use its own sizing basis and zoom while style-only properties remain live");
+ }
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, before);
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test(), cache);
+ publish_size_layout(&mut page_vm)?;
+ let refreshed = page_vm.vm().layout_pass_observability_for_test().1;
+ assert_eq!(refreshed, before + 1);
+ assert_eq!(page_vm.vm_mut().eval(
+ "JSON.stringify([held.width,held.getPropertyValue('height')])"
+ )?, r#"["250px","100px"]"#, "a held declaration observes the newly published snapshot");
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, refreshed);
+ page_vm.vm_mut().set_layout_policy(moli_page_types::LayoutPolicy::Mock);
+ page_vm.vm_mut().eval("document.getElementById('target').style.width='275px';'changed'")?;
+ assert_eq!(page_vm.vm_mut().eval("held.width")?, "275px");
+ assert!(page_vm.vm().layout_snapshot_cache_observability_for_test().3.is_none());
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, refreshed);
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("CSSOM sizes should respect the explicit snapshot lifecycle");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_selects_the_exact_nested_iframe_document_snapshot() {
+ run_page_vm_async_test(async move {
+ let mut page_vm = page_with_size_fixture(
+ r#"<div id=target></div><iframe id=frame style="width:180px;height:120px;border:0"></iframe>"#,
+ )?;
+ page_vm.vm_mut().eval(r#"
+globalThis.frame = document.getElementById('frame');
+const child = frame.contentDocument;
+child.body.style.margin='0';
+child.body.innerHTML='<div id=target></div><iframe id=nested style="width:90px;height:60px;border:0"></iframe>';
+globalThis.nested = child.getElementById('nested');
+const inner = nested.contentDocument;
+inner.body.style.margin='0';
+inner.body.innerHTML='<div id=target></div>';
+globalThis.childStyle = frame.contentWindow.getComputedStyle(child.getElementById('target'));
+globalThis.nestedStyle = nested.contentWindow.getComputedStyle(inner.getElementById('target'));
+'installed'
+"#)?;
+ let cold = page_vm.vm().layout_pass_observability_for_test().1;
+ assert_eq!(page_vm.vm_mut().eval("JSON.stringify([childStyle.width,nestedStyle.width])")?, r#"["auto","auto"]"#);
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, cold);
+ assert!(page_vm.vm().layout_snapshot_cache_observability_for_test().3.is_none());
+ publish_size_layout(&mut page_vm)?;
+ let before = page_vm.vm().layout_pass_observability_for_test().1;
+ let cache = page_vm.vm().layout_snapshot_cache_observability_for_test();
+ for _ in 0..3 {
+ assert_eq!(page_vm.vm_mut().eval(r#"
+JSON.stringify([
+ getComputedStyle(document.getElementById('target')).width,
+ childStyle.width, nestedStyle.width,
+ getComputedStyle(frame.contentDocument.getElementById('target')).width,
+ getComputedStyle(nested.contentDocument.getElementById('target')).width
+])
+"#)?, r#"["320px","180px","90px","180px","90px"]"#);
+ }
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, before);
+ assert_eq!(page_vm.vm().layout_snapshot_cache_observability_for_test(), cache);
+ page_vm.vm_mut().eval(r#"
+const freshFrame = document.createElement('iframe');
+document.body.appendChild(freshFrame);
+const moved = frame.contentDocument.getElementById('target');
+freshFrame.contentDocument.body.appendChild(moved);
+globalThis.movedStyle = freshFrame.contentWindow.getComputedStyle(moved);
+'moved'
+"#)?;
+ assert_eq!(page_vm.vm_mut().eval("movedStyle.width")?, "auto",
+ "adopting a node into an unsampled Document must not read its previous Document's box");
+ assert_eq!(page_vm.vm().layout_pass_observability_for_test().1, before);
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("computed size should use only the owning Document's existing snapshot");
+}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/chromium.rs b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/chromium.rs
new file mode 100644
index 000000000..c588b867f
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/chromium.rs
@@ -0,0 +1,252 @@
+//! Reduced cases from Chromium's third_party/blink/web_tests.
+//!
+//! Source paths below are relative to that directory. We port the width/height
+//! assertions, not Chromium's implicit style/layout flush: each used-value
+//! comparison follows an explicit Moli layout demand, and every CSSOM read
+//! checks that it did not request or publish layout.
+
+use super::*;
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_chromium_resolved_value_display_and_unit_matrix() {
+ // fast/css/getComputedStyle/getComputedStyle-resolved-values.html and its
+ // checked-in expected output. Omit text so platform fonts cannot affect
+ // the fixture; keep the 500x300 containing block and 24px em basis.
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<div style="width:500px;height:300px"><div id=target></div></div>"#,
+ )?;
+ for display in ["block", "inline", "inline-block", "none"] {
+ for (dimensions, computed, used) in [
+ (
+ "width:150px;height:100px",
+ ["150px", "100px"],
+ ["150px", "100px"],
+ ),
+ ("width:50%;height:25%", ["50%", "25%"], ["250px", "75px"]),
+ (
+ "width:10em;height:5em",
+ ["240px", "120px"],
+ ["240px", "120px"],
+ ),
+ ] {
+ let style = format!(
+ "display:{display};font-size:24px;border:24px solid;padding:20px;{dimensions}"
+ );
+ page.vm_mut().eval(&format!(
+ "document.getElementById('target').style.cssText={};'changed'",
+ serde_json::to_string(&style)?,
+ ))?;
+ publish_size_layout(&mut page)?;
+ let expected = if matches!(display, "inline" | "none") {
+ computed
+ } else {
+ used
+ };
+ assert_eq!(
+ read_sizes(&mut page, &["target"])?,
+ json!({"target":expected}),
+ "{display}: {dimensions}"
+ );
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("Chromium resolved-value display/unit cases");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_chromium_no_box_min_max_matrix() {
+ // external/wpt/css/cssom/getComputedStyle-resolved-min-max-clamping.html.
+ // The same held declarations must remain live both before and after a
+ // snapshot, but inapplicable boxes must never acquire used-value clamping.
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<span id=inline></span><div id=none style="display:none"></div>
+<div id=contents style="display:contents"></div>"#,
+ )?;
+ for sampled in [false, true] {
+ if sampled {
+ publish_size_layout(&mut page)?;
+ }
+ for id in ["inline", "none", "contents"] {
+ page.vm_mut().eval(&format!(
+ "globalThis.target=document.getElementById('{id}');globalThis.held=getComputedStyle(target);\
+ target.style.minWidth=target.style.minHeight='10px';\
+ target.style.maxWidth=target.style.maxHeight='50px';'held'"
+ ))?;
+ for value in ["10%", "15px", "1px", "60px", "auto"] {
+ page.vm_mut().eval(&format!(
+ "target.style.width=target.style.height='{value}';'changed'"
+ ))?;
+ assert_eq!(
+ read_without_layout(&mut page, "[held.width,held.getPropertyValue('height')]")?,
+ json!([value, value]), "{id}, sampled={sampled}, value={value}"
+ );
+ }
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("non-replaced inline/none/contents sizes must remain unclamped");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_chromium_box_sizing_and_padding_floor() {
+ // fast/css/getComputedStyle/getComputedStyle-border-box.html.
+ // Extend its content/border 200px pair with zero-size floors, percentages,
+ // and conflicting min/max values. All numbers are CSS sizing-box sizes,
+ // not offsetWidth/Height (which include border/padding and integer rounding).
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<div style="width:200px;height:120px"><div id=target></div></div>"#,
+ )?;
+ for (dimensions, expected) in [
+ ("width:200px;height:200px", ["200px", "200px"]),
+ (
+ "box-sizing:border-box;width:200px;height:200px",
+ ["200px", "200px"],
+ ),
+ ("width:0;height:0", ["0px", "0px"]),
+ ("box-sizing:border-box;width:0;height:0", ["30px", "30px"]),
+ ("width:50%;height:50%", ["100px", "60px"]),
+ (
+ "box-sizing:border-box;width:50%;height:50%",
+ ["100px", "60px"],
+ ),
+ (
+ "width:0;height:0;min-width:100px;max-width:50px;min-height:60px;max-height:20px",
+ ["100px", "60px"],
+ ),
+ (
+ "visibility:hidden;width:122px;height:33px",
+ ["122px", "33px"],
+ ),
+ ] {
+ page.vm_mut().eval(&format!(
+ "document.getElementById('target').style.cssText={};'changed'",
+ serde_json::to_string(&format!("padding:10px;border:5px solid;{dimensions}"))?,
+ ))?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(
+ read_sizes(&mut page, &["target"])?,
+ json!({"target":expected}),
+ "{dimensions}"
+ );
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("CSSOM must select the sampled sizing box, including its minimum border size");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_chromium_table_cell_height_excludes_authored_padding() {
+ // fast/css/getComputedStyle/getComputedStyle-height.html (WebKit bug 33593).
+ // The original 200px content height must not become the 260px border box.
+ // Also cover border-box cells and their table-generated anonymous boxes.
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<style>table{border-spacing:0}td{padding:20px;border:10px solid}</style>
+<table><tr><td id=content style="width:100px;height:200px"></td></tr></table>
+<table><tr><td id=border style="box-sizing:border-box;width:160px;height:260px"></td></tr></table>"#,
+ )?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["content", "border"])?,
+ json!({"content":["100px","200px"],"border":["160px","260px"]}));
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("table cells should expose the correct CSS sizing box");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_chromium_ancestor_zoom_matrix() {
+ // fast/css/getComputedStyle/script-tests/computed-style-with-zoom.js,
+ // restricted to width/height. Explicitly resample after every ancestor
+ // zoom mutation; a stale snapshot alone would make the equality vacuous.
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<div id=content style="position:absolute;width:20px;height:20px;border:20px solid"></div>
+<div id=border style="box-sizing:border-box;width:100.25px;height:80.5px;border:20px solid"></div>"#,
+ )?;
+ for zoom in ["1", "2", "0.5", "1.25"] {
+ page.vm_mut().eval(&format!("document.body.style.zoom='{zoom}';'changed'"))?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["content", "border"])?,
+ json!({"content":["20px","20px"],"border":["100.25px","80.5px"]}), "zoom={zoom}");
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("CSSOM used sizes should remove the sampled absolute zoom");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_chromium_scrollbar_roundtrip_requires_resampling() {
+ // external/wpt/css/cssom/getComputedStyle-width-scroll.tentative.html and
+ // its Chromium expected.txt: the tentative round-trip assertion FAILS in
+ // Chromium (100 -> 85 -> 70 with classic scrollbars). Do not label stale
+ // snapshot equality as WPT conformance, or change the geometry to satisfy it.
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<div id=target style="width:100px;height:100px;overflow:scroll;scrollbar-width:auto"></div>"#,
+ )?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["85px","85px"]}));
+ page.vm_mut().eval(
+ "const target=document.getElementById('target');const held=getComputedStyle(target);\
+ target.style.width=held.width;target.style.height=held.height;'copied'"
+ )?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["85px","85px"]}));
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["70px","70px"]}));
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("a stale snapshot must not disguise Chromium's scrollbar sizing behavior");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_chromium_replacement_in_inline_block_split() {
+ // external/wpt/css/cssom/getComputedStyle-layout-dependent-replaced-into-ib-split.html.
+ // Deliberate Moli difference: replacement is not a layout demand. Its
+ // percentage width can use the existing style-only fallback, but auto
+ // height must stay auto until an explicit refresh creates its own box.
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<style>#wrapper div{width:100%}</style>
+<section id=wrapper style="width:160px"><span><div id=target></div></span></section>"#,
+ )?;
+ page.vm_mut().eval(
+ "globalThis.oldStyle=getComputedStyle(document.getElementById('target'));'held'",
+ )?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(
+ read_sizes(&mut page, &["target"])?,
+ json!({"target":["160px","0px"]})
+ );
+ page.vm_mut().eval(
+ "const replacement=document.createElement('div');replacement.id='target';\
+ document.getElementById('target').replaceWith(replacement);'replaced'",
+ )?;
+ assert_eq!(
+ read_without_layout(&mut page, "[oldStyle.width,oldStyle.height]")?,
+ json!(["", ""])
+ );
+ assert_eq!(
+ read_sizes(&mut page, &["target"])?,
+ json!({"target":["160px","auto"]})
+ );
+ publish_size_layout(&mut page)?;
+ assert_eq!(
+ read_sizes(&mut page, &["target"])?,
+ json!({"target":["160px","0px"]})
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("a replacement in an inline/block split needs its own sampled box");
+}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/lifecycle.rs b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/lifecycle.rs
new file mode 100644
index 000000000..998019363
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/lifecycle.rs
@@ -0,0 +1,262 @@
+//! Moli's demand-driven boundary, not Chromium's synchronous layout behavior.
+//! Mutation updates DOM/Stylo; CSSOM consumes an existing sample or falls back
+//! to style-only values. Only explicit visual demands may publish new geometry.
+
+use super::*;
+
+fn set_viewport(page: &mut PageVm, width: u32, height: u32) -> anyhow::Result<()> {
+ page.set_viewport_surface(Some(crate::protocol_types::ViewportSurface {
+ inner_width: width,
+ inner_height: height,
+ outer_width: width,
+ outer_height: height,
+ device_pixel_ratio: 1.0,
+ screen_width: width,
+ screen_height: height,
+ screen_avail_width: width,
+ screen_avail_height: height,
+ }))?;
+ Ok(())
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_display_transitions_follow_the_sampled_box() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<div style="width:160px"><div id=target><div style="width:75px;height:25px"></div></div></div>"#,
+ )?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["160px","25px"]}));
+ for (style, before_refresh, after_refresh) in [
+ ("display:inline;width:200px;height:80px", ["160px","25px"], ["200px","80px"]),
+ ("display:block", ["auto","auto"], ["160px","25px"]),
+ ("display:none;width:200px;height:80px", ["160px","25px"], ["200px","80px"]),
+ ("display:contents;width:40%;height:20%", ["40%","20%"], ["40%","20%"]),
+ ("display:block", ["auto","auto"], ["160px","25px"]),
+ ] {
+ page.vm_mut().eval(&format!(
+ "document.getElementById('target').style.cssText={};'changed'",
+ serde_json::to_string(style)?,
+ ))?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":before_refresh}),
+ "before refresh: {style}");
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":after_refresh}),
+ "after refresh: {style}");
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("box applicability must be sampled along with its geometry");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_viewport_change_updates_style_but_not_sampled_geometry() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<style>#target{width:20vw;height:10vh;color:red}
+@media(min-width:500px){#target{color:green}}</style><div id=target></div>"#,
+ )?;
+ set_viewport(&mut page, 320, 240)?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["64px","24px"]}));
+ let passes = page.vm().layout_pass_observability_for_test().1;
+ set_viewport(&mut page, 640, 480)?;
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, passes);
+ assert_eq!(read_without_layout(&mut page,
+ "(() => {const s=getComputedStyle(document.getElementById('target'));return [s.width,s.height,s.color]})()")?,
+ json!(["64px","24px","rgb(0, 128, 0)"]),
+ "media style is live while ordinary geometry still belongs to the old viewport");
+ publish_size_layout_at(&mut page, 640, 480)?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["128px","48px"]}));
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("viewport changes must not turn CSSOM into a visual demand");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_document_replacement_discards_the_old_snapshot() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(r#"<div id=target style="width:100px;height:40px"></div>"#)?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["100px","40px"]}));
+ let passes = page.vm().layout_pass_observability_for_test().1;
+ let publishes = page.vm().layout_snapshot_cache_observability_for_test().2;
+ page.vm_mut().eval(r#"
+document.open();
+document.write('<!doctype html><html><head><style>html,body{margin:0}</style></head><body><div id=target></div></body></html>');
+document.close();
+'replaced'
+"#)?;
+ let cache = page.vm().layout_snapshot_cache_observability_for_test();
+ assert!(cache.3.is_none(), "replacement must retire the old Document's geometry");
+ assert_eq!(cache.2, publishes);
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, passes);
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["auto","auto"]}),
+ "reusing an HTML id must not reuse the previous Document's dimensions");
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["320px","0px"]}));
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("a replacement Document must begin without a sampled box");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_shadow_and_slotted_nodes_share_only_their_document_sample() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<div id=host style="width:160px"><div id=slotted style="width:50%;height:20px"></div></div>"#,
+ )?;
+ page.vm_mut().eval(r#"
+const root=document.getElementById('host').attachShadow({mode:'open'});
+root.innerHTML='<div id=wrapper><slot></slot><div id=target></div></div>';
+globalThis.sheet=new CSSStyleSheet();
+sheet.replaceSync('#wrapper{width:120px}#target{width:50%;height:30px;color:red}');
+root.adoptedStyleSheets=[sheet];
+globalThis.shadowStyle=getComputedStyle(root.getElementById('target'));
+globalThis.slottedStyle=getComputedStyle(document.getElementById('slotted'));
+'installed'
+"#)?;
+ publish_size_layout(&mut page)?;
+ let read = "[shadowStyle.width,shadowStyle.height,slottedStyle.width,slottedStyle.height,shadowStyle.color]";
+ assert_eq!(read_without_layout(&mut page, read)?, json!(["60px","30px","60px","20px","rgb(255, 0, 0)"]));
+ page.vm_mut().eval(
+ "sheet.replaceSync('#wrapper{width:200px}#target{width:75%;height:45px;color:blue}');'changed'"
+ )?;
+ assert_eq!(read_without_layout(&mut page, read)?, json!(["60px","30px","60px","20px","rgb(0, 0, 255)"]));
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_without_layout(&mut page, read)?, json!(["150px","45px","100px","20px","rgb(0, 0, 255)"]));
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("flat-tree layout and live shadow style must remain separate");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_reads_do_not_invalidate_screencast_tokens() {
+ use crate::runtime::{
+ RendererCaptureScreencastFrameReply as Reply, RendererCaptureScreencastFrameRequest,
+ RendererCaptureScreenshotReply, RendererCaptureScreenshotRequest, RendererScreenshotFormat,
+ };
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(r#"<div id=target style="height:10px;background:red"></div>"#)?;
+ set_viewport(&mut page, 40, 30)?;
+ let request = |known_visual_state| RendererCaptureScreencastFrameRequest {
+ format: RendererScreenshotFormat::Png,
+ quality: 100,
+ optimize_for_speed: true,
+ max_width: None,
+ max_height: None,
+ known_visual_state,
+ };
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["auto","10px"]}));
+ let before = page.vm().layout_pass_observability_for_test().1;
+ let Reply::Captured(first) = page.capture_screencast_frame(request(None))? else {
+ panic!("first screencast must capture");
+ };
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, before + 1);
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["40px","10px"]}));
+ assert_eq!(page.capture_screencast_frame(request(Some(first.visual_state.clone())))?, Reply::Unchanged);
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, before + 1);
+ page.vm_mut().eval("document.getElementById('target').style.cssText='width:20px;height:10px;background:blue';'changed'")?;
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["40px","10px"]}));
+ let Reply::Captured(second) = page.capture_screencast_frame(request(Some(first.visual_state)))? else {
+ panic!("style mutation must capture a new frame");
+ };
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, before + 2);
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["20px","10px"]}));
+ let raster = moli_image::decode_png(&second.image.bytes)?;
+ assert_eq!(&raster.rgba[0..4], &[0,0,255,255], "fresh capture must paint fresh style");
+ assert_eq!(page.capture_screencast_frame(request(Some(second.visual_state)))?, Reply::Unchanged);
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, before + 2);
+ assert!(matches!(page.capture_screenshot(RendererCaptureScreenshotRequest::viewport_png())?,
+ RendererCaptureScreenshotReply::Captured(_)));
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, before + 3,
+ "screenshot is a fresh demand even when a screencast would be unchanged");
+ assert_eq!(read_sizes(&mut page, &["target"])?, json!({"target":["20px","10px"]}));
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("CSSOM reads must neither request frames nor dirty clean screencast tokens");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_page_snapshots_are_independent() {
+ run_page_vm_async_test(async move {
+ let mut first =
+ page_with_size_fixture(r#"<div id=target style="width:100px;height:40px"></div>"#)?;
+ let mut second =
+ page_with_size_fixture(r#"<div id=target style="width:200px;height:80px"></div>"#)?;
+ publish_size_layout(&mut first)?;
+ publish_size_layout(&mut second)?;
+ first.vm_mut().eval(
+ "document.getElementById('target').style.cssText='width:300px;height:120px';'changed'",
+ )?;
+ assert_eq!(
+ read_sizes(&mut first, &["target"])?,
+ json!({"target":["100px","40px"]})
+ );
+ assert_eq!(
+ read_sizes(&mut second, &["target"])?,
+ json!({"target":["200px","80px"]})
+ );
+ publish_size_layout(&mut second)?;
+ assert_eq!(
+ read_sizes(&mut first, &["target"])?,
+ json!({"target":["100px","40px"]})
+ );
+ let second_cache = second.vm().layout_snapshot_cache_observability_for_test();
+ publish_size_layout(&mut first)?;
+ assert_eq!(
+ read_sizes(&mut first, &["target"])?,
+ json!({"target":["300px","120px"]})
+ );
+ assert_eq!(
+ read_sizes(&mut second, &["target"])?,
+ json!({"target":["200px","80px"]})
+ );
+ assert_eq!(
+ second.vm().layout_snapshot_cache_observability_for_test(),
+ second_cache
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("publishing one Page must not replace another Page's latest sample");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_pseudo_declarations_never_borrow_the_originating_box() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(
+ r#"<style>#target::before{content:'';display:block;width:12px;height:6px}
+#target::after{content:'';display:block;width:20px;height:8px}</style>
+<div id=target style="width:120px;height:40px"></div>"#,
+ )?;
+ page.vm_mut().eval(
+ "globalThis.target=document.getElementById('target');\
+ globalThis.before=getComputedStyle(target,'::before');\
+ globalThis.after=getComputedStyle(target,'::after');'held'",
+ )?;
+ let read = "[before.width,before.height,after.width,after.height]";
+ assert_eq!(
+ read_without_layout(&mut page, read)?,
+ json!(["12px", "6px", "20px", "8px"])
+ );
+ publish_size_layout(&mut page)?;
+ assert_eq!(
+ read_sizes(&mut page, &["target"])?,
+ json!({"target":["120px","40px"]})
+ );
+ assert_eq!(
+ read_without_layout(&mut page, read)?,
+ json!(["12px", "6px", "20px", "8px"]),
+ "the element's principal box is not the pseudo-element's sizing box"
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("pseudo declarations must not accidentally consume their origin's geometry");
+}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
index cac8d280f..b92a11843 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
@@ -116,6 +116,7 @@ mod child_parser_module_root_start_completion;
mod child_realm_materialization;
mod child_realm_materialization_completion;
mod command_checkpoint;
+mod computed_size;
mod cssom_zoom;
mod dedicated_worker_client_event;
mod document_script_completion;
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.rs
index 3fcab8f21..32090e210 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
@@ -3145,6 +3145,15 @@ document.body.innerHTML = `
"16px|16px",
"SVG presentation attributes must resolve 1em through the element's computed font size like Chromium",
);
+ // Before layout exists, CSSOM exposes the live style-only values.
+ // Keep cascade precedence separate from sampled used-size semantics.
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ "const icon=document.getElementById('feishu-time');icon.setAttribute('width','2em');const fromAttribute=getComputedStyle(icon).width;icon.classList.add('css-width');const fromCss=getComputedStyle(icon).width;icon.classList.remove('css-width');const restored=getComputedStyle(icon).width;icon.setAttribute('width','1em');[fromAttribute,fromCss,restored].join('|')",
+ )?,
+ "32px|24px|32px",
+ "mutated presentation attributes must recascade and author CSS must override them",
+ );
let first = page_vm
.vm_mut()
@@ -3199,15 +3208,22 @@ document.body.innerHTML = `
)?;
assert_eq!(
page_vm.vm_mut().eval(
- "const icon=document.getElementById('feishu-time');const fromAttribute=getComputedStyle(icon).width;icon.classList.add('css-width');const fromCss=getComputedStyle(icon).width;icon.classList.remove('css-width');[fromAttribute,fromCss,getComputedStyle(icon).width].join('|')",
+ "getComputedStyle(document.getElementById('feishu-time')).width",
)?,
- "32px|24px|32px",
- "mutated presentation attributes must recascade and author CSS must override them",
+ "16px",
+ "CSSOM must reuse the existing used size until an explicit layout refresh",
);
let second = page_vm
.vm_mut()
.screenshot_layout_snapshot(moli_layout::PaintViewport::new(220, 190, 1.0))?
.expect("mutated inline SVG fixture must retain a layout root");
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ "getComputedStyle(document.getElementById('feishu-time')).width",
+ )?,
+ "32px",
+ "fresh layout must sample the mutated style rather than the old CSSOM used size",
+ );
assert_eq!(second.svg_images.len(), 3);
assert!(second.fragments.iter().any(|fragment| {
matches!(
diff --git a/moli/tests/fetch_cli/eval.rs b/moli/tests/fetch_cli/eval.rs
index 2543b5007..7dacf25d1 100644
--- a/moli/tests/fetch_cli/eval.rs
+++ b/moli/tests/fetch_cli/eval.rs
@@ -65,6 +65,65 @@ fn run_eval_source(
run_moli(args)
}
+#[test]
+fn eval_computed_sizes_only_use_existing_geometry_with_or_without_css() -> Result<()> {
+ let url = "data:text/html,<!doctype html><div id=target style=\"max-width:20px\"></div><canvas id=canvas style=\"max-width:40px\"></canvas>";
+ let script = r#"(() => {
+ const target = document.getElementById('target');
+ const canvas = document.getElementById('canvas');
+ const targetStyle = getComputedStyle(target), canvasStyle = getComputedStyle(canvas);
+ const read = () => [targetStyle.width, targetStyle.height, canvasStyle.width, canvasStyle.height];
+ const before = read();
+ const geometry = [target.offsetWidth, target.offsetHeight, canvas.offsetWidth, canvas.offsetHeight];
+ return { before, geometry, after: read() };
+ })()"#;
+ for args in [
+ vec![],
+ vec!["--disable-css"],
+ vec!["--layout"],
+ vec!["--layout", "--disable-css"],
+ ] {
+ let output = run_eval(url, script, &args)?;
+ assert!(
+ output.status.success(),
+ "{args:?}: {}",
+ clean_output(&output.stderr)
+ );
+ let value: serde_json::Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(
+ value["before"],
+ serde_json::json!(["auto", "auto", "auto", "auto"]),
+ "width/height must not initiate layout: {args:?}: {value}"
+ );
+ if args.contains(&"--layout") {
+ let expected = value["geometry"]
+ .as_array()
+ .expect("geometry array")
+ .iter()
+ .map(|value| format!("{}px", value.as_i64().expect("integer offset size")))
+ .collect::<Vec<_>>();
+ assert_eq!(
+ value["after"],
+ serde_json::json!(expected),
+ "{args:?}: {value}"
+ );
+ if args.contains(&"--disable-css") {
+ assert!(value["geometry"][0].as_i64().expect("block width") > 20);
+ assert_eq!(value["geometry"][2], 300);
+ assert_eq!(value["geometry"][3], 150);
+ } else {
+ assert_eq!(value["geometry"], serde_json::json!([20, 0, 40, 20]));
+ }
+ } else {
+ assert_eq!(
+ value["after"], value["before"],
+ "Mock geometry must not manufacture a real layout snapshot"
+ );
+ }
+ }
+ Ok(())
+}
+
#[test]
fn eval_uses_standard_document_apis_and_writes_text() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;