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): apply document quirks rules to inline line heights

ldm000e5235046f5
diff --git a/moli-layout/src/builder.rs b/moli-layout/src/builder.rs
index 2c06ac8fe..5e5c3c0fc 100644
--- a/moli-layout/src/builder.rs
+++ b/moli-layout/src/builder.rs
@@ -162,6 +162,7 @@ where
root.source = None;
}
let mut world = LayoutWorld::new(root, self.source.root_is_document_element());
+ world.quirks_mode = self.source.quirks_mode();
let root_box = world.root();
if root_generates_principal_box {
world.map_source(source_root, root_box);
diff --git a/moli-layout/src/inline.rs b/moli-layout/src/inline.rs
index 8110acc16..468f25387 100644
--- a/moli-layout/src/inline.rs
+++ b/moli-layout/src/inline.rs
@@ -89,6 +89,8 @@ pub(crate) struct InlineTextUnit {
pub(crate) ancestors: Vec<LayoutBoxId>,
pub(crate) sources: Vec<SourceOrigin>,
pub(crate) control: bool,
+ /// A normalized CSS space that can still collapse at a line boundary.
+ pub(crate) collapsible_whitespace: bool,
pub(crate) break_spaces_opportunity: bool,
}
@@ -118,6 +120,15 @@ pub(crate) struct InlineObject {
pub(crate) vertical_align: InlineVerticalAlign,
}
+/// Used inline-edge dimensions for one numeric layout probe. Margins can
+/// create a line, but only border/padding retain an empty inline's line height
+/// in quirks mode.
+#[derive(Clone, Copy, Debug, Default)]
+pub(crate) struct InlineEdgeContribution {
+ pub(crate) creates_line: bool,
+ pub(crate) has_border_or_padding: bool,
+}
+
/// Pass-owned metadata for one non-atomic inline box flattened into Parley.
///
/// Parley owns shaping and inline-axis breaking, while this hierarchy restores
@@ -163,6 +174,9 @@ pub(crate) struct InlineFormattingContext {
/// baselines. Fallback glyph fonts must not replace its line height or
/// x-height.
pub(crate) parent_strut: Option<InlineStrutMetrics>,
+ /// Quirks and limited-quirks omit the block's strut and empty, undecorated
+ /// inline struts from line height. Keep font metrics for alignment/paint.
+ pub(crate) uses_quirks_line_height: bool,
pub(crate) root_includes_used_font_metrics: bool,
/// Direct structural parent of each shaped style. Including this identity
/// in style deduplication prevents glyph runs from crossing a box-state
@@ -762,6 +776,65 @@ pub(crate) fn break_inline_lines(
}
}
+/// Reads Parley's line items together with their CSS content contribution.
+/// Parley retains line-edge spaces for positioning and selection. Collapse
+/// their contribution here before resolving vertical metrics, while keeping
+/// every item in the same order for painting and fragment geometry.
+fn line_items_with_content<'a>(
+ context: &'a InlineFormattingContext,
+ line: &parley::Line<'a, TextBrush>,
+) -> impl Iterator<Item = (PositionedLayoutItem<'a, TextBrush>, bool)> + 'a {
+ let has_content = |item: &PositionedLayoutItem<'_, TextBrush>| match item {
+ PositionedLayoutItem::GlyphRun(glyph_run) => {
+ glyph_run.style().brush.paint && glyph_run.glyphs().next().is_some()
+ }
+ PositionedLayoutItem::InlineBox(positioned) => context
+ .object(positioned.id)
+ .is_some_and(|object| object.role == InlineObjectRole::Atomic),
+ };
+ let only_collapsible_spaces = |item: &PositionedLayoutItem<'_, TextBrush>| match item {
+ PositionedLayoutItem::GlyphRun(glyph_run) => {
+ glyph_run_is_collapsible_whitespace(context, glyph_run)
+ }
+ PositionedLayoutItem::InlineBox(_) => false,
+ };
+ let mut content_range = 0..0;
+ if context.uses_quirks_line_height {
+ for (index, item) in line.items().enumerate() {
+ if has_content(&item) && !only_collapsible_spaces(&item) {
+ if content_range.is_empty() {
+ content_range.start = index;
+ }
+ content_range.end = index + 1;
+ }
+ }
+ }
+ line.items().enumerate().map(move |(index, item)| {
+ let contributes = has_content(&item)
+ && (!context.uses_quirks_line_height
+ || content_range.contains(&index)
+ || !only_collapsible_spaces(&item));
+ (item, contributes)
+ })
+}
+
+fn glyph_run_is_collapsible_whitespace(
+ context: &InlineFormattingContext,
+ glyph_run: &parley::GlyphRun<'_, TextBrush>,
+) -> bool {
+ let mut found = false;
+ let only_spaces = glyph_run
+ .run()
+ .clusters()
+ .filter(|cluster| std::ptr::eq(cluster.first_style(), glyph_run.style()))
+ .all(|cluster| {
+ found = true;
+ let units = overlapping_output_ranges(&context.text_units, &cluster.text_range());
+ !units.is_empty() && units.iter().all(|unit| unit.collapsible_whitespace)
+ });
+ found && only_spaces
+}
+
/// Builds the pass-local vertical placement sidecar that Parley 0.10 does not
/// provide for CSS `vertical-align`. The sidecar leaves Parley's shaped data
/// immutable and applies the same offsets to glyph projection, atomic boxes,
@@ -770,7 +843,7 @@ pub(crate) fn measure_inline_lines(
context: &InlineFormattingContext,
layout: &Layout<TextBrush>,
atomic_baseline_ascents: &[Option<f32>],
- structural_edge_contributions: &[bool],
+ structural_edge_contributions: &[InlineEdgeContribution],
float_line_clearances: &[f32],
) -> InlineLineMetrics {
resolve_inline_lines(
@@ -787,7 +860,7 @@ pub(crate) fn build_inline_line_placements(
context: &InlineFormattingContext,
layout: &Layout<TextBrush>,
atomic_baseline_ascents: &[Option<f32>],
- structural_edge_contributions: &[bool],
+ structural_edge_contributions: &[InlineEdgeContribution],
float_line_clearances: &[f32],
) -> (Vec<InlineLinePlacement>, InlineLineMetrics) {
let mut placements = Vec::with_capacity(layout.lines().len());
@@ -806,7 +879,7 @@ fn resolve_inline_lines(
context: &InlineFormattingContext,
layout: &Layout<TextBrush>,
atomic_baseline_ascents: &[Option<f32>],
- structural_edge_contributions: &[bool],
+ structural_edge_contributions: &[InlineEdgeContribution],
float_line_clearances: &[f32],
mut placements: Option<&mut Vec<InlineLinePlacement>>,
) -> InlineLineMetrics {
@@ -818,9 +891,8 @@ fn resolve_inline_lines(
let metrics = line.metrics();
let raw_top = unadjusted_line_top;
let raw_bottom = raw_top + metrics.line_height.max(0.0);
- let mut geometries = line
- .items()
- .map(|item| match item {
+ let mut geometries = line_items_with_content(context, &line)
+ .map(|(item, contributes_to_line)| match item {
PositionedLayoutItem::GlyphRun(glyph_run) => {
let run = glyph_run.run();
let run_metrics = run.metrics();
@@ -840,14 +912,14 @@ fn resolve_inline_lines(
bounds,
initial_top: glyph_run.baseline() + bounds.top,
structural_parent,
- edge_box: None,
+ object_index: None,
vertical_align: InlineVerticalAlign::default(),
// Parley may expose an empty root-style run next to
// float/out-of-flow placeholders. It carries the font
// 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(),
+ contributes_to_line,
+ creates_line: contributes_to_line,
glyph_key: if paint {
style_index.map(|index| (run.index(), index))
} else {
@@ -882,13 +954,7 @@ fn resolve_inline_lines(
structural_parent: object
.and_then(|object| object.ancestors.last().copied())
.unwrap_or(context.root_style),
- edge_box: object.and_then(|object| {
- matches!(
- object.role,
- InlineObjectRole::StartEdge | InlineObjectRole::EndEdge
- )
- .then_some(object.box_id)
- }),
+ object_index,
vertical_align: if is_atomic {
object
.map(|object| object.vertical_align)
@@ -896,13 +962,12 @@ fn resolve_inline_lines(
} else {
InlineVerticalAlign::default()
},
- contributes_to_line: is_atomic,
+ contributes_to_line,
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),
+ .is_some_and(|edge| edge.creates_line),
InlineObjectRole::Float | InlineObjectRole::OutOfFlow => false,
}),
glyph_key: None,
@@ -912,15 +977,30 @@ fn resolve_inline_lines(
}
})
.collect::<Vec<_>>();
- let phantom = css_line_is_phantom(
- line.break_reason(),
- geometries.iter().any(|geometry| geometry.creates_line),
+ // Parley keeps forced breaks as clusters without positioned glyphs.
+ // In quirks mode their metrics are a fallback for their own empty box,
+ // resolved after that box's content rather than for the whole line.
+ let line_break =
+ if context.uses_quirks_line_height && line.break_reason() == BreakReason::Explicit {
+ line_break_metrics(context, layout, &line)
+ } else {
+ None
+ };
+ let mut states = build_line_inline_box_states(
+ context,
+ layout,
+ line.text_range(),
+ &geometries,
+ line_break.map(|(box_id, _)| box_id),
);
- let mut states = build_line_inline_box_states(context, line.text_range(), &geometries);
let mut state_indices = BTreeMap::new();
for (index, state) in states.iter().enumerate() {
state_indices.insert(state.box_id.index(), index);
}
+ let phantom = css_line_is_phantom(
+ line.break_reason(),
+ geometries.iter().any(|geometry| geometry.creates_line),
+ );
for state in &mut states {
state.parent = state_indices.get(&state.parent_box.index()).copied();
state.anchor = state
@@ -928,36 +1008,37 @@ fn resolve_inline_lines(
.map_or(LineVerticalAnchor::Root, LineVerticalAnchor::State);
}
for geometry in &mut geometries {
- geometry.anchor = geometry.edge_box.map_or_else(
- || {
- state_indices
- .get(&geometry.structural_parent.index())
- .copied()
- .map_or(LineVerticalAnchor::Root, LineVerticalAnchor::State)
- },
- |box_id| {
- state_indices
- .get(&box_id.index())
- .copied()
- .map_or(LineVerticalAnchor::Root, LineVerticalAnchor::State)
- },
- );
+ let box_id = geometry
+ .edge(context)
+ .map_or(geometry.structural_parent, |object| object.box_id);
+ geometry.anchor = state_indices
+ .get(&box_id.index())
+ .copied()
+ .map_or(LineVerticalAnchor::Root, LineVerticalAnchor::State);
}
+ let line_break = line_break.map(|(box_id, bounds)| {
+ let anchor = state_indices
+ .get(&box_id.index())
+ .copied()
+ .map_or(LineVerticalAnchor::Root, LineVerticalAnchor::State);
+ (anchor, bounds)
+ });
let fallback_root_bounds = InlineVerticalBounds {
top: -metrics.ascent - metrics.leading * 0.5,
bottom: metrics.descent + metrics.leading * 0.5,
};
- let mut root_bounds = (!phantom).then(|| {
+ let mut root_bounds = (!phantom && !context.uses_quirks_line_height).then(|| {
context
.parent_strut
.map_or(fallback_root_bounds, InlineVerticalBounds::from_strut)
});
for state in &mut states {
- state.metrics = (!phantom)
- .then_some(state.strut)
- .flatten()
- .map(InlineVerticalBounds::from_strut);
+ state.metrics =
+ (!phantom && !context.uses_quirks_line_height && state.has_strut_content)
+ .then_some(state.strut)
+ .flatten()
+ .map(InlineVerticalBounds::from_strut);
}
// One pending list per structural target plus one for the root line
@@ -967,6 +1048,23 @@ fn resolve_inline_lines(
let mut pending = vec![Vec::<PendingLineAlignment>::new(); states.len() + 1];
for (item_index, geometry) in geometries.iter_mut().enumerate() {
+ // Text supplies its own strut through glyph_line_bounds below.
+ // An empty inline only contributes if this fragment has used
+ // inline-axis border/padding; margin alone is insufficient.
+ if geometry
+ .object_index
+ .and_then(|index| structural_edge_contributions.get(index))
+ .is_some_and(|edge| edge.has_border_or_padding)
+ && let LineVerticalAnchor::State(index) = geometry.anchor
+ && let Some(strut) = states[index].strut
+ {
+ include_in_parent(
+ InlineVerticalBounds::from_strut(strut),
+ Some(index),
+ &mut states,
+ &mut root_bounds,
+ );
+ }
if !geometry.contributes_to_line {
continue;
}
@@ -1013,7 +1111,11 @@ fn resolve_inline_lines(
&mut states,
&mut geometries,
);
- states[state_index].metrics = target_metrics;
+ states[state_index].metrics = target_metrics.or_else(|| {
+ line_break
+ .filter(|(anchor, _)| *anchor == LineVerticalAnchor::State(state_index))
+ .map(|(_, bounds)| bounds)
+ });
let Some(state_bounds) = states[state_index].metrics else {
continue;
@@ -1054,9 +1156,16 @@ fn resolve_inline_lines(
&mut states,
&mut geometries,
);
+ root_bounds = root_bounds.or_else(|| {
+ line_break
+ .filter(|(anchor, _)| *anchor == LineVerticalAnchor::Root)
+ .map(|(_, bounds)| bounds)
+ });
let bounds = if phantom {
InlineVerticalBounds::ZERO
+ } else if context.uses_quirks_line_height {
+ root_bounds.unwrap_or(InlineVerticalBounds::ZERO)
} else {
root_bounds.unwrap_or(fallback_root_bounds)
};
@@ -1083,9 +1192,8 @@ fn resolve_inline_lines(
// and baselines. The following state walk and vectors exist solely to
// place final glyphs, atomic objects, and structural fragments.
if let Some(placements) = placements.as_mut() {
- let mut ascending_states = (0..states.len()).collect::<Vec<_>>();
- ascending_states.sort_by_key(|index| states[*index].depth);
- for state_index in ascending_states {
+ // Place alignment anchors before the states that reference them.
+ for state_index in state_order.iter().rev().copied() {
states[state_index].global_offset = states[state_index].relative_offset
+ anchor_global_offset(states[state_index].anchor, &states);
}
@@ -1116,10 +1224,24 @@ fn resolve_inline_lines(
.filter_map(|state| {
let strut = state.strut?;
let baseline = root_baseline + state.global_offset;
+ // An empty closing fragment has no font box only when
+ // its whole quirks line has no resolved vertical metrics.
+ // Content with zero height still retains the font box.
+ let (top, height) = if context.uses_quirks_line_height
+ && !state.has_strut_content
+ && root_bounds.is_none()
+ {
+ (baseline, 0.0)
+ } else {
+ (
+ baseline - strut.text_ascent,
+ (strut.text_ascent + strut.text_descent).max(0.0),
+ )
+ };
Some(InlineBoxBlockPlacement {
box_id: state.box_id,
- top: baseline - strut.text_ascent,
- height: (strut.text_ascent + strut.text_descent).max(0.0),
+ top,
+ height,
})
})
.collect();
@@ -1163,8 +1285,9 @@ struct InlineItemVerticalGeometry {
/// baseline back into an item delta.
initial_top: f32,
structural_parent: LayoutBoxId,
- /// Structural edges track their own box baseline rather than their parent.
- edge_box: Option<LayoutBoxId>,
+ /// Source object identity; its role and used edge contributions stay in
+ /// their input records rather than being copied into vertical geometry.
+ object_index: Option<usize>,
vertical_align: InlineVerticalAlign,
/// Whether this item supplies block-axis geometry to the line.
contributes_to_line: bool,
@@ -1177,6 +1300,43 @@ struct InlineItemVerticalGeometry {
relative_offset: f32,
}
+impl InlineItemVerticalGeometry {
+ /// Structural edges align to their own box rather than to their parent.
+ fn edge<'a>(&self, context: &'a InlineFormattingContext) -> Option<&'a InlineObject> {
+ let object = context.objects.get(self.object_index?)?;
+ matches!(
+ object.role,
+ InlineObjectRole::StartEdge | InlineObjectRole::EndEdge
+ )
+ .then_some(object)
+ }
+}
+
+fn line_break_metrics(
+ context: &InlineFormattingContext,
+ layout: &Layout<TextBrush>,
+ line: &parley::Line<'_, TextBrush>,
+) -> Option<(LayoutBoxId, InlineVerticalBounds)> {
+ line.runs().find_map(|run| {
+ let cluster = run
+ .clusters()
+ .find(|cluster| cluster.is_hard_line_break())?;
+ let style_index = layout
+ .styles()
+ .iter()
+ .position(|style| std::ptr::eq(style, cluster.first_style()))?;
+ let structural_parent = context.style_parent(style_index);
+ let primary_strut =
+ context.font_metrics[style_index].map(|metrics| inline_strut_metrics(metrics, true));
+ let bounds = glyph_line_bounds(
+ primary_strut,
+ run.metrics(),
+ context.box_includes_used_font_metrics(structural_parent),
+ );
+ Some((structural_parent, bounds))
+ })
+}
+
#[derive(Clone, Copy, Debug)]
struct LineInlineBoxState {
box_id: LayoutBoxId,
@@ -1185,13 +1345,16 @@ struct LineInlineBoxState {
depth: usize,
vertical_align: InlineVerticalAlign,
strut: Option<InlineStrutMetrics>,
+ /// Content and start edges, plus closing edges in standards mode,
+ /// retain this box's strut and the struts of its structural ancestors.
+ has_strut_content: bool,
metrics: Option<InlineVerticalBounds>,
anchor: LineVerticalAnchor,
relative_offset: f32,
global_offset: f32,
}
-#[derive(Clone, Copy, Debug)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LineVerticalAnchor {
Root,
State(usize),
@@ -1270,21 +1433,60 @@ fn glyph_line_bounds(
fn build_line_inline_box_states(
context: &InlineFormattingContext,
+ layout: &Layout<TextBrush>,
line_range: Range<usize>,
geometries: &[InlineItemVerticalGeometry],
+ line_break_box: Option<LayoutBoxId>,
) -> Vec<LineInlineBoxState> {
let mut present = std::collections::BTreeSet::new();
+ let mut strut_boxes = std::collections::BTreeSet::new();
for unit in overlapping_output_ranges(&context.text_units, &line_range) {
for ancestor in &unit.ancestors {
mark_structural_path(context, *ancestor, &mut present);
+ if !unit.control {
+ mark_structural_path(context, *ancestor, &mut strut_boxes);
+ }
}
}
for geometry in geometries {
mark_structural_path(context, geometry.structural_parent, &mut present);
- if let Some(box_id) = geometry.edge_box {
- mark_structural_path(context, box_id, &mut present);
+ if geometry.contributes_to_line {
+ mark_structural_path(context, geometry.structural_parent, &mut strut_boxes);
+ }
+ if let Some(object) = geometry.edge(context) {
+ mark_structural_path(context, object.box_id, &mut present);
+ // A zero-size closing edge still retains its standards strut.
+ // Parley can carry a close after a collapsed trailing space onto
+ // the next line; that close belongs to the preceding fragment.
+ let follows_wrapped_space = || {
+ geometry
+ .object_index
+ .and_then(|index| layout.inline_boxes().get(index))
+ .filter(|edge| edge.index <= line_range.start)
+ .is_some_and(|edge| {
+ context
+ .text_units
+ .partition_point(|unit| unit.output_range.end <= edge.index)
+ .checked_sub(1)
+ .and_then(|index| context.text_units.get(index))
+ .is_some_and(|unit| {
+ unit.output_range.end == edge.index
+ && unit.collapsible_whitespace
+ && unit.ancestors.contains(&object.box_id)
+ })
+ })
+ };
+ if object.role == InlineObjectRole::StartEdge
+ || (!context.uses_quirks_line_height
+ && (geometry.creates_line || !follows_wrapped_space()))
+ {
+ mark_structural_path(context, object.box_id, &mut strut_boxes);
+ }
}
}
+ if let Some(box_id) = line_break_box {
+ mark_structural_path(context, box_id, &mut present);
+ }
context
.structural_boxes
@@ -1297,6 +1499,7 @@ fn build_line_inline_box_states(
depth: structural_box_depth(context, state.box_id),
vertical_align: state.vertical_align,
strut: state.strut,
+ has_strut_content: strut_boxes.contains(&state.box_id.index()),
metrics: None,
anchor: LineVerticalAnchor::Root,
relative_offset: 0.0,
@@ -1314,7 +1517,9 @@ fn mark_structural_path(
let Some(state) = context.structural_box(box_id) else {
break;
};
- present.insert(box_id.index());
+ if !present.insert(box_id.index()) {
+ break;
+ }
box_id = state.parent;
}
}
@@ -1787,6 +1992,7 @@ impl InlineBuildInput {
objects,
font_metrics,
parent_strut,
+ uses_quirks_line_height: world.quirks_mode != style::context::QuirksMode::NoQuirks,
root_includes_used_font_metrics: world.boxes[self.root_style.index()]
.style
.includes_used_font_metrics(),
@@ -2248,6 +2454,7 @@ impl InlineNormalizer {
ancestors: pending.ancestors,
sources: pending.sources,
control: false,
+ collapsible_whitespace: true,
break_spaces_opportunity: false,
},
);
@@ -2321,8 +2528,23 @@ impl InlineNormalizer {
self.flush_pending();
self.line_has_content = true;
}
+ // Put consecutive closing edges before Parley's newline cluster.
+ // Stop moving edges when a bidi control or another object intervenes.
+ let byte_index = if role == InlineObjectRole::EndEdge {
+ self.units
+ .last()
+ .filter(|unit| &self.text[unit.output_range.clone()] == "\n")
+ .filter(|unit| {
+ self.objects
+ .last()
+ .is_none_or(|(index, _, _)| *index < unit.output_range.end)
+ })
+ .map_or(self.text.len(), |unit| unit.output_range.start)
+ } else {
+ self.text.len()
+ };
self.objects.push((
- self.text.len(),
+ byte_index,
InlineObject {
box_id,
role,
@@ -2349,6 +2571,7 @@ impl InlineNormalizer {
ancestors: ancestors.to_vec(),
sources,
control,
+ collapsible_whitespace: false,
break_spaces_opportunity: false,
});
}
@@ -2549,6 +2772,91 @@ mod tests {
}
}
+ #[test]
+ fn closing_inline_edges_remain_on_the_forced_break_line() {
+ for (bidi, reopen_inline, outer_line) in [
+ (InlineUnicodeBidi::Normal, false, 0),
+ (InlineUnicodeBidi::Embed, false, 1),
+ (InlineUnicodeBidi::Normal, true, 1),
+ ] {
+ let root = LayoutBoxId::from_index(0);
+ let outer = LayoutBoxId::from_index(1);
+ let inner = LayoutBoxId::from_index(2);
+ let atom = LayoutBoxId::from_index(3);
+ let reopened = LayoutBoxId::from_index(4);
+ let align = InlineVerticalAlign::default();
+ let mut normalizer = InlineNormalizer::new(root);
+ normalizer.open_inline(
+ outer,
+ InlineUnicodeBidi::Normal,
+ InlineDirection::Ltr,
+ &[],
+ align,
+ );
+ normalizer.open_inline(inner, bidi, InlineDirection::Ltr, &[outer], align);
+ normalizer.push_object(
+ atom,
+ InlineObjectRole::Atomic,
+ InlineBoxKind::InFlow,
+ &[outer, inner],
+ align,
+ );
+ normalizer.hard_break(inner, &[outer, inner]);
+ normalizer.close_inline(inner, bidi, &[outer], align);
+ if reopen_inline {
+ normalizer.open_inline(
+ reopened,
+ InlineUnicodeBidi::Normal,
+ InlineDirection::Ltr,
+ &[outer],
+ align,
+ );
+ normalizer.close_inline(reopened, InlineUnicodeBidi::Normal, &[outer], align);
+ }
+ normalizer.close_inline(outer, InlineUnicodeBidi::Normal, &[], align);
+ normalizer.hard_break(root, &[]);
+ let input = normalizer.finish();
+
+ let mut font_context = parley::FontContext::new();
+ let mut layout_context = parley::LayoutContext::<TextBrush>::new();
+ let mut builder =
+ layout_context.style_run_builder(&mut font_context, &input.text, 1.0, true);
+ let style = builder.push_style(TextStyle::default());
+ builder.push_style_run(style, ..);
+ for (id, (index, _, kind)) in input.objects.iter().enumerate() {
+ builder.push_inline_box(InlineBox {
+ id: id as u64,
+ kind: *kind,
+ index: *index,
+ width: 1.0,
+ height: 20.0,
+ });
+ }
+ let mut layout = builder.build(&input.text);
+ layout.break_all_lines(None);
+
+ for (box_id, expected_line) in [(inner, 0), (outer, outer_line)] {
+ let object_id = input
+ .objects
+ .iter()
+ .position(|(_, object, _)| {
+ object.box_id == box_id && object.role == InlineObjectRole::EndEdge
+ })
+ .unwrap() as u64;
+ let actual_line = layout.lines().position(|line| {
+ line.items().any(|item| {
+ matches!(item, PositionedLayoutItem::InlineBox(item) if item.id == object_id)
+ })
+ });
+ assert_eq!(
+ actual_line,
+ Some(expected_line),
+ "{bidi:?}, reopen={reopen_inline}, box={box_id:?}"
+ );
+ }
+ }
+ }
+
#[test]
fn parley_shaped_layout_can_be_rebroken_across_probe_widths() {
let text = "alpha beta gamma delta epsilon";
@@ -2695,6 +3003,7 @@ mod tests {
objects: Vec::new(),
font_metrics: vec![None],
parent_strut: None,
+ uses_quirks_line_height: false,
root_includes_used_font_metrics: false,
style_parents: vec![root],
structural_boxes: Vec::new(),
diff --git a/moli-layout/src/source.rs b/moli-layout/src/source.rs
index 383c04c5d..634a6bdef 100644
--- a/moli-layout/src/source.rs
+++ b/moli-layout/src/source.rs
@@ -482,6 +482,11 @@ pub trait LayoutSource {
fn root_is_document_element(&self) -> bool {
false
}
+ /// The source Document's rendering mode, sampled for this layout pass.
+ /// Synthetic sources use standards mode unless they explicitly opt in.
+ fn quirks_mode(&self) -> style::context::QuirksMode {
+ style::context::QuirksMode::NoQuirks
+ }
/// Whether the embedding context disables user scrolling of this viewport,
/// including its scrollbar UI and gutters, independently of CSS overflow.
/// Sampled for this layout pass; descendant scroll containers and
diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rs
index e6d92b304..be3f50e3e 100644
--- a/moli-layout/src/taffy_tree.rs
+++ b/moli-layout/src/taffy_tree.rs
@@ -18,9 +18,10 @@ use crate::{
LAYOUT_SUBPIXELS_PER_CSS_PIXEL, LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic,
LayoutWorld, PaintRect, PaintViewport,
inline::{
- InlineContentWidthsMemo, InlineFormattingContext, InlineFragments, InlineLinePlacement,
- InlineObjectRole, break_inline_lines, build_inline_fragments, build_inline_line_placements,
- measure_inline_lines, relative_atomic_inset_offset, reset_inline_layout_for_probe,
+ InlineContentWidthsMemo, InlineEdgeContribution, InlineFormattingContext, InlineFragments,
+ InlineLinePlacement, InlineObjectRole, break_inline_lines, build_inline_fragments,
+ build_inline_line_placements, measure_inline_lines, relative_atomic_inset_offset,
+ reset_inline_layout_for_probe,
},
positioned::{
FlexCrossAxisStaticContext, HorizontalStaticEdge, PhysicalStaticPosition,
@@ -2361,7 +2362,8 @@ where
inline_percentage_basis(available_space.width, inputs.sizing_purpose);
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 structural_edge_contributions =
+ vec![InlineEdgeContribution::default(); context.objects.len()];
let mut floats = Vec::new();
for (inline_box, object) in layout.inline_boxes_mut().iter_mut().zip(&context.objects) {
@@ -2416,6 +2418,16 @@ where
let logical_start = object.role == InlineObjectRole::StartEdge;
let physical_left =
logical_start == (child_style.direction() == InlineDirection::Ltr);
+ let inline_padding_border = if child_style.uses_horizontal_writing_mode() {
+ (padding.left + border.left, padding.right + border.right)
+ } else {
+ (padding.top + border.top, padding.bottom + border.bottom)
+ };
+ let has_border_or_padding = if physical_left {
+ inline_padding_border.0 != 0.0
+ } else {
+ inline_padding_border.1 != 0.0
+ };
let (margin, padding, border) = if physical_left {
(margins.left, padding.left, border.left)
} else {
@@ -2425,8 +2437,10 @@ where
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;
+ structural_edge_contributions[object_index] = InlineEdgeContribution {
+ creates_line: margin != 0.0 || padding != 0.0 || border != 0.0,
+ has_border_or_padding,
+ };
}
}
}
@@ -3282,6 +3296,7 @@ fn empty_inline_context() -> InlineFormattingContext {
objects: Vec::new(),
font_metrics: Vec::new(),
parent_strut: None,
+ uses_quirks_line_height: false,
root_includes_used_font_metrics: false,
style_parents: Vec::new(),
structural_boxes: Vec::new(),
diff --git a/moli-layout/src/world.rs b/moli-layout/src/world.rs
index ad9320bfc..54aa6e148 100644
--- a/moli-layout/src/world.rs
+++ b/moli-layout/src/world.rs
@@ -617,6 +617,7 @@ where
/// The root is the document element only for a complete document source.
/// Subtree and synthetic sources still use the same internal root slot.
pub(crate) root_is_document_element: bool,
+ pub(crate) quirks_mode: style::context::QuirksMode,
pub(crate) viewport_scroll_policy: ViewportScrollPolicy,
pub(crate) viewport_layout: ViewportLayoutState,
pub(crate) css_image_references: Vec<LayoutCssImageReference<N>>,
@@ -640,6 +641,7 @@ where
display_contents_mapping: HashMap::new(),
root: LayoutBoxId::from_index(0),
root_is_document_element,
+ quirks_mode: style::context::QuirksMode::NoQuirks,
viewport_scroll_policy: ViewportScrollPolicy::default(),
viewport_layout: ViewportLayoutState::default(),
css_image_references: Vec::new(),
diff --git a/moli-renderer-v8/src/layout_renderer/source_view.rs b/moli-renderer-v8/src/layout_renderer/source_view.rs
index 1e9a0d535..2d26db0fa 100644
--- a/moli-renderer-v8/src/layout_renderer/source_view.rs
+++ b/moli-renderer-v8/src/layout_renderer/source_view.rs
@@ -65,6 +65,15 @@ impl LayoutSource for NativeLayoutSourceView<'_> {
}) == Some(self.root)
}
+ fn quirks_mode(&self) -> style::context::QuirksMode {
+ self.document
+ .and_then(|document| self.host().node(document))
+ .and_then(Node::as_document)
+ .map_or(style::context::QuirksMode::NoQuirks, |document| {
+ document.quirks_mode()
+ })
+ }
+
fn disables_viewport_user_scrolling(&self) -> bool {
if !self.root_is_document_element() {
return false;
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/frame_geometry_and_input.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/frame_geometry_and_input.rs
index fd82eaf42..cd5b78394 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/frame_geometry_and_input.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/frame_geometry_and_input.rs
@@ -291,6 +291,612 @@ fn transformed_constrained_iframe_routes_hover_click_and_wheel_in_child_coordina
"800|800"
);
}
+#[test]
+fn iframe_line_height_uses_its_own_document_quirks_mode() {
+ for parent_doctype in ["", "<!doctype html>"] {
+ for (doctype, quirks) in [
+ ("", true),
+ (
+ r#"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">"#,
+ true,
+ ),
+ ("<!doctype html>", false),
+ ] {
+ let mut vm = new_parsed_test_vm(
+ "https://iframe-line-height-mode.test/",
+ &format!(
+ "{parent_doctype}<iframe id=frame scrolling=auto style='width:100px;height:150px;border:0'></iframe>"
+ ),
+ );
+ let child_markup = format!(
+ "{doctype}<body style='margin:0'><iframe id=inner scrolling=no style='width:100%;height:150px;border:0'></iframe>"
+ );
+ vm.eval(&format!(
+ "globalThis.child=frame.contentDocument;child.open();child.write({});child.close()",
+ serde_json::to_string(&child_markup).unwrap()
+ ))
+ .unwrap();
+ let query = r#"JSON.stringify([
+ child.body.getBoundingClientRect().height,
+ child.getElementById('inner').getBoundingClientRect().width
+ ])"#;
+ let first = vm.eval(query).unwrap();
+ let metrics: Vec<f64> = serde_json::from_str(&first).unwrap();
+ if quirks {
+ assert_eq!(metrics, [150.0, 100.0], "{parent_doctype} / {doctype}");
+ } else {
+ assert!(
+ metrics[0] > 150.0,
+ "standards retains font descent: {metrics:?}"
+ );
+ assert_eq!(metrics[1], 85.0, "standards overflow needs a scrollbar");
+ }
+ publish_layout_for_test(&mut vm);
+ assert_eq!(
+ vm.eval(query).unwrap(),
+ first,
+ "paint must use the same line height"
+ );
+ }
+ }
+}
+
+#[test]
+fn quirks_block_line_height_preserves_text_and_atomic_alignment() {
+ for (doctype, quirks) in [
+ ("", true),
+ (
+ r#"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">"#,
+ true,
+ ),
+ ("<!doctype html>", false),
+ ] {
+ let mut vm = new_parsed_test_vm(
+ "https://quirks-block-line-height.test/",
+ &format!(
+ r#"{doctype}<style>
+ .line {{ font:50px/80px monospace; width:300px }}
+ .atomic {{ display:inline-block; width:10px; height:20px }}
+ </style>
+ <div id=only class=line><span class=atomic></span></div>
+ <div id=text class=line>x<span class=atomic></span></div>
+ <div id=smaller class=line><span style="font-size:10px;line-height:10px">x</span></div>
+ <div id=aligned class=line><span class=atomic style="vertical-align:top"></span></div>
+ <div id=spaced class=line> <span class=atomic></span> </div>"#
+ ),
+ );
+ let query = r#"JSON.stringify(['only','text','smaller','aligned','spaced'].map(id => document.getElementById(id).getBoundingClientRect().height))"#;
+ let expected = if quirks {
+ "[20,80,10,20,20]"
+ } else {
+ "[80,80,80,80,80]"
+ };
+ assert_eq!(vm.eval(query).unwrap(), expected, "{doctype}");
+ publish_layout_for_test(&mut vm);
+ assert_eq!(vm.eval(query).unwrap(), expected, "paint: {doctype}");
+ }
+}
+
+fn check_inline_line_height_modes(cases: &[(&str, &str, f64, f64)]) {
+ for (doctype, quirks) in [
+ ("", true),
+ (
+ r#"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">"#,
+ true,
+ ),
+ ("<!doctype html>", false),
+ ] {
+ let mut markup = format!(
+ r#"{doctype}<style>.line{{font:50px/80px monospace;width:300px}}.atom{{display:inline-block;width:10px;height:20px}}em,i{{font-style:normal}}</style>"#
+ );
+ for (id, content, _, _) in cases {
+ markup.push_str(&format!(r#"<div class=line id="{id}">{content}</div>"#));
+ }
+ let mut vm = new_parsed_test_vm("https://quirks-empty-inline.test/", &markup);
+ let query = "JSON.stringify(Array.from(document.querySelectorAll('.line'), e=>e.getBoundingClientRect().height))";
+ let result = vm.eval(query).unwrap();
+ let heights: Vec<f64> = serde_json::from_str(&result).unwrap();
+ for ((id, _, quirks_height, standards_height), actual) in cases.iter().zip(heights) {
+ assert_eq!(
+ actual,
+ if quirks {
+ *quirks_height
+ } else {
+ *standards_height
+ },
+ "{doctype} / {id}: {result}"
+ );
+ }
+ publish_layout_for_test(&mut vm);
+ assert_eq!(
+ vm.eval(query).unwrap(),
+ result,
+ "publication uses the same line height rules"
+ );
+ }
+}
+
+#[test]
+fn quirks_empty_inline_line_height_uses_text_and_fragment_edges() {
+ check_inline_line_height_modes(&[
+ ("direct", r#"<i class="atom"></i>"#, 20.0, 80.0),
+ (
+ "wrapped",
+ r#"<span><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "nested",
+ r#"<span><em><i class="atom"></i></em></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "collapsed",
+ "<span> \n <i class=\"atom\"></i> \n </span>",
+ 20.0,
+ 80.0,
+ ),
+ (
+ "small_descendant_text",
+ r#"<span><em style="font:10px/10px monospace">x</em></span>"#,
+ 10.0,
+ 80.0,
+ ),
+ (
+ "own_text",
+ r#"<span>x<i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "between_atoms",
+ r#"<span><i class="atom"></i> <i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "preserved_space",
+ r#"<span style="white-space:pre"> <i class="atom"></i> </span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "preserved_break",
+ r#"<span style="white-space:pre-line">
+</span>"#,
+ 80.0,
+ 80.0,
+ ),
+ ("br", r#"<span><br></span>"#, 80.0, 80.0),
+ (
+ "atomic_text",
+ r#"<span><i style="display:inline-block;font:10px/10px monospace">x</i></span>"#,
+ 10.0,
+ 80.0,
+ ),
+ (
+ "empty_next_to_atom",
+ r#"<span></span><i class="atom"></i>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "bidi",
+ r#"<span dir=rtl><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "nested_small_atom",
+ r#"<span style="font:100px/160px monospace"><em style="font:10px/10px monospace"><i class="atom"></i></em></span>"#,
+ 20.0,
+ 160.0,
+ ),
+ ]);
+}
+
+#[test]
+fn quirks_empty_inline_line_height_distinguishes_border_padding_and_margin() {
+ check_inline_line_height_modes(&[
+ (
+ "margin_only",
+ r#"<span style="margin:1px"></span>"#,
+ 0.0,
+ 80.0,
+ ),
+ (
+ "padding_block",
+ r#"<span style="padding:7px 0"><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "border_block",
+ r#"<span style="border-style:solid;border-width:7px 0"><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "padding_left",
+ r#"<span style="padding-left:1px"><i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "padding_right",
+ r#"<span style="padding-right:1px"><i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "border_left",
+ r#"<span style="border-left:1px solid"><i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "border_right",
+ r#"<span style="border-right:1px solid"><i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "hidden_border",
+ r#"<span style="border-left:5px hidden"><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "none_border",
+ r#"<span style="border-left:5px none"><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "cancelled_edge",
+ r#"<span style="padding-left:1px;margin-left:-1px"><i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "padding_zero_percent",
+ r#"<span style="padding-left:0%"><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "padding_percent",
+ r#"<span style="padding-left:1%"><i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "margin_next_to_atom",
+ r#"<span style="margin-left:1px"></span><i class="atom"></i>"#,
+ 20.0,
+ 80.0,
+ ),
+ ]);
+}
+
+#[test]
+fn quirks_empty_inline_line_height_is_resolved_per_line() {
+ check_inline_line_height_modes(&[
+ (
+ "multiple_lines",
+ r#"<span><i class="atom"></i><br><i class="atom"></i></span>"#,
+ 40.0,
+ 160.0,
+ ),
+ (
+ "text_first_line",
+ r#"<span>x<br><i class="atom"></i></span>"#,
+ 100.0,
+ 160.0,
+ ),
+ (
+ "text_last_line",
+ r#"<span><i class="atom"></i><br>x</span>"#,
+ 100.0,
+ 160.0,
+ ),
+ (
+ "border_multiple_lines",
+ r#"<span style="border-left:1px solid"><i class="atom"></i><br><i class="atom"></i></span>"#,
+ 100.0,
+ 160.0,
+ ),
+ (
+ "space_at_break",
+ r#"<span><i class="atom"></i> <br><i class="atom"></i></span>"#,
+ 40.0,
+ 160.0,
+ ),
+ (
+ "text_elsewhere",
+ r#"<span>x</span><br><span><i class="atom"></i></span>"#,
+ 100.0,
+ 160.0,
+ ),
+ (
+ "middle_atom",
+ r#"<span><i class="atom" style="vertical-align:middle"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "top_wrapper",
+ r#"<span style="vertical-align:top"><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "bottom_wrapper",
+ r#"<span style="vertical-align:bottom"><i class="atom"></i></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ ]);
+}
+
+#[test]
+fn quirks_empty_inline_line_height_preserves_forced_empty_lines() {
+ check_inline_line_height_modes(&[
+ (
+ "large_preserved_break",
+ r#"<span style="font:20px/100px monospace;white-space:pre-line">
+</span>"#,
+ 100.0,
+ 100.0,
+ ),
+ (
+ "large_br",
+ r#"<span style="font:20px/100px monospace"><br></span>"#,
+ 100.0,
+ 100.0,
+ ),
+ ("root_br", r#"<br>"#, 80.0, 80.0),
+ (
+ "large_nested_br",
+ r#"<span style="font:100px/160px monospace"><em style="font:10px/10px monospace"><br></em></span>"#,
+ 10.0,
+ 160.0,
+ ),
+ (
+ "br_own_font",
+ r#"<br style="font:20px/100px monospace">"#,
+ 100.0,
+ 80.0,
+ ),
+ (
+ "atom_large_br",
+ r#"<span style="font:20px/100px monospace"><i class=atom></i><br></span>"#,
+ 20.0,
+ 100.0,
+ ),
+ (
+ "atom_large_preserved_break",
+ r#"<span style="font:20px/100px monospace;white-space:pre-line"><i class=atom></i>
+</span>"#,
+ 20.0,
+ 100.0,
+ ),
+ (
+ "atom_small_br",
+ r#"<i class=atom></i><br style="font:10px/10px monospace">"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "margin_then_br",
+ r#"<span style="margin-left:1px"></span><br style="font:20px/100px monospace">"#,
+ 100.0,
+ 80.0,
+ ),
+ (
+ "padding_then_br",
+ r#"<span style="padding-left:1px"></span><br style="font:20px/100px monospace">"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "padding_with_br",
+ r#"<span style="padding-left:1px"><br style="font:20px/100px monospace"></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "wrapped_auto_break",
+ r#"<span><i class="atom" style="width:300px"></i> <i class="atom" style="width:300px"></i></span>"#,
+ 40.0,
+ 160.0,
+ ),
+ (
+ "collapsed_large_trailing_space",
+ r#"<i class="atom"></i><span style="font:100px/160px monospace"> </span>"#,
+ 20.0,
+ 160.0,
+ ),
+ (
+ "border_empty",
+ r#"<span style="border-right:1px solid"></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ ]);
+}
+
+#[test]
+fn quirks_empty_inline_line_height_collapses_spaces_after_wrapping() {
+ check_inline_line_height_modes(&[
+ (
+ "wrapped_auto_break",
+ r#"<span><i class="atom" style="width:300px"></i> <i class="atom" style="width:300px"></i></span>"#,
+ 40.0,
+ 160.0,
+ ),
+ (
+ "wrapped_auto_break_preserved",
+ r#"<span style="white-space:pre-wrap"><i class="atom" style="width:300px"></i> <i class="atom" style="width:300px"></i></span>"#,
+ 100.0,
+ 160.0,
+ ),
+ (
+ "wrapped_auto_break_rtl",
+ r#"<span dir=rtl><i class="atom" style="width:300px"></i> <i class="atom" style="width:300px"></i></span>"#,
+ 40.0,
+ 160.0,
+ ),
+ (
+ "wrapped_auto_break_space_font",
+ r#"<span><i class="atom" style="width:300px"></i><em style="font:100px/160px monospace"> </em><i class="atom" style="width:300px"></i></span>"#,
+ 40.0,
+ 240.0,
+ ),
+ (
+ "wrapped_space_font_then_text",
+ r#"<span><i class="atom" style="width:300px"></i><em style="font:100px/160px monospace"> </em>x</span>"#,
+ 100.0,
+ 240.0,
+ ),
+ (
+ "wrapped_space_font_then_zero_text",
+ r#"<span><i class="atom" style="width:300px"></i><em style="font:100px/160px monospace"> </em><b style="font-size:0;line-height:0">x</b></span>"#,
+ 20.0,
+ 240.0,
+ ),
+ ]);
+}
+
+#[test]
+fn quirks_nested_break_line_height_uses_its_own_inline_box() {
+ check_inline_line_height_modes(&[
+ (
+ "nested_br_padding",
+ r#"<span style="font:10px/10px monospace;padding-left:1px"><span style="font:50px/80px monospace"><br></span></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "nested_br_border",
+ r#"<span style="font:10px/10px monospace;border-right:1px solid"><span style="font:50px/80px monospace"><br></span></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "nested_br_text",
+ r#"<span style="font:10px/10px monospace">x<span style="font:50px/80px monospace"><br></span></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "nested_br_atom_sibling",
+ r#"<i class="atom"></i><span><br></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "nested_br_atom_in_parent",
+ r#"<span><i class="atom"></i><span><br></span></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "nested_br_atom_in_same_box",
+ r#"<span><i class="atom"></i><br></span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "nested_br_descendant_text",
+ r#"<span style="font:100px/160px monospace"><em style="font:10px/10px monospace">x</em><br></span>"#,
+ 10.0,
+ 160.0,
+ ),
+ (
+ "nested_br_own_small_text",
+ r#"<span style="font:10px/10px monospace">x<br style="font:50px/80px monospace"></span>"#,
+ 10.0,
+ 80.0,
+ ),
+ (
+ "nested_preserved_break",
+ r#"<span style="font:10px/10px monospace;padding-left:1px"><span style="font:50px/80px monospace;white-space:pre-line">
+</span></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ ]);
+}
+
+#[test]
+fn quirks_wrapped_whitespace_line_height_counts_only_surviving_spaces() {
+ check_inline_line_height_modes(&[
+ (
+ "wrapped_space",
+ r#"<i class="atom"></i><span> </span><i class="atom"></i>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "nested_wrapped_space",
+ r#"<i class="atom"></i><span><em> </em></span><i class="atom"></i>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "wrapped_space_large_font",
+ r#"<i class="atom"></i><span style="font:100px/160px monospace"> </span><i class="atom"></i>"#,
+ 160.0,
+ 160.0,
+ ),
+ (
+ "wrapped_space_small_font",
+ r#"<i class="atom"></i><span style="font:10px/10px monospace"> </span><i class="atom"></i>"#,
+ 22.0,
+ 80.0,
+ ),
+ (
+ "wrapped_space_rtl",
+ r#"<span dir="rtl"><i class="atom"></i><span> </span><i class="atom"></i></span>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "wrapped_space_preserved",
+ r#"<i class="atom"></i><span style="white-space:pre"> </span><i class="atom"></i>"#,
+ 80.0,
+ 80.0,
+ ),
+ (
+ "wrapped_space_leading",
+ r#"<span> </span><i class="atom"></i>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "wrapped_space_trailing",
+ r#"<i class="atom"></i><span> </span>"#,
+ 20.0,
+ 80.0,
+ ),
+ (
+ "wrapped_space_at_break",
+ r#"<i class="atom"></i><span> </span><br><i class="atom"></i>"#,
+ 40.0,
+ 160.0,
+ ),
+ (
+ "wrapped_space_after_wrap",
+ r#"<i class="atom" style="width:300px"></i><span> </span><i class="atom" style="width:300px"></i>"#,
+ 40.0,
+ 160.0,
+ ),
+ ]);
+}
+
#[test]
fn inline_wrapped_whitespace_preserves_sibling_spacing() {
for doctype in [
@@ -326,6 +932,404 @@ fn inline_wrapped_whitespace_preserves_sibling_spacing() {
}
}
+#[test]
+fn inline_closing_edges_after_forced_breaks_contribute_to_their_own_fragment() {
+ let cases = [
+ (
+ "left_border",
+ r#"<span style="border-left:1px solid"><i class=atom></i><br></span><br>"#,
+ 160.0,
+ 160.0,
+ true,
+ ),
+ (
+ "right_border",
+ r#"<span style="border-right:1px solid"><i class=atom></i><br></span><br>"#,
+ 160.0,
+ 160.0,
+ true,
+ ),
+ (
+ "right_padding",
+ r#"<span style="padding-right:1px"><i class=atom></i><br></span><br>"#,
+ 160.0,
+ 160.0,
+ true,
+ ),
+ (
+ "terminal_break",
+ r#"<span style="border-right:1px solid"><i class=atom></i><br></span>"#,
+ 80.0,
+ 80.0,
+ true,
+ ),
+ (
+ "preserved_break",
+ "<span style=\"border-right:1px solid;white-space:pre\"><i class=atom></i>\n</span><br>",
+ 160.0,
+ 160.0,
+ true,
+ ),
+ (
+ "nested_closing_edges",
+ r#"<span style="border-right:1px solid"><em><i class=atom></i><br></em></span><br>"#,
+ 160.0,
+ 160.0,
+ true,
+ ),
+ (
+ "nested_bidi_closing_edges",
+ r#"<span style="padding-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><br>"#,
+ 100.0,
+ 160.0,
+ false,
+ ),
+ (
+ "nested_bidi_terminal_padding",
+ r#"<span style="padding-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>"#,
+ 100.0,
+ 160.0,
+ false,
+ ),
+ (
+ "nested_bidi_terminal_border",
+ r#"<span style="border-right:1px solid"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>"#,
+ 100.0,
+ 160.0,
+ false,
+ ),
+ (
+ "nested_bidi_terminal_margin",
+ r#"<span style="margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>"#,
+ 20.0,
+ 160.0,
+ false,
+ ),
+ (
+ "multiple_fragments",
+ r#"<span style="border-right:1px solid"><i class=atom></i><br><i class=atom></i><br></span><br>"#,
+ 180.0,
+ 240.0,
+ false,
+ ),
+ (
+ "opening_edge_after_break",
+ r#"<span style="border-right:1px solid"><i class=atom></i><br><em></em></span><br>"#,
+ 100.0,
+ 160.0,
+ false,
+ ),
+ (
+ "undecorated",
+ r#"<span><i class=atom></i><br></span><br>"#,
+ 100.0,
+ 160.0,
+ false,
+ ),
+ (
+ "right_margin",
+ r#"<span style="margin-right:1px"><i class=atom></i><br></span><br>"#,
+ 100.0,
+ 160.0,
+ false,
+ ),
+ ];
+ for (doctype, quirks) in [
+ ("", true),
+ (
+ r#"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">"#,
+ true,
+ ),
+ ("<!doctype html>", false),
+ ] {
+ let mut markup = format!(
+ r#"{doctype}<style>.line{{font:50px/80px monospace;width:300px}}.atom{{display:inline-block;width:10px;height:20px}}em,i{{font-style:normal}}</style>"#
+ );
+ for (id, content, ..) in &cases {
+ markup.push_str(&format!(r#"<div class=line id="{id}">{content}</div>"#));
+ }
+ let mut vm = new_parsed_test_vm("https://inline-closing-edge.test/", &markup);
+ let query = r#"JSON.stringify(Array.from(document.querySelectorAll('.line'), e => {
+ const line = e.getBoundingClientRect();
+ const atom = e.querySelector('.atom').getBoundingClientRect();
+ return [line.height, atom.top - line.top];
+ }))"#;
+ let result = vm.eval(query).unwrap();
+ let geometries: Vec<[f64; 2]> = serde_json::from_str(&result).unwrap();
+ let decorated_atom_top = geometries[0][1];
+ for ((id, _, quirks_height, standards_height, decorated), actual) in
+ cases.iter().zip(geometries)
+ {
+ assert_eq!(
+ actual[0],
+ if quirks {
+ *quirks_height
+ } else {
+ *standards_height
+ },
+ "height: {doctype} / {id}: {result}"
+ );
+ assert_eq!(
+ actual[1],
+ if !quirks || *decorated {
+ decorated_atom_top
+ } else {
+ 0.0
+ },
+ "atom top: {doctype} / {id}"
+ );
+ }
+ for (id, fragments) in [
+ ("right_border", 1),
+ ("right_padding", 1),
+ ("terminal_break", 1),
+ ("nested_bidi_closing_edges", 2),
+ ("nested_bidi_terminal_padding", 2),
+ ("nested_bidi_terminal_border", 2),
+ ("nested_bidi_terminal_margin", 2),
+ ] {
+ assert_eq!(
+ vm.eval(&format!(
+ "document.getElementById({id:?}).querySelector('span').getClientRects().length"
+ ))
+ .unwrap(),
+ fragments.to_string(),
+ "closing edge fragment count: {doctype} / {id}"
+ );
+ }
+ let margin_fragment_query = r#"(() => {
+ const rects = document.getElementById('nested_bidi_terminal_margin').querySelector('span').getClientRects();
+ return rects[1].height / rects[0].height;
+ })()"#;
+ let margin_fragment_ratio = vm.eval(margin_fragment_query).unwrap();
+ assert_eq!(margin_fragment_ratio, if quirks { "0" } else { "1" });
+ publish_layout_for_test(&mut vm);
+ assert_eq!(vm.eval(query).unwrap(), result, "paint: {doctype}");
+ assert_eq!(
+ vm.eval(margin_fragment_query).unwrap(),
+ margin_fragment_ratio,
+ "margin fragment paint: {doctype}"
+ );
+ }
+}
+
+#[test]
+fn inline_used_closing_edges_preserve_standards_struts_and_ancestors() {
+ check_inline_closing_fragment_modes(&[
+ (
+ "margin_tall",
+ r#"<span style="line-height:160px;margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>"#,
+ 20.0,
+ 320.0,
+ 0.0,
+ ),
+ (
+ "padding_tall",
+ r#"<span style="line-height:160px;padding-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>"#,
+ 180.0,
+ 320.0,
+ 1.0,
+ ),
+ (
+ "border_tall",
+ r#"<span style="line-height:160px;border-right:1px solid"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>"#,
+ 180.0,
+ 320.0,
+ 1.0,
+ ),
+ (
+ "margin_nested",
+ r#"<span style="line-height:200px"><span style="line-height:100px;margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span></span>"#,
+ 20.0,
+ 400.0,
+ 0.0,
+ ),
+ ]);
+}
+
+#[test]
+fn standards_closing_inline_struts_do_not_depend_on_edge_sizes() {
+ check_inline_line_height_modes(&[
+ (
+ "plain_tall_text",
+ r#"<span style="line-height:160px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>x"#,
+ 100.0,
+ 320.0,
+ ),
+ (
+ "plain_tall_br",
+ r#"<span style="line-height:160px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><br>"#,
+ 100.0,
+ 320.0,
+ ),
+ (
+ "plain_tall_terminal",
+ r#"<span style="line-height:160px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>"#,
+ 20.0,
+ 160.0,
+ ),
+ (
+ "margin_tall_text",
+ r#"<span style="line-height:160px;margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>x"#,
+ 100.0,
+ 320.0,
+ ),
+ (
+ "plain_nested_text",
+ r#"<span style="line-height:200px"><span style="line-height:100px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span></span>x"#,
+ 100.0,
+ 400.0,
+ ),
+ (
+ "plain_nested_br",
+ r#"<span style="line-height:200px"><span style="line-height:100px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span></span><br>"#,
+ 100.0,
+ 400.0,
+ ),
+ (
+ "plain_nested_terminal",
+ r#"<span style="line-height:200px"><span style="line-height:100px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span></span>"#,
+ 20.0,
+ 200.0,
+ ),
+ (
+ "plain_tall_atom",
+ r#"<span style="line-height:160px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><i class=atom></i>"#,
+ 40.0,
+ 320.0,
+ ),
+ (
+ "plain_tall_zero_atom",
+ r#"<span style="line-height:160px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><i class=atom style="height:0"></i>"#,
+ 20.0,
+ 320.0,
+ ),
+ (
+ "plain_tall_zero_text",
+ r#"<span style="line-height:160px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><b style="font-size:0;line-height:0">x</b>"#,
+ 20.0,
+ 320.0,
+ ),
+ (
+ "plain_tall_zero_br",
+ r#"<span style="line-height:160px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><br style="line-height:0">"#,
+ 20.0,
+ 320.0,
+ ),
+ ]);
+}
+
+#[test]
+fn quirks_closing_fragment_font_boxes_follow_line_content() {
+ check_inline_closing_fragment_modes(&[
+ (
+ "margin_br",
+ r#"<span style="margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><br>"#,
+ 100.0,
+ 160.0,
+ 1.0,
+ ),
+ (
+ "margin_text",
+ r#"<span style="margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span>x"#,
+ 100.0,
+ 160.0,
+ 1.0,
+ ),
+ (
+ "margin_atom",
+ r#"<span style="margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><i class=atom></i>"#,
+ 40.0,
+ 160.0,
+ 1.0,
+ ),
+ (
+ "margin_zero_atom",
+ r#"<span style="margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><i class=atom style="height:0"></i>"#,
+ 20.0,
+ 160.0,
+ 1.0,
+ ),
+ (
+ "margin_zero_text",
+ r#"<span style="margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><b style="font-size:0;line-height:0">x</b>"#,
+ 20.0,
+ 160.0,
+ 1.0,
+ ),
+ (
+ "margin_zero_br",
+ r#"<span style="margin-right:1px"><em style="unicode-bidi:embed;direction:rtl"><i class=atom></i><br></em></span><br style="line-height:0">"#,
+ 20.0,
+ 160.0,
+ 1.0,
+ ),
+ ]);
+}
+
+fn check_inline_closing_fragment_modes(cases: &[(&str, &str, f64, f64, f64)]) {
+ for (doctype, quirks) in [
+ ("", true),
+ (
+ r#"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">"#,
+ true,
+ ),
+ ("<!doctype html>", false),
+ ] {
+ let mut markup = format!(
+ r#"{doctype}<style>.line{{font:50px/80px monospace;width:300px}}.atom{{display:inline-block;width:10px;height:20px}}em,i{{font-style:normal}}</style>"#
+ );
+ for (id, content, ..) in cases {
+ markup.push_str(&format!(r#"<div class=line id="{id}">{content}</div>"#));
+ }
+ let mut vm = new_parsed_test_vm("https://inline-closing-fragment.test/", &markup);
+ let query = r#"JSON.stringify(Array.from(document.querySelectorAll('.line'), e => {
+ const rects = e.querySelector('span').getClientRects();
+ return [e.getBoundingClientRect().height, rects.length, rects[1].height / rects[0].height];
+ }))"#;
+ let result = vm.eval(query).unwrap();
+ let geometries: Vec<[f64; 3]> = serde_json::from_str(&result).unwrap();
+ for ((id, _, quirks_height, standards_height, quirks_ratio), actual) in
+ cases.iter().zip(geometries)
+ {
+ assert_eq!(
+ actual,
+ [
+ if quirks {
+ *quirks_height
+ } else {
+ *standards_height
+ },
+ 2.0,
+ if quirks { *quirks_ratio } else { 1.0 },
+ ],
+ "closing fragment: {doctype} / {id}: {result}"
+ );
+ }
+ publish_layout_for_test(&mut vm);
+ assert_eq!(vm.eval(query).unwrap(), result, "paint: {doctype}");
+ }
+}
+
+#[test]
+fn inline_end_border_preserves_tall_atomic_content() {
+ for doctype in ["", "<!doctype html>"] {
+ let mut vm = new_parsed_test_vm(
+ "https://inline-end-border-height.test/",
+ &format!(
+ r#"{doctype}<style>.line{{font:50px/80px monospace}}.atom{{display:inline-block;width:10px;height:200px}}</style><div class=line><span style="border-left:1px solid"><i class=atom></i></span></div><div class=line><span style="border-right:1px solid"><i class=atom></i></span></div>"#
+ ),
+ );
+ let result = vm.eval("JSON.stringify(Array.from(document.querySelectorAll('.line'), e=>e.getBoundingClientRect().height))").unwrap();
+ let heights: Vec<f64> = serde_json::from_str(&result).unwrap();
+ assert!(heights[0] >= 200.0, "{result}");
+ assert_eq!(
+ heights[0], heights[1],
+ "an end edge must retain earlier content bounds"
+ );
+ }
+}
+
#[test]
fn iframe_scrolling_attribute_suppresses_only_viewport_scrollbars() {
for (scrolling, suppressed) in [