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): preserve inline clearance below floats

ldm00f3e3acd4d4b
diff --git a/Cargo.lock b/Cargo.lock
index e2151c44a..5bc31ffc4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5155,7 +5155,7 @@ dependencies = [
[[package]]
name = "taffy"
version = "0.13.0"
-source = "git+https://github.com/ldm0/taffy?rev=71bc149ce5358406cdabba66da853ceb11ac74ee#71bc149ce5358406cdabba66da853ceb11ac74ee"
+source = "git+https://github.com/ldm0/taffy?rev=e4e8f77c4301ba917cca96b9d67b8000c5a06995#e4e8f77c4301ba917cca96b9d67b8000c5a06995"
dependencies = [
"arrayvec",
"serde",
diff --git a/Cargo.toml b/Cargo.toml
index ec8aa593a..1dd29a0f8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -106,7 +106,7 @@ stylo_atoms = { git = "https://github.com/ldm0/stylo", rev = "671d13d31b3b00e7b1
stylo_dom = { git = "https://github.com/ldm0/stylo", rev = "671d13d31b3b00e7b1e0088ba2b36a4e35c0858c" }
stylo_static_prefs = { git = "https://github.com/ldm0/stylo", rev = "671d13d31b3b00e7b1e0088ba2b36a4e35c0858c" }
stylo_traits = { git = "https://github.com/ldm0/stylo", rev = "671d13d31b3b00e7b1e0088ba2b36a4e35c0858c" }
-taffy = { git = "https://github.com/ldm0/taffy", rev = "71bc149ce5358406cdabba66da853ceb11ac74ee" }
+taffy = { git = "https://github.com/ldm0/taffy", rev = "e4e8f77c4301ba917cca96b9d67b8000c5a06995" }
[workspace.lints.clippy]
disallowed_methods = "deny"
diff --git a/moli-layout/src/inline.rs b/moli-layout/src/inline.rs
index 9e17c7fcd..8110acc16 100644
--- a/moli-layout/src/inline.rs
+++ b/moli-layout/src/inline.rs
@@ -771,12 +771,14 @@ pub(crate) fn measure_inline_lines(
layout: &Layout<TextBrush>,
atomic_baseline_ascents: &[Option<f32>],
structural_edge_contributions: &[bool],
+ float_line_clearances: &[f32],
) -> InlineLineMetrics {
resolve_inline_lines(
context,
layout,
atomic_baseline_ascents,
structural_edge_contributions,
+ float_line_clearances,
None,
)
}
@@ -786,6 +788,7 @@ pub(crate) fn build_inline_line_placements(
layout: &Layout<TextBrush>,
atomic_baseline_ascents: &[Option<f32>],
structural_edge_contributions: &[bool],
+ float_line_clearances: &[f32],
) -> (Vec<InlineLinePlacement>, InlineLineMetrics) {
let mut placements = Vec::with_capacity(layout.lines().len());
let metrics = resolve_inline_lines(
@@ -793,6 +796,7 @@ pub(crate) fn build_inline_line_placements(
layout,
atomic_baseline_ascents,
structural_edge_contributions,
+ float_line_clearances,
Some(&mut placements),
);
(placements, metrics)
@@ -803,6 +807,7 @@ fn resolve_inline_lines(
layout: &Layout<TextBrush>,
atomic_baseline_ascents: &[Option<f32>],
structural_edge_contributions: &[bool],
+ float_line_clearances: &[f32],
mut placements: Option<&mut Vec<InlineLinePlacement>>,
) -> InlineLineMetrics {
let mut result = InlineLineMetrics::default();
@@ -1056,6 +1061,16 @@ fn resolve_inline_lines(
root_bounds.unwrap_or(fallback_root_bounds)
};
let line_height = bounds.height();
+ if !phantom {
+ // CSS baseline adjustment can remove phantom lines or change line
+ // heights. Keep float avoidance as a minimum top, so neither that
+ // adjustment nor Parley's height sum discards the clearance.
+ let clearance = float_line_clearances
+ .get(line_index)
+ .copied()
+ .unwrap_or(0.0);
+ preceding_adjustment += (clearance - raw_top - preceding_adjustment).max(0.0);
+ }
let root_baseline = raw_top + preceding_adjustment - bounds.top;
if !phantom {
@@ -1124,7 +1139,15 @@ fn resolve_inline_lines(
box_block_placements,
});
}
- preceding_adjustment += line_height - (raw_bottom - raw_top);
+ // Parley already excludes an empty terminal line from layout.height().
+ // Do not subtract its inherited metrics again after an oversized atom
+ // has forced an emergency break at the end of the paragraph.
+ let measured_height = if line_index + 1 == layout.len() && line.is_empty() {
+ 0.0
+ } else {
+ raw_bottom - raw_top
+ };
+ preceding_adjustment += line_height - measured_height;
unadjusted_line_top += metrics.line_height.max(0.0);
}
@@ -2290,10 +2313,11 @@ impl InlineNormalizer {
vertical_align: InlineVerticalAlign,
) {
self.flush_pending_carriage_return();
- if matches!(
- role,
- InlineObjectRole::Atomic | InlineObjectRole::Float | InlineObjectRole::OutOfFlow
- ) {
+ // Absolutely positioned descendants do not interrupt CSS whitespace
+ // collapsing or make an otherwise empty line non-empty.
+ // In particular, a hidden loading hint before an inline button must
+ // not preserve a leading space and create an extra line beside a float.
+ if matches!(role, InlineObjectRole::Atomic | InlineObjectRole::Float) {
self.flush_pending();
self.line_has_content = true;
}
@@ -2677,9 +2701,9 @@ mod tests {
line_placements: Vec::new(),
fragments: InlineFragments::default(),
};
- let summary = measure_inline_lines(&context, &layout, &[], &[]);
+ let summary = measure_inline_lines(&context, &layout, &[], &[], &[]);
let (placements, materialized_summary) =
- build_inline_line_placements(&context, &layout, &[], &[]);
+ build_inline_line_placements(&context, &layout, &[], &[], &[]);
assert_eq!(summary, materialized_summary);
assert_eq!(placements.len(), layout.lines().len());
diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rs
index bc2fa1e03..b26dd18a1 100644
--- a/moli-layout/src/taffy_tree.rs
+++ b/moli-layout/src/taffy_tree.rs
@@ -2443,6 +2443,7 @@ where
.any(|object| object.role == InlineObjectRole::Float);
let mut float_height = None;
let mut alignment_float_height = 0.0;
+ let mut float_line_clearances = Vec::new();
if has_inline_float
|| block_context
.as_ref()
@@ -2465,7 +2466,7 @@ where
padding_border.top,
[padding_border.left, padding_border.right],
);
- self.break_inline_lines_with_floats(
+ float_line_clearances = self.break_inline_lines_with_floats(
context,
layout,
width,
@@ -2489,7 +2490,7 @@ where
padding_border.top,
[padding_border.left, padding_border.right],
);
- self.break_inline_lines_with_floats(
+ float_line_clearances = self.break_inline_lines_with_floats(
context,
layout,
width,
@@ -2520,6 +2521,7 @@ where
layout,
&atomic_baseline_ascents,
&structural_edge_contributions,
+ &float_line_clearances,
);
(metrics, Some(placements))
} else {
@@ -2529,6 +2531,7 @@ where
layout,
&atomic_baseline_ascents,
&structural_edge_contributions,
+ &float_line_clearances,
),
None,
)
@@ -2587,32 +2590,67 @@ where
block_context: &mut BlockContext<'_>,
content_offset: Point<f32>,
floats: &mut Vec<InlineFloatPlacement>,
- ) {
+ ) -> Vec<f32> {
+ let wraps = self.boxes[context.root_style.index()]
+ .style
+ .computed
+ .as_ref()
+ .is_none_or(|computed| {
+ computed.get_inherited_text().text_wrap_mode
+ == style::computed_values::text_wrap_mode::T::Wrap
+ });
let mut breaker = layout.break_lines();
- let initial_slot = block_context.find_content_slot(0.0, Clear::None, None);
- let mut has_active_floats = initial_slot.segment_id.is_some();
+ let mut slot = inline_float_slot(block_context, 0.0, None, 0.0);
+ let mut clearance = slot.y.max(0.0);
+ let mut line_clearances = Vec::new();
{
let state = breaker.state_mut();
state.set_layout_max_advance(width);
- state.set_line_max_advance(initial_slot.width.max(0.0));
- state.set_line_x(initial_slot.x);
- state.set_line_y(f64::from(initial_slot.y));
+ state.set_line_max_advance(slot.width.max(0.0));
+ state.set_line_x(slot.x);
+ state.set_line_y(f64::from(slot.y));
}
while let Some(yield_data) = breaker.break_next() {
match yield_data {
- YieldData::LineBreak(_) => {
- let state = breaker.state_mut();
- if has_active_floats {
- let next_slot = block_context.find_content_slot(
- state.line_y() as f32,
- Clear::None,
- None,
+ YieldData::LineBreak(data) => {
+ // An unbreakable item may overflow a rectangular paragraph,
+ // but a float-reduced slot can have more room below it.
+ // Regular breaks can hang trailing whitespace beyond the
+ // slot; that whitespace alone must not move a fitting line.
+ // Preformatted/nowrap lines deliberately overflow their
+ // available width instead of moving below adjacent floats.
+ let tolerance = width.abs().max(1.0) * f32::EPSILON * 8.0;
+ if wraps
+ && slot.segment_id.is_some()
+ && (data.reason != parley::BreakReason::Regular || slot.width <= 0.0)
+ && data.advance > slot.width.max(0.0) + tolerance
+ && breaker.revert()
+ {
+ slot = inline_float_slot(
+ block_context,
+ data.line_y_start as f32,
+ slot.segment_id,
+ data.advance,
);
- has_active_floats = next_slot.segment_id.is_some();
- state.set_line_max_advance(next_slot.width.max(0.0));
- state.set_line_x(next_slot.x);
- state.set_line_y(f64::from(next_slot.y));
+ clearance = clearance.max(slot.y);
+ let state = breaker.state_mut();
+ state.set_line_max_advance(slot.width.max(0.0));
+ state.set_line_x(slot.x);
+ state.set_line_y(f64::from(slot.y));
+ continue;
+ }
+ line_clearances.push(clearance);
+ let state = breaker.state_mut();
+ if slot.segment_id.is_some() {
+ let line_y = state.line_y() as f32;
+ slot = inline_float_slot(block_context, line_y, None, 0.0);
+ if slot.y > line_y {
+ clearance = clearance.max(slot.y);
+ }
+ state.set_line_max_advance(slot.width.max(0.0));
+ state.set_line_x(slot.x);
+ state.set_line_y(f64::from(slot.y));
} else {
state.set_line_x(0.0);
state.set_line_max_advance(width);
@@ -2670,17 +2708,20 @@ where
order: usize::try_from(data.inline_box_id).unwrap_or(usize::MAX),
parent_width: child_inputs.parent_size.width,
});
- let next_slot =
- block_context.find_content_slot(state.line_y() as f32, Clear::None, None);
- has_active_floats = next_slot.segment_id.is_some();
- state.set_line_max_advance(next_slot.width.max(0.0));
- state.set_line_x(next_slot.x);
- state.set_line_y(f64::from(next_slot.y));
+ let line_y = state.line_y() as f32;
+ slot = inline_float_slot(block_context, line_y, None, 0.0);
+ if slot.y > line_y {
+ clearance = clearance.max(slot.y);
+ }
+ state.set_line_max_advance(slot.width.max(0.0));
+ state.set_line_x(slot.x);
+ state.set_line_y(f64::from(slot.y));
state.append_inline_box_to_line(data.advance, 0.0);
}
}
}
breaker.finish();
+ line_clearances
}
fn position_inline_objects(
@@ -2799,6 +2840,21 @@ where
}
}
+fn inline_float_slot(
+ context: &BlockContext<'_>,
+ min_y: f32,
+ mut after: Option<usize>,
+ minimum_width: f32,
+) -> taffy::ContentSlot {
+ loop {
+ let slot = context.find_content_slot(min_y, Clear::None, after);
+ if slot.segment_id.is_none() || slot.width >= minimum_width {
+ return slot;
+ }
+ after = slot.segment_id;
+ }
+}
+
fn inline_percentage_basis(
available: AvailableSpace,
sizing_purpose: SizingPurpose,
diff --git a/moli-layout/tests/phase4_layout_contract.rs b/moli-layout/tests/phase4_layout_contract.rs
index 1eb434722..ed1f8ac1b 100644
--- a/moli-layout/tests/phase4_layout_contract.rs
+++ b/moli-layout/tests/phase4_layout_contract.rs
@@ -661,6 +661,107 @@ fn left_float_restricts_inline_slots_and_clear_moves_the_next_block_below_it() {
assert_close(rect(&snapshot, GREEN).y, 40.0);
}
+#[test]
+fn atomic_inline_content_moves_to_the_first_float_slot_that_fits() {
+ // Chromium oracle: a full-width inline button in a normal-flow form
+ // following a full-width float belongs below that float. Smaller buttons
+ // can stay alongside it, or move only as far as the first wider segment.
+ for (left, right, atom_width, expected_x, expected_y) in [
+ (Some((200.0, 80.0)), None, 200.0, 0.0, 80.0),
+ (None, Some((200.0, 80.0)), 200.0, 0.0, 80.0),
+ (Some((120.0, 80.0)), None, 120.0, 0.0, 80.0),
+ (Some((60.0, 80.0)), None, 100.0, 60.0, 0.0),
+ (None, Some((60.0, 80.0)), 100.0, 0.0, 0.0),
+ (Some((120.0, 40.0)), Some((60.0, 80.0)), 80.0, 0.0, 40.0),
+ (Some((120.0, 40.0)), Some((60.0, 80.0)), 160.0, 0.0, 80.0),
+ (Some((60.0, 80.0)), Some((120.0, 40.0)), 80.0, 60.0, 40.0),
+ (Some((60.0, 80.0)), None, 240.0, 0.0, 80.0),
+ (None, None, 240.0, 0.0, 0.0),
+ ] {
+ let source = Source(vec![
+ Node::element("root", "div", LayoutElementCategory::Generic, None, vec![1]),
+ Node::element(
+ "container",
+ "div",
+ LayoutElementCategory::Generic,
+ None,
+ vec![2, 3, 4],
+ ),
+ Node::element("left", "div", LayoutElementCategory::Generic, None, vec![]),
+ Node::element("right", "div", LayoutElementCategory::Generic, None, vec![]),
+ Node::element(
+ "form",
+ "form",
+ LayoutElementCategory::Generic,
+ None,
+ vec![5, 7, 6],
+ ),
+ Node::element(
+ "loading-hint",
+ "span",
+ LayoutElementCategory::Generic,
+ None,
+ vec![8],
+ ),
+ Node::element("atom", "span", LayoutElementCategory::Generic, None, vec![]),
+ Node::text("space", " "),
+ Node::element(
+ "screenreader-hint",
+ "span",
+ LayoutElementCategory::Generic,
+ None,
+ vec![9],
+ ),
+ Node::text("loading", "Loading"),
+ ]);
+ let mut styles = Styles::default();
+ styles.primary.insert(
+ 0,
+ sized(LayoutDisplay::Block, 400.0, 200.0, PaintColor::TRANSPARENT),
+ );
+ for (id, color) in [(1, YELLOW), (4, GREEN)] {
+ styles.primary.insert(
+ id,
+ style(LayoutDisplay::Block, color)
+ .tap_taffy(|s| s.size.width = Dimension::length(200.0))
+ .with_text_metrics(16.0, 20.0),
+ );
+ }
+ for (id, size, direction) in [(2, left, Float::Left), (3, right, Float::Right)] {
+ styles.primary.insert(
+ id,
+ size.map_or_else(
+ || style(LayoutDisplay::None, PaintColor::TRANSPARENT),
+ |(width, height)| {
+ sized(LayoutDisplay::Block, width, height, BLUE)
+ .with_float(direction, Clear::None)
+ },
+ ),
+ );
+ }
+ styles
+ .primary
+ .insert(5, style(LayoutDisplay::Inline, PaintColor::TRANSPARENT));
+ styles.primary.insert(
+ 6,
+ sized(LayoutDisplay::InlineBlock, atom_width, 24.0, RED)
+ .with_inline_alignment(moli_layout::LayoutInlineAlignment::Top),
+ );
+ styles.primary.insert(
+ 8,
+ sized(LayoutDisplay::Block, 1.0, 1.0, PaintColor::TRANSPARENT)
+ .with_position(LayoutPosition::Absolute),
+ );
+ let snapshot = render(&source, &mut styles, 400, 200);
+ let atom = rect(&snapshot, RED);
+ assert_close(atom.x, expected_x);
+ assert_close(atom.y, expected_y);
+ assert_close(atom.width, atom_width);
+ assert_close(rect(&snapshot, GREEN).height, expected_y + 24.0);
+ assert_close(rect(&snapshot, YELLOW).height, expected_y + 24.0);
+ }
+}
+
#[test]
fn intrinsic_inline_probes_clamp_widths_consumed_by_margins_beside_floats() {
// A grid/flex intrinsic probe can give the paragraph a known width of
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 584c56581..542d9f0f6 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
@@ -1761,6 +1761,60 @@ document.body.innerHTML = `<div id=stage>
.expect("absolute fit-content fixture should run");
}
+#[tokio::test(flavor = "current_thread")]
+async fn float_line_clearance_respects_pre_and_nowrap() {
+ 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/float-nowrap.html")?,
+ );
+ page_vm.vm_mut().eval(
+ r#"
+document.head.innerHTML = `<style>
+html,body{margin:0;padding:0}
+.case{position:absolute;top:0;width:200px;height:120px;font:16px/20px monospace}
+.float{float:left;width:60px;height:80px}
+p{margin:0;width:200px}
+#pre{left:0;white-space:pre}
+#nowrap{left:240px;white-space:nowrap}
+#wrap{left:480px;white-space:normal}
+.atom{display:inline-block;width:240px;height:24px;vertical-align:top}
+</style>`;
+document.body.innerHTML = `<div class=case id=pre><div class=float></div><p>abcdefghijabcdefghij <br>abcdefghijabcdefghij</p></div><div class=case id=nowrap><div class=float></div><p><span class=atom></span></p></div><div class=case id=wrap><div class=float></div><p><span class=atom></span></p></div>`;
+"#,
+ )?;
+ page_vm.vm_mut().sync_live_document_style_sources();
+ let geometry = page_vm.vm_mut().eval(
+ r#"JSON.stringify(['pre','nowrap','wrap'].map(id=>{
+const c=document.getElementById(id), p=c.querySelector('p');
+const r=c.getBoundingClientRect(), t=(p.querySelector('span')||p).getBoundingClientRect();
+return [t.x-r.x,t.y-r.y,p.getBoundingClientRect().height];
+}))"#,
+ )?;
+ let geometry: Vec<[f32; 3]> = serde_json::from_str(&geometry)?;
+ // Chromium: pre/nowrap content stays beside the float and overflows;
+ // a wrapping paragraph moves its oversized atom below the float.
+ for (actual, expected) in geometry.iter().zip([
+ [0.0, 0.0, 40.0],
+ [60.0, 0.0, 24.0],
+ [0.0, 80.0, 104.0],
+ ]) {
+ for (actual, expected) in actual.iter().zip(expected) {
+ assert!(
+ (actual - expected).abs() <= 0.05,
+ "expected {expected}, got {actual}; geometry={geometry:?}"
+ );
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("float nowrap fixture should run");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn floated_auto_width_inline_formatting_contexts_shrink_to_fit() {
run_page_vm_async_test(async move {