Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
Refactor intrinsic sizing through Taffy
ldm0bb5c9d0fd3e8
diff --git a/Cargo.lock b/Cargo.lockindex a007e48f8..0d5f508b9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4554,7 +4554,7 @@ dependencies = [[[package]]name = "taffy"version = "0.13.0"-source = "git+https://github.com/ldm0/taffy?rev=28dba60e85046442fe66fcca1ef976ca7953852e#28dba60e85046442fe66fcca1ef976ca7953852e"+source = "git+https://github.com/ldm0/taffy?rev=6bbdfc62fa5daaaca65af2340a6912ba52b0f203#6bbdfc62fa5daaaca65af2340a6912ba52b0f203"dependencies = ["arrayvec","serde",diff --git a/Cargo.toml b/Cargo.tomlindex bec6c58fa..355d52c70 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -90,7 +90,7 @@ stylo_atoms = { git = "https://github.com/ldm0/stylo", rev = "74cd014af14d84db1fstylo_dom = { git = "https://github.com/ldm0/stylo", rev = "74cd014af14d84db1fc8faed85086895012fc687" }stylo_static_prefs = { git = "https://github.com/ldm0/stylo", rev = "74cd014af14d84db1fc8faed85086895012fc687" }stylo_traits = { git = "https://github.com/ldm0/stylo", rev = "74cd014af14d84db1fc8faed85086895012fc687" }-taffy = { git = "https://github.com/ldm0/taffy", rev = "28dba60e85046442fe66fcca1ef976ca7953852e" }+taffy = { git = "https://github.com/ldm0/taffy", rev = "6bbdfc62fa5daaaca65af2340a6912ba52b0f203" }[workspace.lints.clippy]disallowed_methods = "deny"diff --git a/moli-layout/src/intrinsic.rs b/moli-layout/src/intrinsic.rsindex 88148aebe..7702ce8f7 100644--- a/moli-layout/src/intrinsic.rs+++ b/moli-layout/src/intrinsic.rs@@ -9,6 +9,7 @@ use std::{fmt::Debug, hash::Hash};use taffy::{AvailableSpace, LayoutInput, LayoutOutput, LayoutPartialTree, RequestedAxis, RunMode, Size,+ SizingPurpose,};use crate::{LayoutBoxId, LayoutDisplay, LayoutWorld};@@ -36,6 +37,7 @@ whereheight: inputs.available_space.height,},run_mode: RunMode::ComputeSize,+ sizing_purpose: SizingPurpose::IntrinsicContribution,axis: RequestedAxis::Horizontal,..inputs};diff --git a/moli-layout/src/table.rs b/moli-layout/src/table.rsindex 34525b74e..2c4b29caa 100644--- a/moli-layout/src/table.rs+++ b/moli-layout/src/table.rs@@ -15,8 +15,8 @@ use style::Atom;use taffy::{AvailableSpace, DetailedGridInfo, Dimension, Display, GridAutoFlow, Layout,LayoutGridContainer, LayoutInput, LayoutOutput, LayoutPartialTree, Line, NodeId, Point, Rect,- ResolveOrZero, RunMode, Size, SizingMode, Style, TraversePartialTree, TraverseTree,- compute_grid_layout, style_helpers,+ ResolveOrZero, RunMode, Size, SizingMode, SizingPurpose, Style, TraversePartialTree,+ TraverseTree, compute_grid_layout, style_helpers,};use crate::{LayoutBoxId, LayoutBoxKind, LayoutWorld, style::resolve_stylo_calc_value};@@ -507,6 +507,7 @@ whereheight: AvailableSpace::MaxContent,},sizing_mode: SizingMode::InherentSize,+ sizing_purpose: SizingPurpose::Layout,run_mode: RunMode::PerformLayout,axis: taffy::RequestedAxis::Both,vertical_margins_are_collapsible: Line::FALSE,diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rsindex 07787ed76..1ded945b3 100644--- a/moli-layout/src/taffy_tree.rs+++ b/moli-layout/src/taffy_tree.rs@@ -7,7 +7,7 @@ use taffy::{BlockFormattingContext, BoxSizing, CacheTree, Clear, Dimension, Display, FloatDirection,Layout, LayoutBlockContainer, LayoutFlexboxContainer, LayoutGridContainer, LayoutInput,LayoutOutput, LayoutPartialTree, Line, MaybeMath, MaybeResolve, NodeId, Point, ResolveOrZero,- RoundTree, RunMode, Size, SizingMode, Style, TraversePartialTree, TraverseTree,+ RoundTree, RunMode, Size, SizingMode, SizingPurpose, Style, TraversePartialTree, TraverseTree,compute_block_layout, compute_cached_layout, compute_flexbox_layout, compute_grid_layout,compute_hidden_layout, compute_leaf_layout, compute_root_layout, round_layout,};@@ -32,12 +32,6 @@ whereN: Copy + Debug + Eq + Hash,{for layout_box in &mut world.boxes {- let is_replaced = layout_box- .element_semantics- .as_ref()- .is_some_and(crate::LayoutElementSemantics::is_replaced);- layout_box.block_intrinsic_style =- block_intrinsic_style(&layout_box.style.taffy, is_replaced);layout_box.cache.clear();layout_box.unrounded_layout = Layout::with_order(0);layout_box.final_layout = Layout::with_order(0);@@ -49,7 +43,6 @@ whereworld.viewport_layout.children.clear();world.viewport_layout.cache.clear();- world.block_child_intrinsic_zero_min_width = false;world.viewport_layout.unrounded_layout = Layout::with_order(0);world.viewport_layout.final_layout = Layout::with_order(0);world.viewport_layout.style = Style {@@ -313,6 +306,7 @@ whereheight: AvailableSpace::MaxContent,},sizing_mode: SizingMode::InherentSize,+ sizing_purpose: SizingPurpose::Layout,run_mode: RunMode::PerformLayout,axis: taffy::RequestedAxis::Both,vertical_margins_are_collapsible: Line::FALSE,@@ -398,6 +392,7 @@ whereheight: AvailableSpace::MaxContent,},sizing_mode: SizingMode::InherentSize,+ sizing_purpose: SizingPurpose::Layout,run_mode: RunMode::PerformLayout,axis: taffy::RequestedAxis::Both,vertical_margins_are_collapsible: Line::FALSE,@@ -930,6 +925,7 @@ fn layout_inline_absolute_child<N>(parent_size: area.size.map(Some),available_space,sizing_mode: SizingMode::ContentSize,+ sizing_purpose: SizingPurpose::IntrinsicContribution,run_mode: RunMode::ComputeSize,axis: taffy::RequestedAxis::Horizontal,vertical_margins_are_collapsible: Line::FALSE,@@ -949,6 +945,7 @@ fn layout_inline_absolute_child<N>(parent_size: area.size.map(Some),available_space,sizing_mode: SizingMode::ContentSize,+ sizing_purpose: SizingPurpose::Layout,run_mode: RunMode::ComputeSize,axis: taffy::RequestedAxis::Both,vertical_margins_are_collapsible: Line::FALSE,@@ -966,6 +963,7 @@ fn layout_inline_absolute_child<N>(parent_size: area.size.map(Some),available_space,sizing_mode: SizingMode::ContentSize,+ sizing_purpose: SizingPurpose::Layout,run_mode: RunMode::PerformLayout,axis: taffy::RequestedAxis::Both,vertical_margins_are_collapsible: Line::FALSE,@@ -1177,7 +1175,7 @@ where};if self.is_viewport_taffy_node(node_id) {return compute_cached_layout(self, node_id, inputs, |world, node_id, inputs| {- world.compute_block_layout_with_cyclic_min_width(node_id, inputs, None)+ compute_block_layout(world, node_id, inputs, None)});}if self.should_hide(node_id, inputs) {@@ -1242,14 +1240,7 @@ where}fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_> {- let id = LayoutBoxId::from_taffy(child_node_id);- let child = &self.boxes[id.index()];- if self.block_child_intrinsic_zero_min_width {- if let Some(style) = child.block_intrinsic_style.as_ref() {- return style;- }- }- &child.style.taffy+ self.get_core_container_style(child_node_id)}fn compute_block_child_layout(@@ -1336,44 +1327,6 @@ impl<N> LayoutWorld<N>whereN: Copy + Debug + Eq + Hash,{- fn compute_block_layout_with_cyclic_min_width(- &mut self,- node_id: NodeId,- inputs: LayoutInput,- block_context: Option<&mut BlockContext<'_>>,- ) -> LayoutOutput {- let width_is_definite = {- let style = self.get_core_container_style(node_id);- let resolved_preferred = style- .size- .width- .maybe_resolve(inputs.parent_size.width, resolve_stylo_calc_value);- let resolved_min = style- .min_size- .width- .maybe_resolve(inputs.parent_size.width, resolve_stylo_calc_value);- let resolved_max = style- .max_size- .width- .maybe_resolve(inputs.parent_size.width, resolve_stylo_calc_value);- let min_max_determine_width =- matches!((resolved_min, resolved_max), (Some(min), Some(max)) if max <= min);- inputs- .known_dimensions- .maybe_apply_aspect_ratio(style.aspect_ratio)- .width- .or(resolved_preferred)- .is_some()- || min_max_determine_width- };- let previous = self.block_child_intrinsic_zero_min_width;- self.block_child_intrinsic_zero_min_width =- inputs.sizing_mode == SizingMode::InherentSize && !width_is_definite;- let output = compute_block_layout(self, node_id, inputs, block_context);- self.block_child_intrinsic_zero_min_width = previous;- output- }-fn should_hide(&self, node_id: NodeId, inputs: LayoutInput) -> bool {inputs.run_mode == RunMode::PerformHiddenLayout|| self.boxes[LayoutBoxId::from_taffy(node_id).index()]@@ -1423,7 +1376,7 @@ wherereturn compute_table_layout(self, id, inputs);}if display.is_table() {- return self.compute_block_layout_with_cyclic_min_width(node_id, inputs, block_context);+ return compute_block_layout(self, node_id, inputs, block_context);}match kind {@@ -1455,7 +1408,7 @@ where| LayoutBoxKind::AnonymousTableRowGroup| LayoutBoxKind::AnonymousTableRow| LayoutBoxKind::AnonymousTableCell => {- self.compute_block_layout_with_cyclic_min_width(node_id, inputs, block_context)+ compute_block_layout(self, node_id, inputs, block_context)}LayoutBoxKind::PrincipalInline| LayoutBoxKind::InlineContinuation@@ -1672,6 +1625,7 @@ wherelet child_inputs = LayoutInput {run_mode: inputs.run_mode,sizing_mode: SizingMode::InherentSize,+ sizing_purpose: inputs.sizing_purpose,axis: inputs.axis,known_dimensions: Size::NONE,definite_dimensions: Size::NONE,@@ -1695,7 +1649,8 @@ where// entire calc expression, including its absolute term (for example// `calc(0% + 30px)`). A final definite-width layout still supplies its// actual basis here.- let percentage_basis = inline_percentage_basis(available_space.width);+ let percentage_basis =+ inline_percentage_basis(available_space.width, inputs.sizing_purpose);let mut layout = context.unbroken.clone();let mut atomic = vec![None; context.objects.len()];let mut atomic_baseline_ascents = vec![None; context.objects.len()];@@ -1790,10 +1745,8 @@ wherelet display = self.boxes[parent.index()].style.display();display.is_flex_container() || display.is_grid_container()});- let is_intrinsic_contribution_probe = inputs.run_mode == RunMode::ComputeSize- && inputs.axis == taffy::RequestedAxis::Horizontal- && inputs.parent_size.width.is_none()- && known_dimensions.width.is_none();+ let is_intrinsic_contribution =+ inputs.sizing_purpose == SizingPurpose::IntrinsicContribution;let shrink_to_fit = !has_definite_width&& (is_floated// A content-based block parent can probe this IFC with a@@ -1801,7 +1754,7 @@ where// unknown. That is an intrinsic contribution, so clamp the// available width between the IFC's min/max-content sizes// instead of stretching to the probe constraint.- || is_intrinsic_contribution_probe+ || is_intrinsic_contribution// Flex/grid layout passes an auto inline size as unknown when// cross-axis stretch does not apply. In final layout that item// must return its fit-content width within the definite area.@@ -2246,47 +2199,44 @@ where}}-fn inline_percentage_basis(available: AvailableSpace) -> Option<f32> {- Some(available.into_option().unwrap_or(0.0))-}--fn block_intrinsic_style(style: &Style<Atom>, is_replaced: bool) -> Option<Style<Atom>> {- if is_replaced || !style.min_size.width.into_raw().is_calc() {- return None;- }-- // When this box's containing block depends on its contribution, CSS- // Sizing resolves a cyclic percentage in min-width against zero. Retain a- // separate projection for that probe so final layout still uses the- // original expression against the now-known containing-block width.- let width = style- .min_size- .width- .maybe_resolve(Some(0.0), resolve_stylo_calc_value)?;- let mut projected = style.clone();- projected.min_size.width = Dimension::length(width);- Some(projected)+fn inline_percentage_basis(+ available: AvailableSpace,+ sizing_purpose: SizingPurpose,+) -> Option<f32> {+ available+ .into_option()+ .or_else(|| (sizing_purpose == SizingPurpose::IntrinsicContribution).then_some(0.0))}#[cfg(test)]mod tests {use super::inline_percentage_basis;- use taffy::AvailableSpace;+ use taffy::{AvailableSpace, SizingPurpose};#[test]fn intrinsic_inline_percentages_use_a_zero_basis() {assert_eq!(- inline_percentage_basis(AvailableSpace::MinContent),+ inline_percentage_basis(+ AvailableSpace::MinContent,+ SizingPurpose::IntrinsicContribution,+ ),Some(0.0));assert_eq!(- inline_percentage_basis(AvailableSpace::MaxContent),+ inline_percentage_basis(+ AvailableSpace::MaxContent,+ SizingPurpose::IntrinsicContribution,+ ),Some(0.0));assert_eq!(- inline_percentage_basis(AvailableSpace::Definite(240.0)),+ inline_percentage_basis(AvailableSpace::Definite(240.0), SizingPurpose::Layout),Some(240.0));+ assert_eq!(+ inline_percentage_basis(AvailableSpace::MaxContent, SizingPurpose::Layout),+ None+ );}}diff --git a/moli-layout/src/world.rs b/moli-layout/src/world.rsindex 47cd0b725..af4b92138 100644--- a/moli-layout/src/world.rs+++ b/moli-layout/src/world.rs@@ -211,9 +211,6 @@ pub struct LayoutBox<N> {/// Static position emitted by the shared IFC's out-of-flow placeholder.pub(crate) inline_static_position: Option<InlineStaticPosition>,pub(crate) style: ResolvedLayoutStyle,- /// Optional style projection used only while this box contributes to an- /// intrinsically sized block containing block.- pub(crate) block_intrinsic_style: Option<Style<Atom>>,pub(crate) text: Option<Arc<str>>,pub(crate) text_selection: Option<crate::LayoutTextSelection>,/// Shared text/inline layout owned by this formatting-context root.@@ -350,7 +347,6 @@ wherepub(crate) display_contents_mapping: HashMap<N, Vec<LayoutBoxId>>,pub(crate) root: LayoutBoxId,pub(crate) viewport_layout: ViewportLayoutState,- pub(crate) block_child_intrinsic_zero_min_width: bool,}impl<N> LayoutWorld<N>@@ -364,7 +360,6 @@ wheredisplay_contents_mapping: HashMap::new(),root: LayoutBoxId::from_index(0),viewport_layout: ViewportLayoutState::default(),- block_child_intrinsic_zero_min_width: false,}}@@ -684,7 +679,6 @@ wherepositioned_containing_block: None,inline_static_position: None,style,- block_intrinsic_style: None,text,text_selection: None,inline_layout: None,diff --git a/moli-renderer-v8/src/runtime/phase_one/mod.rs b/moli-renderer-v8/src/runtime/phase_one/mod.rsindex 2ca9e5d87..6ce5aaf83 100644--- a/moli-renderer-v8/src/runtime/phase_one/mod.rs+++ b/moli-renderer-v8/src/runtime/phase_one/mod.rs@@ -838,6 +838,78 @@ html,body{margin:0;padding:0}}));}+ #[test]+ fn layout_renderer_resolves_cyclic_preferred_width_after_parent_contribution() {+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .expect("current-thread runtime should build");++ runtime.block_on(tokio::task::LocalSet::new().run_until(async move {+ let mut page_vm = parse_phase_one_html_into_page_vm_for_test(+ r#"<!doctype html><html><head><style>+html,body{margin:0;padding:0}+.host{display:flow-root;width:0}.outer{float:left;width:auto;height:30px}+.inner{height:20px}.raw{width:50%}.calc{width:calc(40px + 0%)}+.atom{display:inline-block;width:60px;height:20px}+#raw-outer{background:rgb(151,152,153)}#raw-inner{background:rgb(161,162,163)}+#calc-outer{background:rgb(171,172,173)}#calc-inner{background:rgb(181,182,183)}+</style></head><body>+<div class=host><div id=raw-outer class=outer><div id=raw-inner class="inner raw"><span class=atom></span></div></div></div>+<div class=host><div id=calc-outer class=outer><div id=calc-inner class="inner calc"><span class=atom></span></div></div></div>+</body></html>"#,+ )+ .await;+ page_vm.vm_mut().sync_live_document_style_sources();++ let snapshot = page_vm+ .vm_mut()+ .screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0))+ .expect("cyclic preferred-width layout should succeed")+ .expect("fixture should have a document element");+ for (color, expected) in [+ (+ moli_layout::PaintColor::new(+ 151.0 / 255.0,+ 152.0 / 255.0,+ 153.0 / 255.0,+ 1.0,+ ),+ moli_layout::PaintRect::new(0.0, 0.0, 60.0, 30.0),+ ),+ (+ moli_layout::PaintColor::new(+ 161.0 / 255.0,+ 162.0 / 255.0,+ 163.0 / 255.0,+ 1.0,+ ),+ moli_layout::PaintRect::new(0.0, 0.0, 30.0, 20.0),+ ),+ (+ moli_layout::PaintColor::new(+ 171.0 / 255.0,+ 172.0 / 255.0,+ 173.0 / 255.0,+ 1.0,+ ),+ moli_layout::PaintRect::new(0.0, 30.0, 60.0, 30.0),+ ),+ (+ moli_layout::PaintColor::new(+ 181.0 / 255.0,+ 182.0 / 255.0,+ 183.0 / 255.0,+ 1.0,+ ),+ moli_layout::PaintRect::new(0.0, 30.0, 40.0, 20.0),+ ),+ ] {+ assert_paint_rect(solid_paint_rect(&snapshot, color), expected);+ }+ }));+ }+#[test]fn layout_renderer_projects_current_blitz_taffy_parity_from_stylo() {let runtime = tokio::runtime::Builder::new_current_thread()