Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
Fix inline-block baseline propagation
ldm063eb3d6bc284
diff --git a/Cargo.lock b/Cargo.lockindex dd2aef0cb..52bf12e66 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=6bbdfc62fa5daaaca65af2340a6912ba52b0f203#6bbdfc62fa5daaaca65af2340a6912ba52b0f203"+source = "git+https://github.com/ldm0/taffy?rev=61ce16ba2527532cf7ae393c03d3da4185111a98#61ce16ba2527532cf7ae393c03d3da4185111a98"dependencies = ["arrayvec","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 355d52c70..a499e093b 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 = "6bbdfc62fa5daaaca65af2340a6912ba52b0f203" }+taffy = { git = "https://github.com/ldm0/taffy", rev = "61ce16ba2527532cf7ae393c03d3da4185111a98" }[workspace.lints.clippy]disallowed_methods = "deny"diff --git a/moli-layout/src/inline.rs b/moli-layout/src/inline.rsindex be704e990..e7b65a361 100644--- a/moli-layout/src/inline.rs+++ b/moli-layout/src/inline.rs@@ -113,7 +113,6 @@ pub(crate) struct InlineObject {#[derive(Clone, Debug)]pub(crate) struct InlineFormattingContext {- pub(crate) text: String,pub(crate) unbroken: Layout<TextBrush>,pub(crate) laid_out: Option<Layout<TextBrush>>,pub(crate) text_units: Vec<InlineTextUnit>,@@ -132,10 +131,6 @@ pub(crate) struct InlineFormattingContext {/// non-baseline alignment is relative to that parent inline box, not/// necessarily to the IFC owner.pub(crate) object_alignment_parent_struts: Vec<Option<InlineStrutMetrics>>,- /// Baseline of the last in-flow line, relative to the border-box block- /// start. Atomic inline parents use this instead of synthesizing every- /// inline-block baseline from its margin-box end.- pub(crate) last_baseline: Option<f32>,pub(crate) line_placements: Vec<InlineLinePlacement>,pub(crate) fragments: InlineFragments,}@@ -160,6 +155,10 @@ pub(crate) struct InlineLinePlacement {pub(crate) line_index: usize,pub(crate) rect: PaintRect,pub(crate) baseline: f32,+ /// CSS phantom line boxes retain positions for their inline descendants,+ /// but do not contribute height, baselines, or block margin-collapse+ /// barriers.+ pub(crate) phantom: bool,content_offset: f32,item_offsets: Vec<f32>,glyph_offsets: Vec<InlineGlyphOffset>,@@ -521,6 +520,7 @@ pub(crate) fn build_inline_line_placements(context: &InlineFormattingContext,layout: &Layout<TextBrush>,atomic_baseline_ascents: &[Option<f32>],+ structural_edge_contributions: &[bool],) -> (Vec<InlineLinePlacement>, f32) {let mut placements = Vec::with_capacity(layout.lines().len());let mut preceding_adjustment = 0.0;@@ -577,6 +577,7 @@ pub(crate) fn build_inline_line_placements(// style but no glyph geometry and is not in-flow line// content by itself.contributes_to_line: paint && style_index.is_some(),+ creates_line: paint && style_index.is_some(),alignment_parent_strut: None,glyph_key: if paint {style_index.map(|index| (run.index(), index))@@ -587,9 +588,10 @@ pub(crate) fn build_inline_line_placements(}PositionedLayoutItem::InlineBox(positioned) => {let object = context.object(positioned.id);+ let object_index = usize::try_from(positioned.id).ok();let internal_baseline_ascent = object.filter(|object| object.role == InlineObjectRole::Atomic)- .and_then(|_| usize::try_from(positioned.id).ok())+ .and(object_index).and_then(|index| atomic_baseline_ascents.get(index).copied().flatten());let is_atomic =object.is_some_and(|object| object.role == InlineObjectRole::Atomic);@@ -608,6 +610,14 @@ pub(crate) fn build_inline_line_placements(.unwrap_or_default(),contributes_to_line: object.is_some_and(|object| object.role == InlineObjectRole::Atomic),+ creates_line: object.is_some_and(|object| match object.role {+ InlineObjectRole::Atomic => true,+ InlineObjectRole::StartEdge | InlineObjectRole::EndEdge => object_index+ .and_then(|index| structural_edge_contributions.get(index))+ .copied()+ .unwrap_or(false),+ InlineObjectRole::Float | InlineObjectRole::OutOfFlow => false,+ }),alignment_parent_strut: context.object_alignment_parent_strut(positioned.id),glyph_key: None,@@ -615,15 +625,12 @@ pub(crate) fn build_inline_line_placements(}}).collect::<Vec<_>>();- // Every CSS line starts with the IFC owner's zero-width font strut.+ let phantom = !geometries.iter().any(|geometry| geometry.creates_line);+ // Every non-phantom CSS line starts with the IFC owner's zero-width font strut.// Reconstruct it explicitly whenever this sidecar owns in-flow// vertical geometry. Float and out-of-flow placeholders do not create// a normal-flow line contribution and retain Parley's raw position.- let reconstructs_parent_strut = context.parent_strut.is_some()- && geometries.iter().any(|geometry| {- geometry.contributes_to_line- || geometry.vertical_align.kind != LayoutInlineAlignment::Baseline- });+ let reconstructs_parent_strut = !phantom && context.parent_strut.is_some();let root_parent_x_height = context.parent_strut.filter(|_| reconstructs_parent_strut)@@ -733,15 +740,19 @@ pub(crate) fn build_inline_line_placements(// First position baseline-, text-edge-, and middle-aligned content.// Top/bottom depend on the resulting aligned subtree and are resolved// in the second pass, matching the ordering used by browser IFCs.- let (mut min_y, mut max_y) = context- .parent_strut- .filter(|_| reconstructs_parent_strut)- .map_or((raw_top, raw_bottom), |strut| {- (- parent_baseline - strut.line_ascent,- parent_baseline + strut.line_descent,- )- });+ let (mut min_y, mut max_y) = if phantom {+ (raw_top, raw_top)+ } else {+ context+ .parent_strut+ .filter(|_| reconstructs_parent_strut)+ .map_or((raw_top, raw_bottom), |strut| {+ (+ parent_baseline - strut.line_ascent,+ parent_baseline + strut.line_descent,+ )+ })+ };let mut item_offsets = base_offsets;for (item_index, geometry) in geometries.iter().enumerate() {if matches!(@@ -817,6 +828,7 @@ pub(crate) fn build_inline_line_placements(line_height,),baseline: parent_baseline + line_content_offset,+ phantom,content_offset: parley_baseline_adjustment+ parent_baseline_adjustment+ line_content_offset,@@ -838,7 +850,12 @@ struct InlineItemVerticalGeometry {uses_internal_atomic_baseline: bool,intrinsic_baseline_adjustment: f32,vertical_align: InlineVerticalAlign,+ /// Whether this item supplies block-axis geometry to the line.contributes_to_line: bool,+ /// Whether this item prevents the line from being a CSS phantom line box.+ /// Structural inline edges with non-zero inline-axis decorations create a+ /// line without themselves affecting its block-axis height.+ creates_line: bool,alignment_parent_strut: Option<InlineStrutMetrics>,glyph_key: Option<(usize, usize)>,}@@ -1078,7 +1095,6 @@ impl InlineBuildInput {.map(|(_, object, _)| object).collect();InlineFormattingContext {- text: self.text,unbroken: layout,laid_out: None,text_units: self.units,@@ -1088,7 +1104,6 @@ impl InlineBuildInput {font_metrics,parent_strut,object_alignment_parent_struts,- last_baseline: None,line_placements: Vec::new(),fragments: InlineFragments::default(),}diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rsindex 1ded945b3..98ba744f9 100644--- a/moli-layout/src/taffy_tree.rs+++ b/moli-layout/src/taffy_tree.rs@@ -1471,6 +1471,7 @@ wheresize,content_size: size,first_baselines: Point::NONE,+ last_baselines: Point::NONE,top_margin: taffy::tree::CollapsibleMarginSet::ZERO,bottom_margin: taffy::tree::CollapsibleMarginSet::ZERO,margins_can_collapse_through: false,@@ -1531,7 +1532,6 @@ where.inline_layout.take().unwrap_or_else(empty_inline_context);- inline_context.last_baseline = None;let mut measurement = None;let mut output = compute_leaf_layout(leaf_inputs,@@ -1587,9 +1587,12 @@ whereoutput.first_baselines.y = measurement.first_baseline.map(|baseline| baseline + padding.top + border.top);- inline_context.last_baseline = measurement+ output.last_baselines.y = measurement.last_baseline.map(|baseline| baseline + padding.top + border.top);+ if measurement.line_placements.iter().any(|line| !line.phantom) {+ output.margins_can_collapse_through = false;+ }if inputs.run_mode == RunMode::PerformLayout {self.position_inline_objects(&inline_context,@@ -1654,6 +1657,7 @@ wherelet mut layout = context.unbroken.clone();let mut atomic = vec![None; context.objects.len()];let mut atomic_baseline_ascents = vec![None; context.objects.len()];+ let mut structural_edge_contributions = vec![false; context.objects.len()];let mut floats = Vec::new();for (inline_box, object) in layout.inline_boxes_mut().iter_mut().zip(&context.objects) {@@ -1676,7 +1680,7 @@ wherelet object_index = usize::try_from(inline_box.id).expect("Parley returned an inline object id outside usize");atomic_baseline_ascents[object_index] = self- .atomic_inline_baseline(object.box_id)+ .atomic_inline_baseline(object.box_id, child_output).map(|baseline| margins.top.max(0.0) + baseline);atomic[object_index] = Some(AtomicMeasurement {output: child_output,@@ -1708,13 +1712,17 @@ wherelet logical_start = object.role == InlineObjectRole::StartEdge;let physical_left =logical_start == (child_style.direction() == InlineDirection::Ltr);- inline_box.width = if physical_left {- margins.left + padding.left + border.left+ let (margin, padding, border) = if physical_left {+ (margins.left, padding.left, border.left)} else {- margins.right + padding.right + border.right- }- .max(0.0);+ (margins.right, padding.right, border.right)+ };+ inline_box.width = (margin + padding + border).max(0.0);inline_box.height = 0.0;+ let object_index = usize::try_from(inline_box.id)+ .expect("Parley returned an inline object id outside usize");+ structural_edge_contributions[object_index] =+ margin != 0.0 || padding != 0.0 || border != 0.0;}}}@@ -1924,21 +1932,26 @@ where},);- let (line_placements, line_expansion) =- build_inline_line_placements(context, &layout, &atomic_baseline_ascents);+ let (line_placements, line_expansion) = build_inline_line_placements(+ context,+ &layout,+ &atomic_baseline_ascents,+ &structural_edge_contributions,+ );let mut height = layout.height() + line_expansion;if let Some(float_height) = float_height {height = height.max(float_height);}- if ends_with_forced_break(context)- && let Some(last) = layout.lines().last()- && last.items().next().is_none()- {- height = (height - last.metrics().line_height).max(0.0);- }let alignment_block_size = height.max(alignment_float_height);- let first_baseline = line_placements.first().map(|line| line.baseline);- let last_baseline = line_placements.last().map(|line| line.baseline);+ let first_baseline = line_placements+ .iter()+ .find(|line| !line.phantom)+ .map(|line| line.baseline);+ let last_baseline = line_placements+ .iter()+ .rev()+ .find(|line| !line.phantom)+ .map(|line| line.baseline);let fragments = build_inline_fragments(context, &layout, &line_placements);InlineMeasurement {size: Size {@@ -1957,7 +1970,7 @@ where}}- fn atomic_inline_baseline(&self, id: LayoutBoxId) -> Option<f32> {+ fn atomic_inline_baseline(&self, id: LayoutBoxId, output: LayoutOutput) -> Option<f32> {let layout_box = &self.boxes[id.index()];if !matches!(layout_box.style.display(),@@ -1967,7 +1980,7 @@ where{return None;}- layout_box.inline_layout.as_ref()?.last_baseline+ output.last_baselines.y}fn break_inline_lines_with_floats(@@ -2330,7 +2343,6 @@ fn single_subject_block_alignment_offset(alignment: Option<AlignContent>, free_sfn empty_inline_context() -> InlineFormattingContext {InlineFormattingContext {- text: String::new(),unbroken: parley::Layout::default(),laid_out: None,text_units: Vec::new(),@@ -2340,21 +2352,11 @@ fn empty_inline_context() -> InlineFormattingContext {font_metrics: Vec::new(),parent_strut: None,object_alignment_parent_struts: Vec::new(),- last_baseline: None,line_placements: Vec::new(),fragments: InlineFragments::default(),}}-fn ends_with_forced_break(context: &InlineFormattingContext) -> bool {- context- .text_units- .iter()- .rev()- .find(|unit| !unit.control)- .is_some_and(|unit| &context.text[unit.output_range.clone()] == "\n")-}-fn measure_text(text: &str,font_size: f32,diff --git a/moli-layout/tests/phase4_layout_contract.rs b/moli-layout/tests/phase4_layout_contract.rsindex 754d9e42e..758f5b930 100644--- a/moli-layout/tests/phase4_layout_contract.rs+++ b/moli-layout/tests/phase4_layout_contract.rs@@ -11,7 +11,7 @@ use moli_layout::{build_screenshot_snapshot,};use style::Atom;-use taffy::{Clear, Dimension, Float, Overflow, Point, Rect, Size, Style};+use taffy::{BoxSizing, Clear, Dimension, Float, Overflow, Point, Rect, Size, Style};const RED: PaintColor = PaintColor::new(0.9, 0.1, 0.1, 1.0);const GREEN: PaintColor = PaintColor::new(0.1, 0.7, 0.2, 1.0);@@ -1042,6 +1042,175 @@ fn inline_blocks_use_their_internal_last_line_baseline_and_overflow_fallback() {assert_close(rect(&fallback, BLUE).y, 19.0);}+#[test]+fn inline_block_propagates_scroll_block_end_baseline_through_block_children() {+ let render_variant = |inner_display, inner_overflow, margin_bottom| {+ let source = Source(vec![+ Node::element(+ "root",+ "div",+ LayoutElementCategory::Generic,+ None,+ vec![1, 4],+ ),+ Node::element(+ "outer",+ "span",+ LayoutElementCategory::Generic,+ None,+ vec![2],+ ),+ Node::element(+ "inner",+ "div",+ LayoutElementCategory::Generic,+ None,+ vec![3],+ ),+ Node::text("inner-text", "X"),+ Node::element(+ "tail",+ "span",+ LayoutElementCategory::Generic,+ None,+ Vec::new(),+ ),+ ]);+ let mut styles = Styles::default();+ styles.primary.insert(+ 0,+ style(LayoutDisplay::Block, PaintColor::TRANSPARENT)+ .tap_taffy(|taffy| {+ taffy.size.width = Dimension::length(200.0);+ })+ .with_text_metrics(16.0, 20.0),+ );+ styles.primary.insert(+ 1,+ style(LayoutDisplay::InlineBlock, YELLOW)+ .tap_taffy(|taffy| {+ taffy.box_sizing = BoxSizing::ContentBox;+ if inner_display == LayoutDisplay::InlineBlock {+ taffy.size.height = Dimension::length(30.0 + margin_bottom);+ }+ taffy.padding.bottom = taffy::LengthPercentage::length(20.0);+ })+ .with_text_metrics(16.0, 20.0),+ );+ styles.primary.insert(+ 2,+ style(inner_display, BLUE)+ .tap_taffy(|taffy| {+ taffy.size = Size {+ width: Dimension::length(30.0),+ height: Dimension::length(30.0),+ };+ taffy.margin.bottom = taffy::LengthPercentageAuto::length(margin_bottom);+ taffy.overflow = Point {+ x: inner_overflow,+ y: inner_overflow,+ };+ })+ .with_text_metrics(16.0, 20.0),+ );+ styles+ .primary+ .insert(4, sized(LayoutDisplay::InlineBlock, 10.0, 10.0, RED));++ render(&source, &mut styles, 200, 120)+ };++ for margin_bottom in [0.0, 30.0] {+ let test = render_variant(LayoutDisplay::Block, Overflow::Hidden, margin_bottom);+ let reference = render_variant(LayoutDisplay::InlineBlock, Overflow::Hidden, margin_bottom);++ assert_eq!(rect(&test, YELLOW), rect(&reference, YELLOW));+ assert_eq!(rect(&test, BLUE), rect(&reference, BLUE));+ assert_eq!(rect(&test, RED), rect(&reference, RED));+ }+}++#[test]+fn phantom_inline_line_does_not_supply_an_inline_block_baseline() {+ let source = Source(vec![+ Node::element(+ "wrapper",+ "div",+ LayoutElementCategory::Generic,+ None,+ vec![1, 2],+ ),+ Node::element(+ "empty-atomic",+ "div",+ LayoutElementCategory::Generic,+ None,+ Vec::new(),+ ),+ Node::element(+ "block-atomic",+ "div",+ LayoutElementCategory::Generic,+ None,+ vec![3, 4],+ ),+ Node::element(+ "empty-inline",+ "span",+ LayoutElementCategory::Generic,+ None,+ Vec::new(),+ ),+ Node::element(+ "green-block",+ "div",+ LayoutElementCategory::Generic,+ None,+ Vec::new(),+ ),+ ]);+ let mut styles = Styles::default();+ styles.primary.insert(+ 0,+ style(LayoutDisplay::Block, RED)+ .tap_taffy(|taffy| {+ taffy.size.width = Dimension::length(200.0);+ })+ .with_text_metrics(0.0, 0.0),+ );+ styles+ .primary+ .insert(1, sized(LayoutDisplay::InlineBlock, 100.0, 200.0, GREEN));+ styles.primary.insert(+ 2,+ style(LayoutDisplay::InlineBlock, PaintColor::TRANSPARENT).with_text_metrics(0.0, 0.0),+ );+ styles.primary.insert(+ 3,+ style(LayoutDisplay::Inline, PaintColor::TRANSPARENT).with_text_metrics(0.0, 0.0),+ );+ styles+ .primary+ .insert(4, sized(LayoutDisplay::Block, 100.0, 200.0, GREEN));++ let snapshot = render(&source, &mut styles, 240, 240);+ let mut green_rects = snapshot+ .fragments+ .iter()+ .filter_map(PaintFragment::solid_fill_in_surface)+ .filter_map(|(rect, color)| (color == GREEN).then_some(rect))+ .collect::<Vec<_>>();+ green_rects.sort_by(|left, right| left.x.total_cmp(&right.x));++ assert_eq!(+ green_rects,+ vec![+ PaintRect::new(0.0, 0.0, 100.0, 200.0),+ PaintRect::new(100.0, 0.0, 100.0, 200.0),+ ]+ );+}+#[test]fn top_and_middle_inline_blocks_align_against_the_parent_line_strut() {let source = Source(vec![