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): resolve logical sizes from sampled layout axes

ldm05ee69560fc2a
diff --git a/moli-layout/src/layout_tree/model.rs b/moli-layout/src/layout_tree/model.rs
index 07fd2e17d..fbdb0c589 100644
--- a/moli-layout/src/layout_tree/model.rs
+++ b/moli-layout/src/layout_tree/model.rs
@@ -57,6 +57,17 @@ impl LayoutSize {
}
}
+/// A short-lived CSSOM projection of one sampled sizing box. Physical and
+/// logical dimensions are untransformed, unzoomed CSS pixels, and use the
+/// writing axes captured with that box rather than the current live style.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct LayoutUsedSize {
+ pub width: f32,
+ pub height: f32,
+ pub inline_size: f32,
+ pub block_size: f32,
+}
+
/// Frozen resolved track list for one axis of a CSS Grid formatting context.
///
/// Track sizes are retained in layout CSS pixels at Blink-compatible 1/64-pixel
diff --git a/moli-layout/src/layout_tree/source_query.rs b/moli-layout/src/layout_tree/source_query.rs
index c598a3cc1..999e6e138 100644
--- a/moli-layout/src/layout_tree/source_query.rs
+++ b/moli-layout/src/layout_tree/source_query.rs
@@ -8,7 +8,7 @@ use super::{
model::{
LayoutBoxModel, LayoutCoordinateSpaceId, LayoutFragmentBoxModel, LayoutFragmentKind,
LayoutOutputBoxId, LayoutPoint, LayoutQuad, LayoutRect, LayoutResolvedGridTracks,
- LayoutSize, LayoutTransform2D,
+ LayoutSize, LayoutTransform2D, LayoutUsedSize,
},
query::{LayoutElementMetrics, LayoutNodeOutput},
tree::{CssSizingBox, FrozenLayoutTree},
@@ -61,22 +61,32 @@ where
self.element_metrics_for_source_with_offset_parent_filter(source, |_| true)
}
- /// CSSOM width/height from this snapshot's sizing box, without transforms,
+ /// Physical and logical CSSOM sizes 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> {
+ pub fn used_size_for_source(&self, source: N) -> Option<LayoutUsedSize> {
let layout_box = self
.boxes
.iter()
.find(|layout_box| layout_box.principal_source == Some(source))?;
- let rect = match layout_box.css_sizing_box? {
+ let sizing = layout_box.css_sizing?;
+ let rect = match sizing.box_kind {
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)),
- )
+ let size = CssomAbsoluteZoom::new(layout_box.effective_zoom)
+ .size(LayoutSize::new(rect.width, rect.height));
+ let (inline_size, block_size) = if sizing.horizontal {
+ (size.width, size.height)
+ } else {
+ (size.height, size.width)
+ };
+ Some(LayoutUsedSize {
+ width: size.width,
+ height: size.height,
+ inline_size,
+ block_size,
+ })
}
/// Returns the exact unprojected content box produced for a source's
@@ -801,7 +811,7 @@ mod tests {
geometry_source: Some(1),
principal_source: Some(1),
hit_source: Some(1),
- css_sizing_box: None,
+ css_sizing: 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 61cb0008e..e8276c3d8 100644
--- a/moli-layout/src/layout_tree/tree.rs
+++ b/moli-layout/src/layout_tree/tree.rs
@@ -16,6 +16,12 @@ pub(crate) enum CssSizingBox {
Border,
}
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) struct CssSizing {
+ pub box_kind: CssSizingBox,
+ pub horizontal: bool,
+}
+
/// One node in the immutable layout tree retained after a full pass.
///
/// `geometry_source` associates ordinary CSSOM geometry with its source. A
@@ -31,11 +37,12 @@ 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
+ /// Box selection and logical-axis orientation for CSSOM sizes, sampled
+ /// with the geometry. `None` means 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>,
+ /// or box-sizing/writing-mode when an ordinary read reuses an older layout
+ /// snapshot. This is interpretation metadata, not another copy of sizes.
+ pub(crate) css_sizing: Option<CssSizing>,
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/lib.rs b/moli-layout/src/lib.rs
index e8b9c78d3..11b3b16de 100644
--- a/moli-layout/src/lib.rs
+++ b/moli-layout/src/lib.rs
@@ -56,8 +56,8 @@ pub use layout_tree::{
LayoutPassMetrics, LayoutPassResult, LayoutPoint, LayoutQuad, LayoutQuery, LayoutQueryAnswer,
LayoutQueryBatch, LayoutRect, LayoutResolvedGridTrackList, LayoutResolvedGridTracks,
LayoutScrollContainerMetrics, LayoutScrollExtent, LayoutScrollIntoViewGeometry, LayoutSize,
- LayoutTransform2D, LayoutTreeRetentionMetrics, LayoutViewport, MAX_RETAINED_LAYOUT_BOXES,
- MAX_RETAINED_LAYOUT_FRAGMENTS, MAX_RETAINED_LAYOUT_TREE_BYTES,
+ LayoutTransform2D, LayoutTreeRetentionMetrics, LayoutUsedSize, LayoutViewport,
+ MAX_RETAINED_LAYOUT_BOXES, MAX_RETAINED_LAYOUT_FRAGMENTS, MAX_RETAINED_LAYOUT_TREE_BYTES,
};
pub use normalize::{NormalizedBoxNode, NormalizedBoxTree, NormalizedFormattingContext};
pub use normalize_source::{
diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rs
index e470ea328..ded04acbe 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::{CssSizingBox, LayoutCoordinateSpace};
+use crate::layout_tree::{CssSizing, CssSizingBox, LayoutCoordinateSpace};
use crate::overflow::{OverflowProjection, inset_rect, offset_rect, outset_rect};
use crate::stacking::{PaintOrderEvent, build_paint_order};
use crate::style::ResolvedLayoutTransform;
@@ -951,15 +951,18 @@ where
)| {
let layout_box = &world.boxes[geometry.id.index()];
let display = layout_box.style.display();
- let css_sizing_box = (principal_source.is_some()
+ let css_sizing = (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,
+ .then_some(CssSizing {
+ box_kind: match layout_box.style.taffy.box_sizing {
+ taffy::BoxSizing::ContentBox => CssSizingBox::Content,
+ taffy::BoxSizing::BorderBox => CssSizingBox::Border,
+ },
+ horizontal: layout_box.style.uses_horizontal_writing_mode(),
});
let resolved_grid_tracks = layout_box.resolved_grid_tracks.clone();
FrozenLayoutBox {
@@ -969,7 +972,7 @@ where
geometry_source,
principal_source,
hit_source,
- css_sizing_box,
+ css_sizing,
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 4a96d730c..58ede2864 100644
--- a/moli-layout/tests/phase5_output_contract.rs
+++ b/moli-layout/tests/phase5_output_contract.rs
@@ -1956,7 +1956,12 @@ fn frozen_used_size_keeps_its_sizing_basis_after_style_inputs_are_discarded() {
drop(source);
assert_eq!(
output.used_size_for_source(1),
- Some(moli_layout::LayoutSize::new(100.25, 50.5))
+ Some(moli_layout::LayoutUsedSize {
+ width: 100.25,
+ height: 50.5,
+ inline_size: 100.25,
+ block_size: 50.5
+ })
);
let model = output.box_model_for_source(1).expect("sized box");
let expected_border_width = if box_sizing == BoxSizing::ContentBox {
@@ -2001,7 +2006,12 @@ fn frozen_used_size_excludes_non_replaced_inlines_and_suppressed_boxes() {
}
assert_eq!(
output.used_size_for_source(4),
- Some(moli_layout::LayoutSize::new(60.0, 25.0))
+ Some(moli_layout::LayoutUsedSize {
+ width: 60.0,
+ height: 25.0,
+ inline_size: 60.0,
+ block_size: 25.0
+ })
);
}
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 3f88bc480..314d954d3 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,13 +5125,15 @@ fn resolve_moli_computed_style_value(
{
return tracks;
}
- if matches!(property, "width" | "height")
+ if matches!(property, "width" | "height" | "inline-size" | "block-size")
&& let Some(size) = used_size_from_layout_snapshot(runtime, handle)
{
- let value = if property == "width" {
- size.width
- } else {
- size.height
+ let value = match property {
+ "width" => size.width,
+ "height" => size.height,
+ "inline-size" => size.inline_size,
+ "block-size" => size.block_size,
+ _ => unreachable!(),
};
return format_non_negative_used_css_px(f64::from(value));
}
@@ -5184,7 +5186,7 @@ fn resolve_moli_computed_style_value(
fn used_size_from_layout_snapshot(
runtime: &JsContextHost,
handle: DomHandle,
-) -> Option<moli_layout::LayoutSize> {
+) -> Option<moli_layout::LayoutUsedSize> {
if !runtime.layout_policy().uses_real_layout() || !runtime.dom_host().is_connected(handle) {
return None;
}
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
index 9ab9f5098..3d993526f 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rs
@@ -2,6 +2,7 @@ use super::*;
mod chromium;
mod lifecycle;
+mod logical;
fn page_with_size_fixture(html: &str) -> anyhow::Result<PageVm> {
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/logical.rs b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/logical.rs
new file mode 100644
index 000000000..4f28f3d01
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/logical.rs
@@ -0,0 +1,174 @@
+//! Logical counterparts of the physical resolved sizes. Like the Chromium
+//! css/css-logical/parsing/{inline,block}-size-computed.html WPTs, these read
+//! through both IDL attributes and getPropertyValue. Unlike Chromium, a read
+//! must never initiate layout: the fixture explicitly publishes each sample.
+
+use super::*;
+
+fn read_logical_sizes(page: &mut PageVm, ids: &[&str]) -> anyhow::Result<serde_json::Value> {
+ read_without_layout(
+ page,
+ &format!(
+ "Object.fromEntries({}.map(id=>{{const s=getComputedStyle(document.getElementById(id));return [id,[s.width,s.height,s.inlineSize,s.blockSize,s.getPropertyValue('inline-size'),s.getPropertyValue('block-size')]]}}))",
+ serde_json::to_string(ids)?,
+ ),
+ )
+}
+
+fn expected_sizes(width: &str, height: &str, horizontal: bool) -> serde_json::Value {
+ let (inline, block) = if horizontal {
+ (width, height)
+ } else {
+ (height, width)
+ };
+ json!([width, height, inline, block, inline, block])
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_logical_resolved_values_from_chromium_wpt_use_explicit_samples() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(r#"
+<div style="width:200px;height:300px"><div id=target style="width:0;height:0;font-size:40px"><div style="width:60px;height:80px"></div></div></div>
+"#)?;
+ for (property, auto, percent, intrinsic) in [
+ ("inline-size", "200px", "40px", "60px"),
+ ("block-size", "80px", "60px", "80px"),
+ ] {
+ for (specified, expected) in [
+ ("auto", auto), ("10px", "10px"), ("20%", percent),
+ ("calc(0.5em + 10px)", "30px"), ("calc(-0.5em + 10px)", "0px"),
+ ("min-content", intrinsic), ("max-content", intrinsic),
+ ] {
+ page.vm_mut().eval(&format!(
+ "document.getElementById('target').style.cssText='width:0;height:0;font-size:40px;{property}:{specified}';'changed'"
+ ))?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_without_layout(&mut page, &format!(
+ "getComputedStyle(document.getElementById('target')).getPropertyValue('{property}')"
+ ))?, json!(expected), "{property}: {specified}");
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("logical resolved-value WPT cases should consume explicit Moli samples");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_logical_axes_follow_sampled_constraints_box_sizing_and_zoom() {
+ run_page_vm_async_test(async move {
+ for writing_mode in ["horizontal-tb", "vertical-rl", "vertical-lr"] {
+ for direction in ["ltr", "rtl"] {
+ let mut page = page_with_size_fixture(&format!(r#"
+<div style="writing-mode:{writing_mode};direction:{direction};zoom:2">
+ <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:30px;min-height:25px"></div>
+ <div id=border style="box-sizing:border-box;width:90.25px;height:60.5px;padding:10px;border:5px solid;transform:scale(2)"></div>
+ <div id=content style="width:90.25px;height:60.5px;padding:10px;border:5px solid"></div>
+</div>"#))?;
+ publish_size_layout(&mut page)?;
+ let horizontal = writing_mode == "horizontal-tb";
+ assert_eq!(read_logical_sizes(&mut page, &["max", "min", "border", "content"] )?,
+ json!({
+ "max":expected_sizes("120px","80px",horizontal),
+ "min":expected_sizes("30px","25px",horizontal),
+ "border":expected_sizes("90.25px","60.5px",horizontal),
+ "content":expected_sizes("90.25px","60.5px",horizontal),
+ }), "{writing_mode}, {direction}");
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("logical dimensions must select the same sampled CSS sizing box");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_logical_cold_and_non_box_reads_stay_style_only() {
+ run_page_vm_async_test(async move {
+ for policy in [moli_page_types::LayoutPolicy::Mock, crate::real_layout_test_policy()] {
+ let mut page = page_with_size_fixture(r#"
+<div id=auto></div>
+<div id=clamped style="writing-mode:vertical-rl;width:500px;height:400px;max-width:120px;max-height:80px"></div>
+<span id=inline style="width:50%;height:20%"></span>
+<div id=none style="display:none;width:50%;height:20%"></div>
+<div id=contents style="display:contents;width:50%;height:20%"></div>
+"#)?;
+ page.vm_mut().set_layout_policy(policy);
+ assert_eq!(read_logical_sizes(&mut page, &["auto", "clamped"] )?, json!({
+ "auto":expected_sizes("auto","auto",true),
+ "clamped":expected_sizes("500px","400px",false),
+ }));
+ let unboxed = read_logical_sizes(&mut page, &["inline", "none", "contents"] )?;
+ assert_eq!(unboxed, json!({
+ "inline":expected_sizes("50%","20%",true),
+ "none":expected_sizes("50%","20%",true),
+ "contents":expected_sizes("50%","20%",true),
+ }));
+ if policy.uses_real_layout() {
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_logical_sizes(&mut page, &["inline", "none", "contents"] )?, unboxed);
+ page.vm_mut().eval("globalThis.added=document.createElement('div');added.id='new';document.body.appendChild(added);'added'")?;
+ assert_eq!(read_logical_sizes(&mut page, &["new"] )?, json!({"new":expected_sizes("auto","auto",true)}));
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("logical dimensions must not manufacture a box or start layout");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_logical_held_declarations_keep_sampled_writing_axes_until_refresh() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(r#"<div id=parent><div id=target style="width:500px;height:400px;max-width:120px;max-height:80px"></div></div>"#)?;
+ page.vm_mut().eval("globalThis.held=getComputedStyle(document.getElementById('target'));'held'")?;
+ let read = "[held.width,held.height,held.inlineSize,held.blockSize,held.getPropertyValue('inline-size'),held.getPropertyValue('block-size')]";
+ publish_size_layout(&mut page)?;
+ let mut horizontal = true;
+ for mode in ["vertical-rl", "vertical-lr", "horizontal-tb"] {
+ page.vm_mut().eval(&format!("document.getElementById('parent').style.writingMode='{mode}';'changed'"))?;
+ assert_eq!(read_without_layout(&mut page, "held.writingMode")?, json!(mode), "computed style stays live");
+ assert_eq!(read_without_layout(&mut page, read)?, expected_sizes("120px","80px",horizontal), "old sample after {mode}");
+ publish_size_layout(&mut page)?;
+ horizontal = mode == "horizontal-tb";
+ assert_eq!(read_without_layout(&mut page, read)?, expected_sizes("120px","80px",horizontal), "fresh sample after {mode}");
+ }
+ page.vm_mut().eval("document.getElementById('target').remove();'removed'")?;
+ assert_eq!(read_without_layout(&mut page, read)?, json!(["","","","","",""]), "a held declaration must not revive a removed target's geometry");
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("logical axes must have the same lifetime as their geometry");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_logical_auto_and_replaced_sizes_use_existing_samples() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(r#"
+<div style="width:160px"><div id=auto><div style="height:20px"></div></div></div>
+<canvas id=canvas style="writing-mode:vertical-rl"></canvas>
+<div style="writing-mode:vertical-lr;width:100px;height:80px;position:relative"><div id=positioned style="position:absolute;inset:10px"></div></div>
+"#)?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_logical_sizes(&mut page, &["auto", "canvas", "positioned"] )?, json!({
+ "auto":expected_sizes("160px","20px",true),
+ "canvas":expected_sizes("300px","150px",false),
+ "positioned":expected_sizes("80px","60px",false),
+ }));
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("auto and replaced logical sizes must use numeric layout results");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_logical_iframe_and_shadow_axes_are_local_to_the_sampled_box() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(r#"<div id=host></div><iframe id=frame style="width:180px;height:120px;border:0"></iframe>"#)?;
+ page.vm_mut().eval(r#"
+const root=document.getElementById('host').attachShadow({mode:'open'});
+root.innerHTML='<style>:host{writing-mode:vertical-lr}#target{width:500px;height:400px;max-width:40px;max-height:20px}</style><div id=target></div>';
+globalThis.shadowStyle=getComputedStyle(root.getElementById('target'));
+const frame=document.getElementById('frame');
+frame.contentDocument.body.innerHTML='<div id=target style="writing-mode:vertical-rl;width:500px;height:400px;max-width:90px;max-height:30px"></div>';
+globalThis.childStyle=frame.contentWindow.getComputedStyle(frame.contentDocument.getElementById('target'));
+'installed'
+"#)?;
+ publish_size_layout(&mut page)?;
+ assert_eq!(read_without_layout(&mut page,
+ "[shadowStyle.width,shadowStyle.height,shadowStyle.inlineSize,shadowStyle.blockSize,childStyle.width,childStyle.height,childStyle.inlineSize,childStyle.blockSize]")?,
+ json!(["40px","20px","20px","40px","90px","30px","30px","90px"]));
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("logical dimensions must use each target's own frozen axes and Document");
+}
diff --git a/moli/tests/fetch_cli/eval.rs b/moli/tests/fetch_cli/eval.rs
index 7dacf25d1..e6604928c 100644
--- a/moli/tests/fetch_cli/eval.rs
+++ b/moli/tests/fetch_cli/eval.rs
@@ -73,9 +73,11 @@ fn eval_computed_sizes_only_use_existing_geometry_with_or_without_css() -> Resul
const canvas = document.getElementById('canvas');
const targetStyle = getComputedStyle(target), canvasStyle = getComputedStyle(canvas);
const read = () => [targetStyle.width, targetStyle.height, canvasStyle.width, canvasStyle.height];
+ const readLogical = () => [targetStyle.inlineSize, targetStyle.blockSize, canvasStyle.inlineSize, canvasStyle.blockSize];
const before = read();
+ const logicalBefore = readLogical();
const geometry = [target.offsetWidth, target.offsetHeight, canvas.offsetWidth, canvas.offsetHeight];
- return { before, geometry, after: read() };
+ return { before, logicalBefore, geometry, after: read(), logicalAfter: readLogical() };
})()"#;
for args in [
vec![],
@@ -90,6 +92,14 @@ fn eval_computed_sizes_only_use_existing_geometry_with_or_without_css() -> Resul
clean_output(&output.stderr)
);
let value: serde_json::Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(
+ value["logicalBefore"], value["before"],
+ "cold axes: {args:?}"
+ );
+ assert_eq!(
+ value["logicalAfter"], value["after"],
+ "sampled axes: {args:?}"
+ );
assert_eq!(
value["before"],
serde_json::json!(["auto", "auto", "auto", "auto"]),