Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(layout): omit whitespace-only flex and grid items

ldm007f8e8533a8a
diff --git a/moli-layout/src/builder.rs b/moli-layout/src/builder.rs
index cd263e2b5..2145844ef 100644
--- a/moli-layout/src/builder.rs
+++ b/moli-layout/src/builder.rs
@@ -52,6 +52,35 @@ where
viewport_body_candidate: Option<ViewportBodyCandidate<S::NodeId>>,
}
+/// Selects both the generated wrapper and its whitespace-suppression rule.
+/// Mixed block/inline flow follows `white-space-collapse`; Flex and Grid omit
+/// an all-CSS-whitespace text sequence before generating an anonymous item,
+/// even when the inherited whitespace mode preserves those characters.
+#[derive(Clone, Copy)]
+enum AnonymousInlineRunRole {
+ MixedFlow,
+ FlexItem,
+ GridItem,
+}
+
+impl AnonymousInlineRunRole {
+ fn box_kind(self) -> LayoutBoxKind {
+ match self {
+ Self::MixedFlow => LayoutBoxKind::AnonymousBlock,
+ Self::FlexItem => LayoutBoxKind::AnonymousFlexItem,
+ Self::GridItem => LayoutBoxKind::AnonymousGridItem,
+ }
+ }
+
+ fn reason(self) -> LayoutAnonymousReason {
+ match self {
+ Self::MixedFlow => LayoutAnonymousReason::MixedFlowInlineRun,
+ Self::FlexItem => LayoutAnonymousReason::FlexTextRun,
+ Self::GridItem => LayoutAnonymousReason::GridTextRun,
+ }
+ }
+}
+
impl<'a, S, R> BoxBuilder<'a, S, R>
where
S: LayoutSource,
@@ -561,7 +590,7 @@ where
owner,
parent_style,
children,
- LayoutBoxKind::AnonymousFlexItem,
+ AnonymousInlineRunRole::FlexItem,
)?
} else if parent_style.display().is_grid_container() {
self.normalize_item_children(
@@ -569,7 +598,7 @@ where
owner,
parent_style,
children,
- LayoutBoxKind::AnonymousGridItem,
+ AnonymousInlineRunRole::GridItem,
)?
} else {
self.normalize_flow_children(world, owner, parent_style, children)?
@@ -737,7 +766,7 @@ where
world,
owner,
parent_style,
- LayoutBoxKind::AnonymousBlock,
+ AnonymousInlineRunRole::MixedFlow,
&mut output,
&mut inline_run,
)?;
@@ -754,7 +783,7 @@ where
world,
owner,
parent_style,
- LayoutBoxKind::AnonymousBlock,
+ AnonymousInlineRunRole::MixedFlow,
&mut output,
&mut inline_run,
)?;
@@ -765,7 +794,7 @@ where
world,
owner,
parent_style,
- LayoutBoxKind::AnonymousBlock,
+ AnonymousInlineRunRole::MixedFlow,
&mut output,
&mut inline_run,
)?;
@@ -778,7 +807,7 @@ where
owner: S::NodeId,
parent_style: &ResolvedLayoutStyle,
children: Vec<LayoutBoxId>,
- anonymous_kind: LayoutBoxKind,
+ run_role: AnonymousInlineRunRole,
) -> Result<Vec<LayoutBoxId>, LayoutError> {
let mut output = Vec::new();
let mut text_run = Vec::new();
@@ -794,7 +823,7 @@ where
world,
owner,
parent_style,
- anonymous_kind,
+ run_role,
&mut output,
&mut text_run,
)?;
@@ -809,7 +838,7 @@ where
world,
owner,
parent_style,
- anonymous_kind,
+ run_role,
&mut output,
&mut text_run,
)?;
@@ -821,7 +850,7 @@ where
world: &mut LayoutWorld<S::NodeId>,
owner: S::NodeId,
parent_style: &ResolvedLayoutStyle,
- anonymous_kind: LayoutBoxKind,
+ run_role: AnonymousInlineRunRole,
output: &mut Vec<LayoutBoxId>,
run: &mut Vec<LayoutBoxId>,
) -> Result<(), LayoutError> {
@@ -830,33 +859,14 @@ where
}
if run
.iter()
- .all(|id| self.is_ignorable_whitespace_text(world, *id))
+ .all(|id| self.is_ignorable_text_for_anonymous_run(world, *id, run_role))
{
run.clear();
return Ok(());
}
- let (reason, display) = match anonymous_kind {
- LayoutBoxKind::AnonymousBlock => (
- LayoutAnonymousReason::MixedFlowInlineRun,
- LayoutDisplay::Block,
- ),
- LayoutBoxKind::AnonymousFlexItem => {
- (LayoutAnonymousReason::FlexTextRun, LayoutDisplay::Block)
- }
- LayoutBoxKind::AnonymousGridItem => {
- (LayoutAnonymousReason::GridTextRun, LayoutDisplay::Block)
- }
- _ => {
- return Err(LayoutError::source_contract(
- self.source.label(owner),
- format!(
- "box kind {} cannot be constructed as an anonymous inline-run wrapper",
- anonymous_kind.debug_name()
- ),
- ));
- }
- };
- let style = self.styles.anonymous_style(owner, parent_style, display)?;
+ let style = self
+ .styles
+ .anonymous_style(owner, parent_style, LayoutDisplay::Block)?;
let mut anonymous = LayoutWorld::new_box(
None,
Some(owner),
@@ -864,8 +874,8 @@ where
format!("anonymous({})", self.source.label(owner)),
Some(self.source.label(owner)),
None,
- Some(reason),
- anonymous_kind,
+ Some(run_role.reason()),
+ run_role.box_kind(),
style,
None,
);
@@ -1205,6 +1215,15 @@ where
&self,
world: &LayoutWorld<S::NodeId>,
id: LayoutBoxId,
+ ) -> bool {
+ self.is_ignorable_text_for_anonymous_run(world, id, AnonymousInlineRunRole::MixedFlow)
+ }
+
+ fn is_ignorable_text_for_anonymous_run(
+ &self,
+ world: &LayoutWorld<S::NodeId>,
+ id: LayoutBoxId,
+ run_role: AnonymousInlineRunRole,
) -> bool {
world.box_by_id(id).is_some_and(|layout_box| {
layout_box.kind.is_text()
@@ -1212,7 +1231,11 @@ where
.capability_diagnostics
.contains(&LayoutCapabilityDiagnostic::GeneratedContentUnsupported)
&& layout_box.text.as_deref().is_none_or(|text| {
- whitespace_text_is_ignorable(text, layout_box.style.white_space_collapse())
+ text_is_ignorable_in_anonymous_run(
+ text,
+ layout_box.style.white_space_collapse(),
+ run_role,
+ )
})
})
}
@@ -1343,10 +1366,7 @@ fn whitespace_text_is_ignorable(text: &str, mode: InlineWhiteSpaceCollapse) -> b
if text.is_empty() {
return true;
}
- if !text
- .chars()
- .all(|character| matches!(character, ' ' | '\t' | '\n' | '\r' | '\u{000C}'))
- {
+ if !text_contains_only_css_whitespace(text) {
return false;
}
match mode {
@@ -1358,6 +1378,24 @@ fn whitespace_text_is_ignorable(text: &str, mode: InlineWhiteSpaceCollapse) -> b
}
}
+fn text_contains_only_css_whitespace(text: &str) -> bool {
+ text.chars()
+ .all(|character| matches!(character, ' ' | '\t' | '\n' | '\r' | '\u{000C}'))
+}
+
+fn text_is_ignorable_in_anonymous_run(
+ text: &str,
+ mode: InlineWhiteSpaceCollapse,
+ run_role: AnonymousInlineRunRole,
+) -> bool {
+ match run_role {
+ AnonymousInlineRunRole::MixedFlow => whitespace_text_is_ignorable(text, mode),
+ AnonymousInlineRunRole::FlexItem | AnonymousInlineRunRole::GridItem => {
+ text_contains_only_css_whitespace(text)
+ }
+ }
+}
+
fn principal_kind(
semantics: &LayoutElementSemantics,
style: &ResolvedLayoutStyle,
@@ -1456,7 +1494,10 @@ fn push_diagnostic(
#[cfg(test)]
mod tests {
- use super::{InlineWhiteSpaceCollapse, whitespace_text_is_ignorable};
+ use super::{
+ AnonymousInlineRunRole, InlineWhiteSpaceCollapse, text_contains_only_css_whitespace,
+ text_is_ignorable_in_anonymous_run, whitespace_text_is_ignorable,
+ };
#[test]
fn only_collapsible_whitespace_is_ignorable_during_box_construction() {
@@ -1485,4 +1526,37 @@ mod tests {
InlineWhiteSpaceCollapse::Collapse,
));
}
+
+ #[test]
+ fn flex_and_grid_item_runs_ignore_css_whitespace_independently_of_collapse_mode() {
+ assert!(text_contains_only_css_whitespace(" \t\n\r\u{000C}"));
+ assert!(!text_contains_only_css_whitespace("\u{00a0}"));
+
+ for role in [
+ AnonymousInlineRunRole::FlexItem,
+ AnonymousInlineRunRole::GridItem,
+ ] {
+ assert!(text_is_ignorable_in_anonymous_run(
+ " \t\n\r\u{000C}",
+ InlineWhiteSpaceCollapse::Preserve,
+ role,
+ ));
+ assert!(!text_is_ignorable_in_anonymous_run(
+ "\u{00a0}",
+ InlineWhiteSpaceCollapse::Collapse,
+ role,
+ ));
+ assert!(!text_is_ignorable_in_anonymous_run(
+ " text ",
+ InlineWhiteSpaceCollapse::Preserve,
+ role,
+ ));
+ }
+
+ assert!(!text_is_ignorable_in_anonymous_run(
+ " \n",
+ InlineWhiteSpaceCollapse::Preserve,
+ AnonymousInlineRunRole::MixedFlow,
+ ));
+ }
}
diff --git a/moli-layout/tests/box_builder_contract.rs b/moli-layout/tests/box_builder_contract.rs
index 8c5d9b382..ca152e0b1 100644
--- a/moli-layout/tests/box_builder_contract.rs
+++ b/moli-layout/tests/box_builder_contract.rs
@@ -584,6 +584,43 @@ fn grid_direct_text_uses_one_anonymous_grid_item_and_keeps_text_boundaries() {
assert!(root.capability_diagnostics().is_empty());
}
+#[test]
+fn flex_and_grid_distinguish_css_whitespace_from_non_breaking_space_items() {
+ let cases = [
+ (LayoutDisplay::Flex, LayoutBoxKind::AnonymousFlexItem),
+ (LayoutDisplay::Grid, LayoutBoxKind::AnonymousGridItem),
+ ];
+
+ for (container_display, anonymous_kind) in cases {
+ let source = TestSource {
+ root: 0,
+ nodes: vec![
+ TestNode::element("root", vec![1, 2, 3]),
+ TestNode::text("css-whitespace", " \t\n"),
+ TestNode::element("item", Vec::new()),
+ TestNode::text("non-breaking-space", "\u{00a0}"),
+ ],
+ };
+ let mut styles = TestStyles::default();
+ styles.primary.insert(0, style(container_display));
+ styles.primary.insert(2, style(LayoutDisplay::Block));
+
+ let world = build_layout_world(&source, &mut styles).unwrap();
+ let root = world.box_by_id(world.root()).unwrap();
+ assert_eq!(root.children().len(), 2, "display={container_display:?}");
+ assert_eq!(world.source_box(1), None, "display={container_display:?}");
+ assert_eq!(
+ world.box_by_id(root.children()[1]).unwrap().kind(),
+ anonymous_kind,
+ "display={container_display:?}",
+ );
+ assert!(
+ world.source_box(3).is_some(),
+ "display={container_display:?}"
+ );
+ }
+}
+
#[test]
fn contents_text_is_an_item_of_the_flattened_flex_or_grid_container() {
let cases = [
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/grid_item_box_generation.rs b/moli-renderer-v8/src/runtime/page_vm/tests/grid_item_box_generation.rs
new file mode 100644
index 000000000..ed0d1b9d5
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/grid_item_box_generation.rs
@@ -0,0 +1,56 @@
+use super::*;
+
+#[tokio::test(flavor = "current_thread")]
+async fn screenshot_omits_whitespace_only_flex_and_grid_items_even_when_preserved() {
+ 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/grid-whitespace-box-generation.html")?,
+ );
+ page_vm.vm_mut().eval(
+ r#"
+document.head.innerHTML = `<style>
+html,body{margin:0}
+.probe{white-space:pre;vertical-align:top}
+.grid{display:inline-grid;grid-auto-flow:column;grid-auto-columns:20px;grid-auto-rows:20px}
+.flex{display:inline-flex}
+.item{width:20px;height:20px}
+</style>`;
+document.body.innerHTML = `
+<div class="probe grid" id=grid-whitespace> \t\n <div class=item></div>\r\f </div>
+<div class="probe grid" id=grid-nbsp>&nbsp;<div class=item></div></div>
+<div class="probe grid" id=grid-text>text<div class=item></div></div>
+<div class="probe flex" id=flex-whitespace> \t\n <div class=item></div>\r\f </div>
+<div class="probe flex" id=flex-text>text<div class=item></div></div>`;
+'installed'
+"#,
+ )?;
+ page_vm.vm_mut().sync_live_document_style_sources();
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(moli_layout::PaintViewport::new(400, 200, 1.0))?
+ .expect("Grid whitespace box-generation screenshot layout");
+
+ let geometry = page_vm.vm_mut().eval(
+ r#"JSON.stringify(Object.fromEntries(['grid-whitespace','grid-nbsp','grid-text','flex-whitespace','flex-text'].map(id=>{const host=document.getElementById(id),item=host.querySelector('.item'),hostRect=host.getBoundingClientRect(),itemRect=item.getBoundingClientRect(),itemX=itemRect.x-hostRect.x;if(id.startsWith('grid-'))return [id,{width:hostRect.width,itemX,columns:getComputedStyle(host).gridTemplateColumns}];if(id==='flex-whitespace')return [id,{width:hostRect.width,itemX}];return [id,{anonymousItem:itemX>0&&hostRect.width>itemRect.width}]})))"#,
+ )?;
+ let geometry: serde_json::Value = serde_json::from_str(&geometry)?;
+ assert_eq!(
+ geometry,
+ serde_json::json!({
+ "grid-whitespace": {"width": 20, "itemX": 0, "columns": "20px"},
+ "grid-nbsp": {"width": 40, "itemX": 20, "columns": "20px 20px"},
+ "grid-text": {"width": 40, "itemX": 20, "columns": "20px 20px"},
+ "flex-whitespace": {"width": 20, "itemX": 0},
+ "flex-text": {"anonymousItem": true},
+ }),
+ "only CSS whitespace sequences must disappear before Grid item generation; non-breaking spaces and ordinary text must retain their anonymous item",
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("Grid whitespace box-generation fixture should run");
+}
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 b92a11843..a9cf659a9 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
@@ -124,6 +124,7 @@ mod element_toggle_event;
mod fetch_xhr;
mod file_entry_file_callback;
mod file_system_directory_reader;
+mod grid_item_box_generation;
mod grid_resolved_track_values;
mod hash_change_delivery;
mod history_traversal;