Skip to content

armgit / moli

Public Imported from GitHub
0

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

perf(layout): localize overflow feedback projection

ldm06c4103eefc56
diff --git a/moli-layout/src/inline.rs b/moli-layout/src/inline.rs
index 6a58509eb..e7307b625 100644
--- a/moli-layout/src/inline.rs
+++ b/moli-layout/src/inline.rs
@@ -324,6 +324,11 @@ pub(crate) fn build_inline_fragments(
layout: &Layout<TextBrush>,
line_placements: &[InlineLinePlacement],
) -> InlineFragments {
+ // Binary overlap lookup relies on both endpoints being monotonic. Validate
+ // each immutable normalization product once, rather than rescanning the
+ // complete maps for every visual glyph cluster in debug and test builds.
+ debug_assert!(output_ranges_are_monotonic(&context.text_units));
+ debug_assert!(output_ranges_are_monotonic(&context.source_map));
let mut fragments = InlineFragments::default();
let mut box_fragments = HashMap::<(usize, usize), FragmentAccumulator>::new();
let mut source_fragments = HashMap::<SourceFragmentKey, FragmentAccumulator>::new();
@@ -1377,15 +1382,21 @@ where
if target.is_empty() {
return &items[..0];
}
- debug_assert!(items.windows(2).all(|pair| {
- pair[0].output_range().start <= pair[1].output_range().start
- && pair[0].output_range().end <= pair[1].output_range().end
- }));
let start = items.partition_point(|item| item.output_range().end <= target.start);
let end = start + items[start..].partition_point(|item| item.output_range().start < target.end);
&items[start..end]
}
+fn output_ranges_are_monotonic<T>(items: &[T]) -> bool
+where
+ T: HasInlineOutputRange,
+{
+ items.windows(2).all(|pair| {
+ pair[0].output_range().start <= pair[1].output_range().start
+ && pair[0].output_range().end <= pair[1].output_range().end
+ })
+}
+
pub(crate) fn prepare_inline_contexts<N>(
world: &mut LayoutWorld<N>,
services: &mut DocumentLayoutServices,
@@ -2260,6 +2271,9 @@ mod tests {
source(2..5),
source(7..9),
];
+ assert!(output_ranges_are_monotonic(&entries));
+ assert!(!output_ranges_are_monotonic(&[source(1..3), source(0..4),]));
+ assert!(!output_ranges_are_monotonic(&[source(0..4), source(1..3),]));
let ranges = |query: Range<usize>| {
overlapping_output_ranges(&entries, &query)
.iter()
diff --git a/moli-layout/src/layout_tree/pass_result.rs b/moli-layout/src/layout_tree/pass_result.rs
index b6f3c0ace..0cbe9b7c2 100644
--- a/moli-layout/src/layout_tree/pass_result.rs
+++ b/moli-layout/src/layout_tree/pass_result.rs
@@ -52,6 +52,9 @@ pub struct LayoutPassMetrics {
/// Number of box-cache entries explicitly invalidated across automatic
/// scrollbar feedback iterations. Unchanged subtrees stay cacheable.
pub numeric_feedback_invalidated_node_count: usize,
+ /// Boxes whose local or descendant overflow was recomputed after the
+ /// initial linear overflow projection. Unaffected branches are excluded.
+ pub numeric_feedback_overflow_recomputed_node_count: usize,
pub box_count: usize,
pub fragment_count: usize,
/// Paint-order events considered for this capture before viewport culling.
diff --git a/moli-layout/src/lib.rs b/moli-layout/src/lib.rs
index 24716033a..e483f8233 100644
--- a/moli-layout/src/lib.rs
+++ b/moli-layout/src/lib.rs
@@ -21,6 +21,7 @@ mod layout_tree;
mod list;
mod normalize;
mod normalize_source;
+mod overflow;
mod paint;
mod pass;
mod positioned;
diff --git a/moli-layout/src/overflow.rs b/moli-layout/src/overflow.rs
new file mode 100644
index 000000000..9ed1897b9
--- /dev/null
+++ b/moli-layout/src/overflow.rs
@@ -0,0 +1,519 @@
+use std::{collections::VecDeque, fmt::Debug, hash::Hash};
+
+use crate::{
+ LayoutBoxId, LayoutPoint, LayoutRect, LayoutScrollbarAxis, LayoutTransform2D, LayoutViewport,
+ LayoutWorld, style::ResolvedLayoutTransform,
+};
+
+/// Geometry needed to resolve scrollable overflow and no other projection
+/// concern. Keeping this sidecar smaller than `OutputProjection` lets automatic
+/// scrollbar feedback converge without allocating sources, fragments, clips,
+/// paint order, diagnostics, or hit-test state on every numeric iteration.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct OverflowBoxGeometry {
+ pub(crate) border_box: LayoutRect,
+ pub(crate) padding_box: LayoutRect,
+ pub(crate) content_box: LayoutRect,
+ pub(crate) margin_box: LayoutRect,
+ pub(crate) resolved_transform: ResolvedLayoutTransform,
+ pub(crate) local_scrollport: LayoutRect,
+ pub(crate) vertical_gutter: f32,
+ pub(crate) vertical_leading_gutter: f32,
+ pub(crate) horizontal_gutter: f32,
+ pub(crate) horizontal_leading_gutter: f32,
+ local_overflow: LayoutRect,
+}
+
+/// One pass-local, incrementally refreshed scrollable-overflow projection.
+///
+/// The initial build touches each numeric box and overflow edge once. After a
+/// scrollbar changes layout, callers provide the boxes Taffy actually touched;
+/// a worklist expands only through their overflow ancestors. Unaffected local
+/// geometry and descendant aggregates remain reusable across feedback turns.
+pub(crate) struct OverflowProjection {
+ geometries: Vec<OverflowBoxGeometry>,
+ scrollable_overflow: Vec<LayoutRect>,
+ parents: Vec<Option<LayoutBoxId>>,
+ children: Vec<Vec<LayoutBoxId>>,
+ affected: Vec<bool>,
+ remaining_affected_children: Vec<usize>,
+}
+
+impl OverflowProjection {
+ pub(crate) fn new<N>(world: &LayoutWorld<N>, viewport: LayoutViewport) -> Self
+ where
+ N: Copy + Debug + Eq + Hash,
+ {
+ let count = world.boxes.len();
+ let geometries = (0..count)
+ .map(|index| project_box(world, viewport, LayoutBoxId::from_index(index)))
+ .collect::<Vec<_>>();
+ let parents = (0..count)
+ .map(|index| overflow_parent(world, LayoutBoxId::from_index(index)))
+ .collect::<Vec<_>>();
+ let mut children = vec![Vec::new(); count];
+ for (index, parent) in parents.iter().copied().enumerate() {
+ if let Some(parent) = parent {
+ children[parent.index()].push(LayoutBoxId::from_index(index));
+ }
+ }
+ let mut projection = Self {
+ scrollable_overflow: geometries
+ .iter()
+ .map(|geometry| geometry.local_overflow)
+ .collect(),
+ geometries,
+ parents,
+ children,
+ affected: vec![false; count],
+ remaining_affected_children: vec![0; count],
+ };
+ projection.resolve_all(world);
+ projection
+ }
+
+ pub(crate) fn len(&self) -> usize {
+ self.geometries.len()
+ }
+
+ pub(crate) fn geometry(&self, id: LayoutBoxId) -> OverflowBoxGeometry {
+ self.geometries[id.index()]
+ }
+
+ pub(crate) fn scrollable_overflow(&self, id: LayoutBoxId) -> LayoutRect {
+ self.scrollable_overflow[id.index()]
+ }
+
+ pub(crate) fn overflowing_axes<N>(
+ &self,
+ world: &LayoutWorld<N>,
+ id: LayoutBoxId,
+ ) -> (bool, bool)
+ where
+ N: Copy + Debug + Eq + Hash,
+ {
+ if !establishes_scroll_container(world, id) {
+ return (false, false);
+ }
+ let geometry = self.geometry(id);
+ let overflow = self.scrollable_overflow(id);
+ let horizontal_range = geometry
+ .local_scrollport
+ .width
+ .max((overflow.right() - geometry.local_scrollport.x).max(0.0))
+ - geometry.local_scrollport.width;
+ let vertical_range = geometry
+ .local_scrollport
+ .height
+ .max((overflow.bottom() - geometry.local_scrollport.y).max(0.0))
+ - geometry.local_scrollport.height;
+ (
+ horizontal_range > f32::EPSILON,
+ vertical_range > f32::EPSILON,
+ )
+ }
+
+ /// Reprojects the boxes changed by numeric layout and their overflow
+ /// ancestors. The returned identities are exactly the boxes whose current
+ /// overflow state may need another automatic-scrollbar admission check.
+ pub(crate) fn refresh<N>(
+ &mut self,
+ world: &LayoutWorld<N>,
+ viewport: LayoutViewport,
+ touched: &[LayoutBoxId],
+ ) -> Vec<LayoutBoxId>
+ where
+ N: Copy + Debug + Eq + Hash,
+ {
+ assert_eq!(self.geometries.len(), world.boxes.len());
+ let mut affected = Vec::new();
+ for touched in touched.iter().copied() {
+ let mut current = Some(touched);
+ while let Some(id) = current {
+ if self.affected[id.index()] {
+ break;
+ }
+ self.affected[id.index()] = true;
+ affected.push(id);
+ current = self.parents[id.index()];
+ }
+ }
+ if affected.is_empty() {
+ return affected;
+ }
+
+ for id in affected.iter().copied() {
+ let geometry = project_box(world, viewport, id);
+ self.geometries[id.index()] = geometry;
+ self.scrollable_overflow[id.index()] = geometry.local_overflow;
+ self.remaining_affected_children[id.index()] = self.children[id.index()]
+ .iter()
+ .filter(|child| self.affected[child.index()])
+ .count();
+ }
+
+ let mut ready = affected
+ .iter()
+ .copied()
+ .filter(|id| self.remaining_affected_children[id.index()] == 0)
+ .collect::<VecDeque<_>>();
+ let mut resolved = 0usize;
+ while let Some(id) = ready.pop_front() {
+ self.resolve_one(world, id);
+ resolved = resolved.saturating_add(1);
+ if let Some(parent) = self.parents[id.index()]
+ && self.affected[parent.index()]
+ {
+ let remaining = &mut self.remaining_affected_children[parent.index()];
+ *remaining = remaining
+ .checked_sub(1)
+ .expect("overflow worklist child count underflowed");
+ if *remaining == 0 {
+ ready.push_back(parent);
+ }
+ }
+ }
+ assert_eq!(
+ resolved,
+ affected.len(),
+ "overflow dependencies must form an acyclic forest"
+ );
+ for id in affected.iter().copied() {
+ self.affected[id.index()] = false;
+ self.remaining_affected_children[id.index()] = 0;
+ }
+ affected
+ }
+
+ fn resolve_all<N>(&mut self, world: &LayoutWorld<N>)
+ where
+ N: Copy + Debug + Eq + Hash,
+ {
+ let mut remaining_children = self.children.iter().map(Vec::len).collect::<Vec<_>>();
+ let mut ready = remaining_children
+ .iter()
+ .enumerate()
+ .filter_map(|(index, remaining)| {
+ (*remaining == 0).then_some(LayoutBoxId::from_index(index))
+ })
+ .collect::<VecDeque<_>>();
+ let mut resolved = 0usize;
+ while let Some(id) = ready.pop_front() {
+ self.resolve_one(world, id);
+ resolved = resolved.saturating_add(1);
+ if let Some(parent) = self.parents[id.index()] {
+ let remaining = &mut remaining_children[parent.index()];
+ *remaining = remaining
+ .checked_sub(1)
+ .expect("overflow child count underflowed");
+ if *remaining == 0 {
+ ready.push_back(parent);
+ }
+ }
+ }
+ assert_eq!(
+ resolved,
+ self.geometries.len(),
+ "overflow dependencies must form an acyclic forest"
+ );
+ }
+
+ fn resolve_one<N>(&mut self, world: &LayoutWorld<N>, id: LayoutBoxId)
+ where
+ N: Copy + Debug + Eq + Hash,
+ {
+ let mut overflow = self.geometries[id.index()].local_overflow;
+ for child in self.children[id.index()].iter().copied() {
+ overflow = overflow.union(self.child_contribution(world, child));
+ }
+ self.scrollable_overflow[id.index()] = overflow;
+ }
+
+ fn child_contribution<N>(&self, world: &LayoutWorld<N>, child: LayoutBoxId) -> LayoutRect
+ where
+ N: Copy + Debug + Eq + Hash,
+ {
+ let geometry = self.geometries[child.index()];
+ let visual_overflow = if clips_overflow(world, child) {
+ geometry.border_box
+ } else {
+ self.scrollable_overflow[child.index()]
+ };
+ let location = world.boxes[child.index()].final_layout.location;
+ let layout_translation = LayoutTransform2D::translation(location.x, location.y);
+ let local_to_parent = layout_translation.concatenate(geometry.resolved_transform.transform);
+ local_to_parent
+ .map_rect(visual_overflow)
+ .bounding_rect()
+ .union(
+ layout_translation
+ .map_rect(geometry.margin_box)
+ .bounding_rect(),
+ )
+ }
+}
+
+fn overflow_parent<N>(world: &LayoutWorld<N>, id: LayoutBoxId) -> Option<LayoutBoxId>
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ if id == world.root || world.boxes[id.index()].style.is_fixed_positioned() {
+ return None;
+ }
+ world.boxes[id.index()].layout_parent.or(Some(world.root))
+}
+
+fn project_box<N>(
+ world: &LayoutWorld<N>,
+ viewport: LayoutViewport,
+ id: LayoutBoxId,
+) -> OverflowBoxGeometry
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ let layout_box = &world.boxes[id.index()];
+ let layout = layout_box.final_layout;
+ let is_root = id == world.root;
+ let border_box = LayoutRect::new(
+ 0.0,
+ 0.0,
+ layout.size.width.max(0.0),
+ layout.size.height.max(0.0),
+ );
+ let padding_box = inset_rect(
+ border_box,
+ layout.border.top,
+ layout.border.right,
+ layout.border.bottom,
+ layout.border.left,
+ );
+ let vertical_gutter = scrollbar_gutter_thickness(world, id, LayoutScrollbarAxis::Vertical);
+ let vertical_leading_gutter =
+ scrollbar_leading_gutter_thickness(world, id, LayoutScrollbarAxis::Vertical);
+ let horizontal_gutter = scrollbar_gutter_thickness(world, id, LayoutScrollbarAxis::Horizontal);
+ let horizontal_leading_gutter =
+ scrollbar_leading_gutter_thickness(world, id, LayoutScrollbarAxis::Horizontal);
+ let mut content_box = inset_rect(
+ padding_box,
+ layout.padding.top,
+ layout.padding.right,
+ layout.padding.bottom,
+ layout.padding.left,
+ );
+ if !is_root {
+ content_box.width = (content_box.width - vertical_gutter).max(0.0);
+ content_box.height = (content_box.height - horizontal_gutter).max(0.0);
+ content_box.x += vertical_leading_gutter;
+ content_box.y += horizontal_leading_gutter;
+ }
+ let margin_box = outset_rect(
+ border_box,
+ layout.margin.top,
+ layout.margin.right,
+ layout.margin.bottom,
+ layout.margin.left,
+ );
+ let resolved_transform = layout_box
+ .style
+ .resolved_2d_transform(border_box.width, border_box.height);
+ let local_scrollport = scrollport_for_box(
+ is_root,
+ viewport,
+ padding_box,
+ vertical_gutter,
+ vertical_leading_gutter,
+ horizontal_gutter,
+ horizontal_leading_gutter,
+ );
+ let mut local_overflow = LayoutRect::new(
+ local_scrollport.x,
+ local_scrollport.y,
+ local_scrollport
+ .width
+ .max(layout.content_size.width)
+ .max(0.0),
+ local_scrollport
+ .height
+ .max(layout.content_size.height)
+ .max(0.0),
+ );
+ if is_root {
+ local_overflow = local_overflow.union(padding_box);
+ }
+ if let Some(context) = layout_box.inline_layout.as_ref() {
+ let origin = LayoutPoint::new(
+ layout.border.left
+ + layout.padding.left
+ + if is_root {
+ 0.0
+ } else {
+ vertical_leading_gutter
+ },
+ layout.border.top
+ + layout.padding.top
+ + if is_root {
+ 0.0
+ } else {
+ horizontal_leading_gutter
+ },
+ );
+ for line in &context.fragments.lines {
+ local_overflow = local_overflow.union(offset_rect(line.rect, origin));
+ }
+ for fragment in &context.fragments.text {
+ local_overflow = local_overflow.union(offset_rect(fragment.rect, origin));
+ }
+ for fragment in &context.fragments.boxes {
+ local_overflow = local_overflow.union(offset_rect(fragment.rect, origin));
+ }
+ }
+ OverflowBoxGeometry {
+ border_box,
+ padding_box,
+ content_box,
+ margin_box,
+ resolved_transform,
+ local_scrollport,
+ vertical_gutter,
+ vertical_leading_gutter,
+ horizontal_gutter,
+ horizontal_leading_gutter,
+ local_overflow,
+ }
+}
+
+fn scrollbar_gutter_thickness<N>(
+ world: &LayoutWorld<N>,
+ id: LayoutBoxId,
+ axis: LayoutScrollbarAxis,
+) -> f32
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ if id == world.root {
+ world
+ .viewport_scroll_policy
+ .scrollbar_gutter_thickness(axis)
+ } else if world.is_viewport_defining_body(id) {
+ 0.0
+ } else {
+ world.boxes[id.index()]
+ .style
+ .scrollbar_gutter_thickness(axis)
+ }
+}
+
+fn scrollbar_leading_gutter_thickness<N>(
+ world: &LayoutWorld<N>,
+ id: LayoutBoxId,
+ axis: LayoutScrollbarAxis,
+) -> f32
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ if id == world.root {
+ world
+ .viewport_scroll_policy
+ .scrollbar_leading_gutter_thickness(axis)
+ } else if world.is_viewport_defining_body(id) {
+ 0.0
+ } else {
+ world.boxes[id.index()]
+ .style
+ .scrollbar_leading_gutter_thickness(axis, false)
+ }
+}
+
+fn establishes_scroll_container<N>(world: &LayoutWorld<N>, id: LayoutBoxId) -> bool
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ if id == world.root {
+ world.viewport_scroll_policy.establishes_scroll_container()
+ } else if world.is_viewport_defining_body(id) {
+ false
+ } else {
+ world.boxes[id.index()].style.establishes_scroll_container()
+ }
+}
+
+fn clips_overflow<N>(world: &LayoutWorld<N>, id: LayoutBoxId) -> bool
+where
+ N: Copy + Debug + Eq + Hash,
+{
+ if id == world.root {
+ world.viewport_scroll_policy.clips_overflow()
+ } else if world.is_viewport_defining_body(id) {
+ false
+ } else {
+ world.boxes[id.index()].style.clips_overflow()
+ }
+}
+
+pub(crate) fn inset_rect(
+ rect: LayoutRect,
+ top: f32,
+ right: f32,
+ bottom: f32,
+ left: f32,
+) -> LayoutRect {
+ let top = top.max(0.0);
+ let right = right.max(0.0);
+ let bottom = bottom.max(0.0);
+ let left = left.max(0.0);
+ LayoutRect::new(
+ rect.x + left,
+ rect.y + top,
+ (rect.width - left - right).max(0.0),
+ (rect.height - top - bottom).max(0.0),
+ )
+}
+
+pub(crate) fn outset_rect(
+ rect: LayoutRect,
+ top: f32,
+ right: f32,
+ bottom: f32,
+ left: f32,
+) -> LayoutRect {
+ LayoutRect::new(
+ rect.x - left,
+ rect.y - top,
+ (rect.width + left + right).max(0.0),
+ (rect.height + top + bottom).max(0.0),
+ )
+}
+
+pub(crate) fn offset_rect(rect: LayoutRect, offset: LayoutPoint) -> LayoutRect {
+ LayoutRect::new(
+ rect.x + offset.x,
+ rect.y + offset.y,
+ rect.width,
+ rect.height,
+ )
+}
+
+fn scrollport_for_box(
+ is_root: bool,
+ viewport: LayoutViewport,
+ padding_box: LayoutRect,
+ vertical_gutter: f32,
+ vertical_leading_gutter: f32,
+ horizontal_gutter: f32,
+ horizontal_leading_gutter: f32,
+) -> LayoutRect {
+ if is_root {
+ return LayoutRect::new(
+ 0.0,
+ 0.0,
+ (viewport.css_width as f32 - vertical_gutter).max(0.0),
+ (viewport.css_height as f32 - horizontal_gutter).max(0.0),
+ );
+ }
+ let mut scrollport = padding_box;
+ scrollport.width = (scrollport.width - vertical_gutter).max(0.0);
+ scrollport.height = (scrollport.height - horizontal_gutter).max(0.0);
+ scrollport.x += vertical_leading_gutter;
+ scrollport.y += horizontal_leading_gutter;
+ scrollport
+}
diff --git a/moli-layout/src/pass.rs b/moli-layout/src/pass.rs
index db289215c..2c6292558 100644
--- a/moli-layout/src/pass.rs
+++ b/moli-layout/src/pass.rs
@@ -5,10 +5,9 @@ use crate::{
form::prepare_form_controls,
inline::prepare_inline_contexts,
list::prepare_list_markers,
- projection::{finish_layout_pass, overflowing_axes},
- taffy_tree::{
- compute_prepared_world_layout, invalidate_scrollbar_feedback_layout, prepare_world_layout,
- },
+ overflow::OverflowProjection,
+ projection::finish_layout_pass,
+ taffy_tree::{compute_prepared_world_layout, prepare_world_layout},
};
use std::collections::HashMap;
use std::time::{Duration, Instant};
@@ -299,6 +298,8 @@ where
numeric_layout_pass_count: numeric_metrics.pass_count,
numeric_feedback_invalidated_node_count: numeric_metrics
.feedback_invalidated_node_count,
+ numeric_feedback_overflow_recomputed_node_count: numeric_metrics
+ .feedback_overflow_recomputed_node_count,
},
)
}
@@ -315,6 +316,7 @@ struct NumericLayoutMetrics {
overflow_detection_elapsed: Duration,
scrollbar_feedback_elapsed: Duration,
feedback_invalidated_node_count: usize,
+ feedback_overflow_recomputed_node_count: usize,
}
fn compute_world_layout_with_scrollbars<N>(
@@ -325,7 +327,6 @@ where
N: Copy + std::fmt::Debug + Eq + std::hash::Hash,
{
let root_id = world.root;
- let root = root_id.index();
let defining_body = world.viewport_scroll_policy.defining_body();
world.viewport_scroll_policy.prepare_scrollbar_layout();
for (index, layout_box) in world.boxes.iter_mut().enumerate() {
@@ -343,10 +344,12 @@ where
let phase_started = Instant::now();
let mut prepared = prepare_world_layout(world, viewport);
let preparation_elapsed = phase_started.elapsed();
+ let mut overflow_projection: Option<OverflowProjection> = None;
+ let mut pending_feedback_seeds = Vec::new();
loop {
metrics.pass_count = metrics.pass_count.saturating_add(1);
let phase_started = Instant::now();
- compute_prepared_world_layout(world, viewport, &mut prepared);
+ let mut touched = compute_prepared_world_layout(world, viewport, &mut prepared);
let elapsed = phase_started.elapsed();
if metrics.pass_count == 1 {
metrics.first_pass_elapsed = preparation_elapsed + elapsed;
@@ -354,24 +357,46 @@ where
metrics.followup_passes_elapsed += elapsed;
}
let phase_started = Instant::now();
- let overflow = overflowing_axes(world, viewport);
+ touched.append(&mut pending_feedback_seeds);
+ let candidates = if let Some(projection) = overflow_projection.as_mut() {
+ let affected = projection.refresh(world, viewport, &touched);
+ metrics.feedback_overflow_recomputed_node_count = metrics
+ .feedback_overflow_recomputed_node_count
+ .saturating_add(affected.len());
+ affected
+ } else {
+ let projection = OverflowProjection::new(world, viewport);
+ let candidates = (0..projection.len())
+ .map(crate::LayoutBoxId::from_index)
+ .collect();
+ overflow_projection = Some(projection);
+ candidates
+ };
+ let projection = overflow_projection
+ .as_ref()
+ .expect("overflow projection is initialized above");
+ let candidates = candidates
+ .into_iter()
+ .map(|id| (id, projection.overflowing_axes(world, id)))
+ .collect::<Vec<_>>();
metrics.overflow_detection_elapsed += phase_started.elapsed();
let phase_started = Instant::now();
- let (root_overflow_x, root_overflow_y) = overflow[root];
- let mut viewport_changed = world
- .viewport_scroll_policy
- .reveal_auto_scrollbar(LayoutScrollbarAxis::Horizontal, root_overflow_x);
- viewport_changed |= world
- .viewport_scroll_policy
- .reveal_auto_scrollbar(LayoutScrollbarAxis::Vertical, root_overflow_y);
+ let mut viewport_changed = false;
let mut changed_boxes = Vec::new();
- for (index, ((overflow_x, overflow_y), layout_box)) in
- overflow.into_iter().zip(world.boxes.iter_mut()).enumerate()
- {
- let id = crate::LayoutBoxId::from_index(index);
- if id == root_id || defining_body == Some(id) {
+ for (id, (overflow_x, overflow_y)) in candidates {
+ if id == root_id {
+ viewport_changed |= world
+ .viewport_scroll_policy
+ .reveal_auto_scrollbar(LayoutScrollbarAxis::Horizontal, overflow_x);
+ viewport_changed |= world
+ .viewport_scroll_policy
+ .reveal_auto_scrollbar(LayoutScrollbarAxis::Vertical, overflow_y);
continue;
}
+ if defining_body == Some(id) {
+ continue;
+ }
+ let layout_box = &mut world.boxes[id.index()];
let mut box_changed = layout_box.style.reveal_auto_scrollbar(
LayoutScrollbarAxis::Horizontal,
false,
@@ -390,8 +415,12 @@ where
if changed {
metrics.feedback_invalidated_node_count =
metrics.feedback_invalidated_node_count.saturating_add(
- invalidate_scrollbar_feedback_layout(world, &changed_boxes, viewport_changed),
+ prepared.invalidate_scrollbar_feedback(world, &changed_boxes, viewport_changed),
);
+ pending_feedback_seeds.extend(changed_boxes.iter().copied());
+ if viewport_changed {
+ pending_feedback_seeds.push(root_id);
+ }
}
metrics.scrollbar_feedback_elapsed += phase_started.elapsed();
if !changed {
diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rs
index 15f5edb8b..dbbc3fb93 100644
--- a/moli-layout/src/projection.rs
+++ b/moli-layout/src/projection.rs
@@ -3,6 +3,7 @@ use std::{collections::HashMap, fmt::Debug, hash::Hash, time::Instant};
use taffy::ResolveOrZero;
use crate::layout_tree::LayoutCoordinateSpace;
+use crate::overflow::{OverflowProjection, inset_rect, offset_rect, outset_rect};
use crate::stacking::{PaintOrderEvent, build_paint_order};
use crate::style::ResolvedLayoutTransform;
use crate::{
@@ -28,6 +29,7 @@ pub(crate) struct LayoutPassPhaseMetrics {
pub(crate) embedded_frame_elapsed: std::time::Duration,
pub(crate) numeric_layout_pass_count: usize,
pub(crate) numeric_feedback_invalidated_node_count: usize,
+ pub(crate) numeric_feedback_overflow_recomputed_node_count: usize,
}
pub(crate) fn finish_layout_pass<N>(
@@ -45,9 +47,10 @@ where
N: Copy + Debug + Eq + Hash,
{
let projection_started = Instant::now();
+ let overflow = OverflowProjection::new(world, viewport);
let mut projection = OutputProjection::new(world, viewport);
- projection.build_local_box_geometry();
- projection.resolve_scrollable_overflow();
+ projection.build_local_box_geometry(&overflow);
+ projection.build_scroll_extents(&overflow);
projection.build_coordinate_spaces()?;
projection.build_fragments();
projection.assign_clip_and_paint_order();
@@ -109,6 +112,8 @@ where
numeric_layout_pass_count: phase_metrics.numeric_layout_pass_count,
numeric_feedback_invalidated_node_count: phase_metrics
.numeric_feedback_invalidated_node_count,
+ numeric_feedback_overflow_recomputed_node_count: phase_metrics
+ .numeric_feedback_overflow_recomputed_node_count,
box_count: projection.boxes.len(),
fragment_count: projection.fragments.len(),
paint_event_count: paint_projection_metrics.event_count,
@@ -145,31 +150,6 @@ where
))
}
-/// Samples overflow from the same projection that will freeze scroll extents.
-/// This keeps `overflow:auto` discovery correct for positioned descendants,
-/// transforms, and nested clips without maintaining a second approximation.
-pub(crate) fn overflowing_axes<N>(
- world: &LayoutWorld<N>,
- viewport: LayoutViewport,
-) -> Vec<(bool, bool)>
-where
- N: Copy + Debug + Eq + Hash,
-{
- let mut projection = OutputProjection::new(world, viewport);
- projection.build_local_box_geometry();
- projection.resolve_scrollable_overflow();
- projection
- .scroll_extents
- .into_iter()
- .map(|extent| {
- (
- extent.maximum_offset.x - extent.minimum_offset.x > f32::EPSILON,
- extent.maximum_offset.y - extent.minimum_offset.y > f32::EPSILON,
- )
- })
- .collect()
-}
-
/// Blink-like linear paint space for one projected coordinate space.
///
/// Chromium describes this space as the combination of a transform and a
@@ -316,38 +296,6 @@ where
self.resolved_transforms[id.index()].has_unsupported_3d
}
- fn scrollbar_gutter_thickness(&self, id: LayoutBoxId, axis: LayoutScrollbarAxis) -> f32 {
- if id == self.world.root {
- self.world
- .viewport_scroll_policy
- .scrollbar_gutter_thickness(axis)
- } else if self.world.is_viewport_defining_body(id) {
- 0.0
- } else {
- self.world.boxes[id.index()]
- .style
- .scrollbar_gutter_thickness(axis)
- }
- }
-
- fn scrollbar_leading_gutter_thickness(
- &self,
- id: LayoutBoxId,
- axis: LayoutScrollbarAxis,
- ) -> f32 {
- if id == self.world.root {
- self.world
- .viewport_scroll_policy
- .scrollbar_leading_gutter_thickness(axis)
- } else if self.world.is_viewport_defining_body(id) {
- 0.0
- } else {
- self.world.boxes[id.index()]
- .style
- .scrollbar_leading_gutter_thickness(axis, false)
- }
- }
-
fn scrollbar_control_thickness(&self, id: LayoutBoxId) -> f32 {
if id == self.world.root {
self.world
@@ -435,7 +383,9 @@ where
}
}
- fn build_local_box_geometry(&mut self) {
+ fn build_local_box_geometry(&mut self, overflow: &OverflowProjection) {
+ assert_eq!(overflow.len(), self.world.boxes.len());
+ let layout_origins = self.world.global_layout_origins();
for (index, layout_box) in self.world.boxes.iter().enumerate() {
for diagnostic in layout_box.capability_diagnostics() {
self.diagnostics.push(PaintDiagnostic::new(
@@ -450,52 +400,8 @@ where
}
let box_id = LayoutBoxId::from_index(index);
let id = LayoutOutputBoxId::from_index(index);
- let is_root = box_id == self.world.root;
- let layout = layout_box.final_layout;
- let border_box = LayoutRect::new(
- 0.0,
- 0.0,
- layout.size.width.max(0.0),
- layout.size.height.max(0.0),
- );
- let padding_box = inset_rect(
- border_box,
- layout.border.top,
- layout.border.right,
- layout.border.bottom,
- layout.border.left,
- );
- let vertical_gutter =
- self.scrollbar_gutter_thickness(box_id, LayoutScrollbarAxis::Vertical);
- let vertical_leading_gutter =
- self.scrollbar_leading_gutter_thickness(box_id, LayoutScrollbarAxis::Vertical);
- let horizontal_gutter =
- self.scrollbar_gutter_thickness(box_id, LayoutScrollbarAxis::Horizontal);
- let horizontal_leading_gutter =
- self.scrollbar_leading_gutter_thickness(box_id, LayoutScrollbarAxis::Horizontal);
- let mut content_box = inset_rect(
- padding_box,
- layout.padding.top,
- layout.padding.right,
- layout.padding.bottom,
- layout.padding.left,
- );
- if !is_root {
- content_box.width = (content_box.width - vertical_gutter).max(0.0);
- content_box.height = (content_box.height - horizontal_gutter).max(0.0);
- content_box.x += vertical_leading_gutter;
- content_box.y += horizontal_leading_gutter;
- }
- let margin_box = outset_rect(
- border_box,
- layout.margin.top,
- layout.margin.right,
- layout.margin.bottom,
- layout.margin.left,
- );
- let resolved = layout_box
- .style
- .resolved_2d_transform(border_box.width, border_box.height);
+ let geometry = overflow.geometry(box_id);
+ let resolved = geometry.resolved_transform;
self.resolved_transforms[index] = resolved;
if resolved.has_unsupported_3d {
self.diagnostics.push(PaintDiagnostic::new(
@@ -507,68 +413,7 @@ where
PaintDiagnosticSeverity::Warning,
));
}
- let local_scrollport = scrollport_for_box(
- is_root,
- self.viewport,
- padding_box,
- vertical_gutter,
- vertical_leading_gutter,
- horizontal_gutter,
- horizontal_leading_gutter,
- );
- // Scrollable overflow starts at the padding-derived scrollport. A
- // box's own border is visual geometry, not reachable descendant
- // content, while starting after reserved gutters keeps a
- // perpendicular scrollbar from manufacturing overflow on its own.
- // Taffy's content_size is expressed from the padding edge and
- // equals CSSOM scrollWidth/scrollHeight when it is larger than the
- // client area.
- let mut overflow = LayoutRect::new(
- local_scrollport.x,
- local_scrollport.y,
- local_scrollport
- .width
- .max(layout.content_size.width)
- .max(0.0),
- local_scrollport
- .height
- .max(layout.content_size.height)
- .max(0.0),
- );
- if is_root {
- // The synthetic viewport has already removed root gutters,
- // so the root's own used padding box can safely contribute
- // without manufacturing perpendicular overflow.
- overflow = overflow.union(padding_box);
- }
- if let Some(context) = layout_box.inline_layout.as_ref() {
- let origin = LayoutPoint::new(
- layout.border.left
- + layout.padding.left
- + if is_root {
- 0.0
- } else {
- vertical_leading_gutter
- },
- layout.border.top
- + layout.padding.top
- + if is_root {
- 0.0
- } else {
- horizontal_leading_gutter
- },
- );
- for line in &context.fragments.lines {
- overflow = overflow.union(offset_rect(line.rect, origin));
- }
- for fragment in &context.fragments.text {
- overflow = overflow.union(offset_rect(fragment.rect, origin));
- }
- for fragment in &context.fragments.boxes {
- overflow = overflow.union(offset_rect(fragment.rect, origin));
- }
- }
- self.scrollable_overflow[index] = overflow;
+ self.scrollable_overflow[index] = overflow.scrollable_overflow(box_id);
let source = layout_box.source.or_else(|| {
(layout_box.anonymous_reason
== Some(LayoutAnonymousReason::InlineSplitContinuation))
@@ -584,9 +429,6 @@ where
.flatten()
}));
let semantics = layout_box.element_semantics();
- let (layout_x, layout_y) = self
- .world
- .global_layout_origin(LayoutBoxId::from_index(index));
self.boxes.push(LayoutBoxGeometry {
id,
effective_zoom: layout_box.style.effective_zoom(),
@@ -602,12 +444,12 @@ where
position: layout_box.style.position(),
coordinate_space: LayoutCoordinateSpaceId::from_index(index + 1),
clip_chain: None,
- content_box,
- padding_box,
- border_box,
- margin_box,
+ content_box: geometry.content_box,
+ padding_box: geometry.padding_box,
+ border_box: geometry.border_box,
+ margin_box: geometry.margin_box,
fragments: Vec::new(),
- layout_origin_in_document: LayoutPoint::new(layout_x, layout_y),
+ layout_origin_in_document: layout_origins[index],
is_body_element: semantics.is_some_and(|element| element.is_html_element("body")),
is_table_offset_parent: semantics.is_some_and(|element| {
element.is_html_element("table")
@@ -623,72 +465,19 @@ where
}
}
- fn resolve_scrollable_overflow(&mut self) {
- for index in (0..self.world.boxes.len()).rev() {
- let parent_id = self.world.boxes[index].layout_parent.or_else(|| {
- // An absolutely positioned box whose containing block is the
- // initial containing block is a direct child of Taffy's
- // virtual viewport. It still contributes to the root
- // element's scrollable overflow. Fixed boxes are excluded
- // below because they remain anchored to that viewport.
- (index != self.world.root.index()).then_some(self.world.root)
- });
- let Some(parent_id) = parent_id else {
- continue;
- };
- if self.world.boxes[index].style.is_fixed_positioned() {
- continue;
- }
- let child_geometry = &self.boxes[index];
- let visual_overflow = if self.clips_overflow(LayoutBoxId::from_index(index)) {
- child_geometry.border_box
- } else {
- self.scrollable_overflow[index]
- };
- let location = self.world.boxes[index].final_layout.location;
- let layout_translation = LayoutTransform2D::translation(location.x, location.y);
- let local_to_parent =
- layout_translation.concatenate(self.resolved_transforms[index].transform);
- let mapped = local_to_parent
- .map_rect(visual_overflow)
- .bounding_rect()
- .union(
- layout_translation
- .map_rect(child_geometry.margin_box)
- .bounding_rect(),
- );
- self.scrollable_overflow[parent_id.index()] =
- self.scrollable_overflow[parent_id.index()].union(mapped);
- }
-
+ fn build_scroll_extents(&mut self, overflow_projection: &OverflowProjection) {
for index in 0..self.world.boxes.len() {
let id = LayoutBoxId::from_index(index);
- let geometry = &self.boxes[index];
- let overflow = self.scrollable_overflow[index];
+ let geometry = overflow_projection.geometry(id);
+ let overflow = overflow_projection.scrollable_overflow(id);
let is_root = id == self.world.root;
- let vertical_gutter =
- self.scrollbar_gutter_thickness(id, LayoutScrollbarAxis::Vertical);
- let vertical_leading_gutter =
- self.scrollbar_leading_gutter_thickness(id, LayoutScrollbarAxis::Vertical);
- let horizontal_gutter =
- self.scrollbar_gutter_thickness(id, LayoutScrollbarAxis::Horizontal);
- let horizontal_leading_gutter =
- self.scrollbar_leading_gutter_thickness(id, LayoutScrollbarAxis::Horizontal);
let scrollbar_thickness = self.scrollbar_control_thickness(id);
let vertical_scrollbar_on_left = self.places_vertical_scrollbar_on_left(id);
- let local_scrollport = scrollport_for_box(
- is_root,
- self.viewport,
- geometry.padding_box,
- vertical_gutter,
- vertical_leading_gutter,
- horizontal_gutter,
- horizontal_leading_gutter,
- );
+ let local_scrollport = geometry.local_scrollport;
let scrollport = if is_root {
LayoutRect::new(
- vertical_leading_gutter,
- horizontal_leading_gutter,
+ geometry.vertical_leading_gutter,
+ geometry.horizontal_leading_gutter,
local_scrollport.width,
local_scrollport.height,
)
@@ -779,18 +568,19 @@ where
)
})
.filter(|bar| bar.frame.width > 0.0 && bar.frame.height > 0.0);
- let scrollbar_corner = (vertical_gutter > 0.0 && horizontal_gutter > 0.0).then(|| {
- LayoutRect::new(
- if vertical_scrollbar_on_left {
- scrollport.x - scrollbar_thickness
- } else {
- scrollport.right()
- },
- scrollport.bottom(),
- scrollbar_thickness,
- scrollbar_thickness,
- )
- });
+ let scrollbar_corner =
+ (geometry.vertical_gutter > 0.0 && geometry.horizontal_gutter > 0.0).then(|| {
+ LayoutRect::new(
+ if vertical_scrollbar_on_left {
+ scrollport.x - scrollbar_thickness
+ } else {
+ scrollport.right()
+ },
+ scrollport.bottom(),
+ scrollbar_thickness,
+ scrollbar_thickness,
+ )
+ });
self.scroll_extents.push(LayoutScrollExtent {
scrollport,
scrollable_overflow: overflow,
@@ -1416,37 +1206,6 @@ where
Ok(())
}
-fn inset_rect(rect: LayoutRect, top: f32, right: f32, bottom: f32, left: f32) -> LayoutRect {
- let top = top.max(0.0);
- let right = right.max(0.0);
- let bottom = bottom.max(0.0);
- let left = left.max(0.0);
- LayoutRect::new(
- rect.x + left,
- rect.y + top,
- (rect.width - left - right).max(0.0),
- (rect.height - top - bottom).max(0.0),
- )
-}
-
-fn outset_rect(rect: LayoutRect, top: f32, right: f32, bottom: f32, left: f32) -> LayoutRect {
- LayoutRect::new(
- rect.x - left,
- rect.y - top,
- (rect.width + left + right).max(0.0),
- (rect.height + top + bottom).max(0.0),
- )
-}
-
-fn offset_rect(rect: LayoutRect, offset: LayoutPoint) -> LayoutRect {
- LayoutRect::new(
- rect.x + offset.x,
- rect.y + offset.y,
- rect.width,
- rect.height,
- )
-}
-
fn finite_point(point: LayoutPoint) -> LayoutPoint {
LayoutPoint::new(
if point.x.is_finite() { point.x } else { 0.0 },
@@ -1454,31 +1213,6 @@ fn finite_point(point: LayoutPoint) -> LayoutPoint {
)
}
-fn scrollport_for_box(
- is_root: bool,
- viewport: LayoutViewport,
- padding_box: LayoutRect,
- vertical_gutter: f32,
- vertical_leading_gutter: f32,
- horizontal_gutter: f32,
- horizontal_leading_gutter: f32,
-) -> LayoutRect {
- if is_root {
- return LayoutRect::new(
- 0.0,
- 0.0,
- (viewport.css_width as f32 - vertical_gutter).max(0.0),
- (viewport.css_height as f32 - horizontal_gutter).max(0.0),
- );
- }
- let mut scrollport = padding_box;
- scrollport.width = (scrollport.width - vertical_gutter).max(0.0);
- scrollport.height = (scrollport.height - horizontal_gutter).max(0.0);
- scrollport.x += vertical_leading_gutter;
- scrollport.y += horizontal_leading_gutter;
- scrollport
-}
-
fn inline_fragment_box_model<N>(
world: &LayoutWorld<N>,
owner_index: usize,
diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rs
index b53c16c6e..aba9e366b 100644
--- a/moli-layout/src/taffy_tree.rs
+++ b/moli-layout/src/taffy_tree.rs
@@ -34,6 +34,8 @@ pub(crate) struct PreparedWorldLayout {
positioned_static_placeholders: Vec<PositionedStaticPlaceholder>,
numeric_unrounded_layouts: Vec<Layout>,
numeric_viewport_layout: Layout,
+ feedback_invalidation_marks: Vec<bool>,
+ feedback_invalidation_worklist: Vec<LayoutBoxId>,
}
impl PreparedWorldLayout {
@@ -69,6 +71,48 @@ impl PreparedWorldLayout {
);
self.numeric_viewport_layout = world.viewport_layout.unrounded_layout;
}
+
+ /// Clears only the cache entries on changed scrollbar boxes and their
+ /// numeric ancestors. The reusable mark table makes this proportional to
+ /// the affected paths rather than to every box in the document.
+ pub(crate) fn invalidate_scrollbar_feedback<N>(
+ &mut self,
+ world: &mut LayoutWorld<N>,
+ changed_boxes: &[LayoutBoxId],
+ viewport_changed: bool,
+ ) -> usize
+ where
+ N: Copy + Debug + Eq + Hash,
+ {
+ assert!(self.feedback_invalidation_worklist.is_empty());
+ self.feedback_invalidation_marks
+ .resize(world.boxes.len(), false);
+ if viewport_changed {
+ self.feedback_invalidation_worklist.push(world.root);
+ }
+ self.feedback_invalidation_worklist
+ .extend(changed_boxes.iter().copied());
+
+ let mut invalidated = Vec::new();
+ while let Some(id) = self.feedback_invalidation_worklist.pop() {
+ if self.feedback_invalidation_marks[id.index()] {
+ continue;
+ }
+ self.feedback_invalidation_marks[id.index()] = true;
+ invalidated.push(id);
+ world.boxes[id.index()].cache.clear();
+ if let Some(parent) = world.boxes[id.index()].layout_parent {
+ self.feedback_invalidation_worklist.push(parent);
+ }
+ }
+ if viewport_changed || !changed_boxes.is_empty() {
+ world.viewport_layout.cache.clear();
+ }
+ for id in invalidated.iter().copied() {
+ self.feedback_invalidation_marks[id.index()] = false;
+ }
+ invalidated.len()
+ }
}
/// Builds the stable numeric tree once for the entire scrollbar feedback
@@ -102,6 +146,8 @@ where
positioned_static_placeholders,
numeric_unrounded_layouts: Vec::with_capacity(world.boxes.len()),
numeric_viewport_layout: Layout::with_order(0),
+ feedback_invalidation_marks: vec![false; world.boxes.len()],
+ feedback_invalidation_worklist: Vec::new(),
};
prepared.capture_numeric_geometry(world);
prepared
@@ -153,10 +199,12 @@ pub(crate) fn compute_prepared_world_layout<N>(
world: &mut LayoutWorld<N>,
viewport: PaintViewport,
prepared: &mut PreparedWorldLayout,
-) where
+) -> Vec<LayoutBoxId>
+where
N: Copy + Debug + Eq + Hash,
{
prepared.restore_numeric_geometry(world);
+ world.begin_numeric_layout_tracking();
update_viewport_layout_style(world, viewport);
let root = world.viewport_taffy_node();
@@ -187,47 +235,7 @@ pub(crate) fn compute_prepared_world_layout<N>(
for marker in outside_markers {
round_layout_to_css_subpixels(world, marker.to_taffy());
}
-}
-
-/// Invalidates exactly the boxes whose style changed and their numeric
-/// ancestors. Descendants and sibling subtrees retain their Taffy entries; a
-/// changed input naturally misses the keyed cache, while an unchanged input
-/// can reuse both its output and the restored local geometry.
-pub(crate) fn invalidate_scrollbar_feedback_layout<N>(
- world: &mut LayoutWorld<N>,
- changed_boxes: &[LayoutBoxId],
- viewport_changed: bool,
-) -> usize
-where
- N: Copy + Debug + Eq + Hash,
-{
- let mut invalidated = vec![false; world.boxes.len()];
- if viewport_changed {
- invalidated[world.root.index()] = true;
- }
- for changed in changed_boxes {
- let mut current = Some(*changed);
- while let Some(id) = current {
- if invalidated[id.index()] {
- break;
- }
- invalidated[id.index()] = true;
- current = world.boxes[id.index()].layout_parent;
- }
- }
- let invalidated_count = invalidated
- .iter()
- .filter(|invalidated| **invalidated)
- .count();
- for (layout_box, invalidated) in world.boxes.iter_mut().zip(invalidated) {
- if invalidated {
- layout_box.cache.clear();
- }
- }
- if viewport_changed || !changed_boxes.is_empty() {
- world.viewport_layout.cache.clear();
- }
- invalidated_count
+ world.finish_numeric_layout_tracking()
}
/// Converts Taffy's horizontal block-start anchor into the physical edge used
@@ -1429,7 +1437,11 @@ where
if self.is_viewport_taffy_node(node_id) {
self.viewport_layout.unrounded_layout = *layout;
} else {
- self.boxes[LayoutBoxId::from_taffy(node_id).index()].unrounded_layout = *layout;
+ let id = LayoutBoxId::from_taffy(node_id);
+ if self.boxes[id.index()].unrounded_layout != *layout {
+ self.record_numeric_layout_touch(id);
+ }
+ self.boxes[id.index()].unrounded_layout = *layout;
}
}
@@ -1502,9 +1514,14 @@ where
if self.is_viewport_taffy_node(node_id) {
self.viewport_layout.cache.store(inputs, output);
} else {
- self.boxes[LayoutBoxId::from_taffy(node_id).index()]
- .cache
- .store(inputs, output);
+ let id = LayoutBoxId::from_taffy(node_id);
+ if inputs.run_mode == RunMode::PerformLayout {
+ // A cache miss may rebuild inline fragments without changing
+ // the outer numeric rectangle, so final-layout stores are also
+ // first-class overflow dependencies.
+ self.record_numeric_layout_touch(id);
+ }
+ self.boxes[id.index()].cache.store(inputs, output);
}
}
@@ -1615,7 +1632,11 @@ where
if self.is_viewport_taffy_node(node_id) {
self.viewport_layout.final_layout = *layout;
} else {
- self.boxes[LayoutBoxId::from_taffy(node_id).index()].final_layout = *layout;
+ let id = LayoutBoxId::from_taffy(node_id);
+ if self.boxes[id.index()].final_layout != *layout {
+ self.record_numeric_layout_touch(id);
+ }
+ self.boxes[id.index()].final_layout = *layout;
}
}
}
diff --git a/moli-layout/src/world.rs b/moli-layout/src/world.rs
index 6326ccfe3..d5b176075 100644
--- a/moli-layout/src/world.rs
+++ b/moli-layout/src/world.rs
@@ -568,6 +568,9 @@ where
pub(crate) viewport_scroll_policy: ViewportScrollPolicy,
pub(crate) viewport_layout: ViewportLayoutState,
pub(crate) css_image_references: Vec<LayoutCssImageReference<N>>,
+ numeric_layout_tracking: bool,
+ numeric_layout_touched: Vec<LayoutBoxId>,
+ numeric_layout_touched_marks: Vec<bool>,
}
impl<N> LayoutWorld<N>
@@ -583,6 +586,9 @@ where
viewport_scroll_policy: ViewportScrollPolicy::default(),
viewport_layout: ViewportLayoutState::default(),
css_image_references: Vec::new(),
+ numeric_layout_tracking: false,
+ numeric_layout_touched: Vec::new(),
+ numeric_layout_touched_marks: vec![false],
}
}
@@ -622,22 +628,99 @@ where
usize::from(node) == self.boxes.len()
}
- pub(crate) fn global_layout_origin(&self, id: LayoutBoxId) -> (f32, f32) {
- let mut x = 0.0;
- let mut y = 0.0;
- let mut current = Some(id);
- while let Some(box_id) = current {
- let layout_box = &self.boxes[box_id.index()];
- x += layout_box.final_layout.location.x;
- y += layout_box.final_layout.location.y;
- current = layout_box.layout_parent;
+ /// Resolves every numeric layout origin in one preorder forest traversal.
+ ///
+ /// Calling the former single-box helper for every output box repeatedly
+ /// walked shared ancestor chains and became quadratic for a deep document.
+ /// The intrusive child links below avoid one allocation per parent in a
+ /// deeply nested tree while still covering detached numeric roots.
+ pub(crate) fn global_layout_origins(&self) -> Vec<LayoutPoint> {
+ let count = self.boxes.len();
+ let mut first_child = vec![None; count];
+ let mut next_sibling = vec![None; count];
+ let mut roots = Vec::new();
+ for index in (0..count).rev() {
+ let id = LayoutBoxId::from_index(index);
+ if let Some(parent) = self.boxes[index].layout_parent {
+ assert!(
+ parent.index() < count,
+ "numeric layout parent must belong to this world"
+ );
+ next_sibling[index] = first_child[parent.index()];
+ first_child[parent.index()] = Some(id);
+ } else {
+ roots.push(id);
+ }
+ }
+
+ let mut origins = vec![LayoutPoint::ZERO; count];
+ let mut visited = vec![false; count];
+ let mut stack = roots
+ .into_iter()
+ .map(|root| (root, LayoutPoint::ZERO))
+ .collect::<Vec<_>>();
+ let mut resolved = 0usize;
+ while let Some((id, parent_origin)) = stack.pop() {
+ assert!(
+ !visited[id.index()],
+ "numeric layout parents must form an acyclic forest"
+ );
+ visited[id.index()] = true;
+ resolved = resolved.saturating_add(1);
+ let location = self.boxes[id.index()].final_layout.location;
+ let origin =
+ LayoutPoint::new(parent_origin.x + location.x, parent_origin.y + location.y);
+ origins[id.index()] = origin;
+
+ let mut child = first_child[id.index()];
+ while let Some(child_id) = child {
+ stack.push((child_id, origin));
+ child = next_sibling[child_id.index()];
+ }
+ }
+ assert_eq!(
+ resolved, count,
+ "numeric layout parents must form an acyclic forest"
+ );
+ origins
+ }
+
+ pub(crate) fn begin_numeric_layout_tracking(&mut self) {
+ assert!(
+ !self.numeric_layout_tracking,
+ "numeric layout tracking cannot be nested"
+ );
+ assert!(self.numeric_layout_touched.is_empty());
+ self.numeric_layout_touched_marks
+ .resize(self.boxes.len(), false);
+ self.numeric_layout_tracking = true;
+ }
+
+ pub(crate) fn record_numeric_layout_touch(&mut self, id: LayoutBoxId) {
+ if !self.numeric_layout_tracking || self.numeric_layout_touched_marks[id.index()] {
+ return;
+ }
+ self.numeric_layout_touched_marks[id.index()] = true;
+ self.numeric_layout_touched.push(id);
+ }
+
+ pub(crate) fn finish_numeric_layout_tracking(&mut self) -> Vec<LayoutBoxId> {
+ assert!(
+ self.numeric_layout_tracking,
+ "numeric layout tracking must be active"
+ );
+ self.numeric_layout_tracking = false;
+ let touched = std::mem::take(&mut self.numeric_layout_touched);
+ for id in touched.iter().copied() {
+ self.numeric_layout_touched_marks[id.index()] = false;
}
- (x, y)
+ touched
}
pub(crate) fn allocate(&mut self, layout_box: LayoutBox<N>) -> LayoutBoxId {
let id = LayoutBoxId::from_index(self.boxes.len());
self.boxes.push(layout_box);
+ self.numeric_layout_touched_marks.push(false);
id
}
diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rs
index 0173e62ec..35f52c939 100644
--- a/moli-layout/tests/phase5_output_contract.rs
+++ b/moli-layout/tests/phase5_output_contract.rs
@@ -822,6 +822,129 @@ fn scrollbar_feedback_prepares_static_position_placeholders_once() {
assert!(output.source_output(3).is_some());
}
+#[test]
+fn nested_auto_scrollbar_feedback_reprojects_each_affected_path_linearly() {
+ for depth in [8usize, 64] {
+ let leaf = depth + 1;
+ let mut nodes = Vec::with_capacity(leaf + 1);
+ nodes.push(Node::element("root", vec![1]));
+ for index in 1..=depth {
+ nodes.push(Node::element(
+ "nested-scroller",
+ vec![if index == depth { leaf } else { index + 1 }],
+ ));
+ }
+ nodes.push(Node::element("oversized-leaf", Vec::new()));
+ let source = Source(nodes);
+ let mut styles = Styles::default();
+ styles
+ .0
+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));
+ for index in 1..=depth {
+ styles.0.insert(
+ index,
+ resolved(
+ LayoutDisplay::Block,
+ Style {
+ size: Size {
+ width: length(200.0),
+ height: length(100.0),
+ },
+ overflow: Point {
+ x: Overflow::Scroll,
+ y: Overflow::Scroll,
+ },
+ ..Style::default()
+ },
+ ),
+ );
+ }
+ styles
+ .0
+ .insert(leaf, fixed_size(LayoutDisplay::Block, 200.0, 200.0));
+
+ let output = build(&source, &mut styles);
+ assert_eq!(output.metrics.numeric_layout_pass_count, 3);
+ assert_eq!(output.metrics.box_count, depth + 2);
+ assert_eq!(
+ output
+ .metrics
+ .numeric_feedback_overflow_recomputed_node_count,
+ 2 * (depth + 2),
+ "each perpendicular-axis turn should visit the one affected chain once"
+ );
+ }
+}
+
+#[test]
+fn scrollbar_feedback_worklist_skips_unaffected_wide_branches() {
+ const UNRELATED_FIXED_BOXES: usize = 128;
+ let mut root_children = vec![1];
+ root_children.extend(3..3 + UNRELATED_FIXED_BOXES);
+ let mut nodes = vec![
+ Node::element("root", root_children),
+ Node::element("scroller", vec![2]),
+ Node::element("oversized-content", Vec::new()),
+ ];
+ nodes.extend((0..UNRELATED_FIXED_BOXES).map(|_| Node::element("unrelated-fixed", Vec::new())));
+ let source = Source(nodes);
+ let mut styles = Styles::default();
+ styles
+ .0
+ .insert(0, fixed_size(LayoutDisplay::Block, 320.0, 240.0));
+ styles.0.insert(
+ 1,
+ resolved(
+ LayoutDisplay::Block,
+ Style {
+ size: Size {
+ width: length(200.0),
+ height: length(100.0),
+ },
+ overflow: Point {
+ x: Overflow::Scroll,
+ y: Overflow::Scroll,
+ },
+ ..Style::default()
+ },
+ ),
+ );
+ styles
+ .0
+ .insert(2, fixed_size(LayoutDisplay::Block, 200.0, 200.0));
+ for index in 3..3 + UNRELATED_FIXED_BOXES {
+ styles.0.insert(
+ index,
+ resolved(
+ LayoutDisplay::Block,
+ Style {
+ position: Position::Absolute,
+ size: Size {
+ width: length(10.0),
+ height: length(10.0),
+ },
+ ..Style::default()
+ },
+ )
+ .with_position(LayoutPosition::Fixed),
+ );
+ }
+
+ let output = build(&source, &mut styles);
+ assert_eq!(output.metrics.numeric_layout_pass_count, 3);
+ assert!(output.metrics.box_count > UNRELATED_FIXED_BOXES);
+ assert!(
+ output
+ .metrics
+ .numeric_feedback_overflow_recomputed_node_count
+ < 16,
+ "unrelated viewport-fixed branches must stay out of the overflow worklist: {:?}",
+ output
+ .metrics
+ .numeric_feedback_overflow_recomputed_node_count
+ );
+}
+
#[test]
fn thin_and_hidden_scrollbars_match_chromium_client_geometry() {
let source = Source(vec![
diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
index 6607fb5be..15e55a060 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs
@@ -269,6 +269,8 @@ impl JsContextHost {
numeric_layout_pass_count = metrics.numeric_layout_pass_count,
numeric_feedback_invalidated_node_count = metrics
.numeric_feedback_invalidated_node_count,
+ numeric_feedback_overflow_recomputed_node_count = metrics
+ .numeric_feedback_overflow_recomputed_node_count,
box_count = metrics.box_count,
fragment_count = metrics.fragment_count,
paint_event_count = metrics.paint_event_count,
diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs b/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs
index 7d50e25a9..468ba97e2 100644
--- a/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs
+++ b/moli-renderer-v8/src/native_bridge/element/geometry/mock/queries.rs
@@ -157,6 +157,7 @@ pub(crate) fn answer_queries(
projection_elapsed: Duration::ZERO,
numeric_layout_pass_count: 1,
numeric_feedback_invalidated_node_count: 0,
+ numeric_feedback_overflow_recomputed_node_count: 0,
box_count: 0,
fragment_count: 0,
paint_event_count: 0,