Skip to content

Truly independent web browser

LibWeb: Lay out flex items on the style and layout threads

Aliaksandr Kalenikb29ade659bcc
diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rs
index 0e4915e94b7..4d0f71e1b70 100644
--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs
@@ -436,6 +436,14 @@ pub struct StyleEngine {
}
impl RetainedState {
+ pub(crate) fn deepest_element_depth(&self) -> u32 {
+ self.deepest_element.load(std::sync::atomic::Ordering::Relaxed)
+ }
+
+ pub(crate) fn started_style_layout_pool(&self) -> Option<std::sync::Arc<rayon::ThreadPool>> {
+ self.style_layout_pool.as_ref()?.started()
+ }
+
/// The groups of default values every computation starting from nothing starts from.
pub(crate) fn default_groups(&self) -> &crate::css::computed_values::DefaultGroups {
&self.process_style.default_groups
diff --git a/Libraries/LibWeb/Rust/src/layout/flex_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/flex_formatting_context.rs
index ce2a4e0bbe2..df1a45a5eee 100644
--- a/Libraries/LibWeb/Rust/src/layout/flex_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/flex_formatting_context.rs
@@ -383,6 +383,7 @@ pub(super) struct FlexFormattingContext<'pass> {
item_percentage_bases: ContainingBlockConstraints,
item_runs_offered_to_block_size_measurements: Option<ItemRunsOfferedToBlockSizeMeasurements>,
flex_item_index_by_node: OnceCell<HashMap<Node, usize>>,
+ items_to_fork: OnceCell<Vec<usize>>,
in_flow_items_margin_box_block_extent: Option<CssPixels>,
/// The cells in which this context sizes the flex container, in the frame its items are laid out in. The context
/// takes them again after the run sizes the container's own box.
@@ -433,6 +434,7 @@ impl<'pass> FlexFormattingContext<'pass> {
item_percentage_bases: ContainingBlockConstraints::default(),
item_runs_offered_to_block_size_measurements: None,
flex_item_index_by_node: OnceCell::new(),
+ items_to_fork: OnceCell::new(),
in_flow_items_margin_box_block_extent: None,
container_cells: Cell::new(container_cells),
}
@@ -1149,6 +1151,7 @@ impl<'pass> FlexFormattingContext<'pass> {
let order = inputs.style.order();
items_have_different_orders |= *order_of_first_item.get_or_insert(order) != order;
self.flex_items.push(FlexItem::new(child, alignment_facts, &inputs));
+ self.items_to_fork.take();
self.flex_item_details.push(FlexItemDetails::new(inputs, cells));
self.populate_specified_margins(self.flex_items.len() - 1);
}
@@ -2226,6 +2229,16 @@ impl<'pass> FlexFormattingContext<'pass> {
self.flex_items[index].hypothetical_cross_size = css_clamp(size, min, max);
}
+ fn fork_candidates(&self) -> Vec<usize> {
+ self.items_to_fork
+ .get_or_init(|| {
+ parallel_layout::fork_candidates(&self.run.callbacks, 0..self.flex_items.len(), |index| {
+ self.flex_items[index].box_
+ })
+ })
+ .clone()
+ }
+
// https://drafts.csswg.org/css-flexbox/#hypothetical-cross-size
fn determine_hypothetical_cross_size_of_item(&mut self, index: usize) {
// Determine the hypothetical cross size of each item by performing layout as if it were an in-flow block-level box
@@ -3353,13 +3366,7 @@ impl<'pass> FlexFormattingContext<'pass> {
)
}
- /// Lays out the contents of the item at `index`, and returns the fragments and what placing the item takes.
- fn layout_inside_item(
- &mut self,
- run: &FormattingContextRun<'pass>,
- index: usize,
- ) -> (Option<fragment_tree::RunRootFragment>, formatting_context::PlacedChild) {
- let node = self.flex_items[index].box_;
+ fn item_run_request(&self, index: usize) -> (used_values::RootInputCells, LayoutInput) {
let mut cells = self.flex_item_details[index].cells;
// A button centers its content within its final main size even when that size can't resolve percentages.
if self.flex_items[index].alignment_facts.uses_button_layout
@@ -3370,20 +3377,23 @@ impl<'pass> FlexFormattingContext<'pass> {
cells.has_definite_block_size_only_for_button_content_alignment = true;
}
let input = self.item_layout_input(index, &cells, self.available_space_for_items.unwrap().space);
+ (cells, input)
+ }
+
+ /// Takes in the layout of the contents of the item at `index`, and returns the fragments and what placing the item
+ /// takes.
+ fn take_in_item_layout(
+ &mut self,
+ run: &FormattingContextRun<'pass>,
+ index: usize,
+ laid_out: formatting_context::ChildLayout,
+ ) -> (Option<fragment_tree::RunRootFragment>, formatting_context::PlacedChild) {
+ let node = self.flex_items[index].box_;
let formatting_context::ChildLayout {
outcome,
fragment_arrival,
laid_out_box,
- } = formatting_context::layout_inside_child_with_input_cells(
- run,
- None,
- None,
- node,
- input,
- cells,
- false,
- run.percentage_block_insets_of_root_children_have_definite_basis(&self.container_cells),
- );
+ } = laid_out;
self.flex_item_details[index].cells = laid_out_box.cells;
self.flex_item_details[index].orthogonal_flow_baselines = laid_out_box.orthogonal_flow_baselines;
outcome.report_percentage_block_size_dependency_of(run, node);
@@ -4301,10 +4311,82 @@ impl<'pass> FlexFormattingContext<'pass> {
let main_axis_is_horizontal = self.main_axis_is_horizontal();
let container_content_inline_size = self.container_cells.content_inline_size();
let mut items_awaiting_baseline_alignment = Vec::new();
+ let percentage_block_insets_have_definite_basis =
+ run.percentage_block_insets_of_root_children_have_definite_basis(&self.container_cells);
+ let candidates = self.fork_candidates();
+ let mut next_candidate = 0;
+ let mut laid_out_ahead = formatting_context::ChildRunsLaidOutAhead::default();
+ let mut handed_over_to_runs_laid_out_ahead = false;
+ let mut items_prepared = 0;
for index in 0..self.flex_items.len() {
- self.treat_used_cross_size_of_item_as_definite(index, container_cross_size_is_auto);
- self.copy_dimensions_from_flex_item_to_box(index, main_axis_is_horizontal, container_content_inline_size);
- let (fragment_arrival, placed_item) = self.layout_inside_item(run, index);
+ if index >= items_prepared {
+ self.treat_used_cross_size_of_item_as_definite(index, container_cross_size_is_auto);
+ self.copy_dimensions_from_flex_item_to_box(
+ index,
+ main_axis_is_horizontal,
+ container_content_inline_size,
+ );
+ items_prepared = index + 1;
+ }
+ let is_candidate = candidates.get(next_candidate) == Some(&index);
+ next_candidate += usize::from(is_candidate);
+ let node = self.flex_items[index].box_;
+ let laid_out = if let Some(laid_out) = laid_out_ahead.take(run, index) {
+ laid_out
+ } else {
+ let (cells, input) = self.item_run_request(index);
+ let planned = if is_candidate && !handed_over_to_runs_laid_out_ahead {
+ formatting_context::plan_child_run(
+ run,
+ node,
+ input,
+ cells,
+ percentage_block_insets_have_definite_basis,
+ )
+ } else {
+ formatting_context::PlannedChildRun::Unplanned(cells, input)
+ };
+ match planned {
+ formatting_context::PlannedChildRun::Job(job) if job.reuses_stored_run() => {
+ formatting_context::lay_out_child_run_job(run.callbacks, job)
+ }
+ formatting_context::PlannedChildRun::Job(job) => {
+ for later in index + 1..self.flex_items.len() {
+ self.treat_used_cross_size_of_item_as_definite(later, container_cross_size_is_auto);
+ self.copy_dimensions_from_flex_item_to_box(
+ later,
+ main_axis_is_horizontal,
+ container_content_inline_size,
+ );
+ }
+ items_prepared = self.flex_items.len();
+ handed_over_to_runs_laid_out_ahead = true;
+ laid_out_ahead = formatting_context::ChildRunsLaidOutAhead::lay_out_from_first_miss(
+ run,
+ (index, job),
+ candidates[next_candidate..].iter().map(|&later| {
+ let (cells, input) = self.item_run_request(later);
+ (later, self.flex_items[later].box_, cells, input)
+ }),
+ percentage_block_insets_have_definite_basis,
+ );
+ laid_out_ahead.take(run, index).expect("the item was laid out ahead")
+ }
+ formatting_context::PlannedChildRun::Unplanned(cells, input) => {
+ formatting_context::layout_inside_child_with_input_cells(
+ run,
+ None,
+ None,
+ node,
+ input,
+ cells,
+ false,
+ percentage_block_insets_have_definite_basis,
+ )
+ }
+ }
+ };
+ let (fragment_arrival, placed_item) = self.take_in_item_layout(run, index, laid_out);
if self.item_participates_in_baseline_alignment(index) {
items_awaiting_baseline_alignment.push((index, fragment_arrival, placed_item));
continue;
diff --git a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
index 27c0508561c..7f5a3055b6b 100644
--- a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
@@ -2031,16 +2031,47 @@ pub(super) fn run_formatting_context(
false,
);
}
- let cache_probe = fc_run_cache::FcRunCacheProbe::new(fc_type, &input, root_cells);
- let cache_attempt = match fc_run_cache::FcRunCacheAttempt::probe(
+ let attempt = fc_run_cache::FcRunCacheAttempt::probe(
box_,
subgrid_parent.is_some(),
builds_fragments,
should_collect_devtools_layout_data,
false,
&callbacks,
- &cache_probe,
- ) {
+ &fc_run_cache::FcRunCacheProbe::new(fc_type, &input, root_cells),
+ );
+ run_formatting_context_after_probe(
+ parent_collects_fragments,
+ root_cells,
+ box_,
+ root_containing_block,
+ subgrid_parent,
+ fc_type,
+ should_collect_devtools_layout_data,
+ callbacks,
+ input,
+ table_inline_layout,
+ attempt,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+fn run_formatting_context_after_probe(
+ parent_collects_fragments: bool,
+ root_cells: used_values::RootInputCells,
+ box_: Node,
+ root_containing_block: Node,
+ subgrid_parent: Option<&grid_formatting_context::SubgridParent>,
+ fc_type: FormattingContextType,
+ should_collect_devtools_layout_data: bool,
+ callbacks: LayoutPass<'_>,
+ input: LayoutInput,
+ table_inline_layout: Option<table_formatting_context::TableInlineLayout>,
+ attempt: Result<fc_run_cache::FcRunCacheAttempt, fc_run_cache::FcRunCacheHit>,
+) -> ChildLayout {
+ let builds_fragments = run_builds_fragments(&input, parent_collects_fragments);
+ let cache_probe = fc_run_cache::FcRunCacheProbe::new(fc_type, &input, root_cells);
+ let cache_attempt = match attempt {
Ok(attempt) => attempt,
Err(hit) => {
let _trace = callbacks.layout_trace().run(box_, fc_type, || {
@@ -3007,15 +3038,14 @@ pub(crate) fn layout_inside_child_with_input_cells(
depends_on_percentage_block_size: run.sizing().skipped_child_depends_on_percentage_block_size(child),
out_of_flow_root_used_insets,
};
- if !force_independent_context_run
- && !facts.node_has_size_containment()
- && matches!(
- input.participation,
- ParticipationInParentFormattingContext::AtomicInline
- )
- && created_fc_type == Some(FormattingContextType::Block)
- && run.callbacks.first_child(child).is_invalid()
- {
+ if is_empty_atomic_block_sized_in_parent_run(
+ run,
+ child,
+ facts,
+ created_fc_type,
+ &input,
+ force_independent_context_run,
+ ) {
// OPTIMIZATION: An empty atomic block has no formatting-context body output. Size it in the
// parent run, which will also construct its fragment when placing the box.
let cells_of_this_layout = Cell::new(child_input_cells);
@@ -3027,11 +3057,7 @@ pub(crate) fn layout_inside_child_with_input_cells(
);
return ChildLayout::of_child_sized_in_parent_run(skipped(None), cells_of_this_layout.get());
}
- let creates_replaced_context = matches!(
- created_fc_type,
- Some(FormattingContextType::InternalReplaced | FormattingContextType::ReplacedWithChildren)
- );
- if !facts.can_have_children() && !creates_replaced_context {
+ if is_childless_box_sized_in_parent_run(facts, created_fc_type) {
let cells_of_this_layout = Cell::new(child_input_cells);
let out_of_flow_root_used_insets =
size_skipped_independent_root(run, parent_block, child, &cells_of_this_layout, &input);
@@ -3072,6 +3098,211 @@ pub(crate) fn layout_inside_child_with_input_cells(
)
}
+fn is_empty_atomic_block_sized_in_parent_run(
+ run: &FormattingContextRun,
+ child: Node,
+ facts: NodeFacts<'_>,
+ created_fc_type: Option<FormattingContextType>,
+ input: &LayoutInput,
+ force_independent_context_run: bool,
+) -> bool {
+ !force_independent_context_run
+ && !facts.node_has_size_containment()
+ && matches!(
+ input.participation,
+ ParticipationInParentFormattingContext::AtomicInline
+ )
+ && created_fc_type == Some(FormattingContextType::Block)
+ && run.callbacks.first_child(child).is_invalid()
+}
+
+fn is_childless_box_sized_in_parent_run(facts: NodeFacts<'_>, created_fc_type: Option<FormattingContextType>) -> bool {
+ let creates_replaced_context = matches!(
+ created_fc_type,
+ Some(FormattingContextType::InternalReplaced | FormattingContextType::ReplacedWithChildren)
+ );
+ !facts.can_have_children() && !creates_replaced_context
+}
+
+pub(crate) struct ChildRunJob {
+ child: Node,
+ fc_type: FormattingContextType,
+ root_containing_block: Node,
+ input: LayoutInput,
+ root_cells: used_values::RootInputCells,
+ parent_collects_fragments: bool,
+ should_collect_devtools_layout_data: bool,
+ attempt: Result<fc_run_cache::FcRunCacheAttempt, fc_run_cache::FcRunCacheHit>,
+}
+
+impl ChildRunJob {
+ pub(crate) fn child(&self) -> Node {
+ self.child
+ }
+
+ pub(crate) fn reuses_stored_run(&self) -> bool {
+ self.attempt.is_err()
+ }
+}
+
+const _: () = {
+ const fn assert_send<T: Send>() {}
+ assert_send::<ChildRunJob>();
+ assert_send::<ChildLayout>();
+ assert_send::<ChildRunShape>();
+ assert_send::<table_formatting_context::TableInlineLayout>();
+};
+
+pub(crate) enum PlannedChildRun {
+ Job(ChildRunJob),
+ Unplanned(used_values::RootInputCells, LayoutInput),
+}
+
+pub(crate) fn plan_child_run(
+ run: &FormattingContextRun,
+ child: Node,
+ input: LayoutInput,
+ child_input_cells: used_values::RootInputCells,
+ percentage_block_insets_of_containing_block_have_definite_basis: bool,
+) -> PlannedChildRun {
+ let facts = NodeFacts::new(&run.callbacks, child);
+ let created_fc_type = formatting_context_type_created_by_box(facts);
+ if is_empty_atomic_block_sized_in_parent_run(run, child, facts, created_fc_type, &input, false)
+ || is_childless_box_sized_in_parent_run(facts, created_fc_type)
+ {
+ return PlannedChildRun::Unplanned(child_input_cells, input);
+ }
+ let ChildRunPlan {
+ fc_type,
+ root_containing_block,
+ input,
+ } = child_run_plan(
+ run,
+ child,
+ created_fc_type,
+ input,
+ false,
+ percentage_block_insets_of_containing_block_have_definite_basis,
+ );
+ let parent_collects_fragments = run.fragments.is_some();
+ let attempt = fc_run_cache::FcRunCacheAttempt::probe(
+ child,
+ false,
+ run_builds_fragments(&input, parent_collects_fragments),
+ run.should_collect_devtools_layout_data,
+ false,
+ &run.callbacks,
+ &fc_run_cache::FcRunCacheProbe::new(fc_type, &input, child_input_cells),
+ );
+ PlannedChildRun::Job(ChildRunJob {
+ child,
+ fc_type,
+ root_containing_block,
+ input,
+ root_cells: child_input_cells,
+ parent_collects_fragments,
+ should_collect_devtools_layout_data: run.should_collect_devtools_layout_data,
+ attempt,
+ })
+}
+
+fn lay_out_child_run_job_noting_its_host_findings(callbacks: LayoutPass<'_>, job: ChildRunJob) -> LaidOutChildRun {
+ let host_findings = run_state::HostFindingsSink::default();
+ let layout = lay_out_child_run_job(callbacks.noting_host_findings_in(&host_findings), job);
+ LaidOutChildRun {
+ layout,
+ host_findings: host_findings.take(),
+ }
+}
+
+pub(crate) struct LaidOutChildRun {
+ pub(crate) layout: ChildLayout,
+ pub(crate) host_findings: run_state::HostFindings,
+}
+
+#[derive(Default)]
+pub(crate) struct ChildRunsLaidOutAhead(Vec<Option<LaidOutChildRun>>);
+
+impl ChildRunsLaidOutAhead {
+ pub(crate) fn lay_out_from_first_miss(
+ run: &FormattingContextRun,
+ first_miss: (usize, ChildRunJob),
+ later: impl IntoIterator<Item = (usize, Node, used_values::RootInputCells, LayoutInput)>,
+ percentage_block_insets_have_definite_basis: bool,
+ ) -> Self {
+ let mut laid_out = Self(Vec::new());
+ let mut jobs = vec![first_miss];
+ for (index, child, cells, input) in later {
+ match plan_child_run(run, child, input, cells, percentage_block_insets_have_definite_basis) {
+ PlannedChildRun::Job(job) if job.reuses_stored_run() => {
+ laid_out.keep(
+ index,
+ lay_out_child_run_job_noting_its_host_findings(run.callbacks, job),
+ );
+ }
+ PlannedChildRun::Job(job) => jobs.push((index, job)),
+ PlannedChildRun::Unplanned(..) => {}
+ }
+ }
+ match parallel_layout::lay_out_in_parallel(
+ &run.callbacks,
+ jobs,
+ |(_, job)| job.child(),
+ |callbacks, (index, job)| (index, lay_out_child_run_job(callbacks, job)),
+ ) {
+ Ok(tasks) => {
+ for parallel_layout::ForkedTask {
+ result: (index, layout),
+ host_findings,
+ } in tasks
+ {
+ laid_out.keep(index, LaidOutChildRun { layout, host_findings });
+ }
+ }
+ Err(jobs) => {
+ for (index, job) in jobs {
+ laid_out.keep(
+ index,
+ lay_out_child_run_job_noting_its_host_findings(run.callbacks, job),
+ );
+ }
+ }
+ }
+ laid_out
+ }
+
+ fn keep(&mut self, index: usize, laid_out: LaidOutChildRun) {
+ if self.0.len() <= index {
+ self.0.resize_with(index + 1, || None);
+ }
+ self.0[index] = Some(laid_out);
+ }
+
+ pub(crate) fn take(&mut self, run: &FormattingContextRun, index: usize) -> Option<ChildLayout> {
+ let LaidOutChildRun { layout, host_findings } = self.0.get_mut(index)?.take()?;
+ if !host_findings.is_empty() {
+ run.callbacks.note_host_findings(|into| into.receive(host_findings));
+ }
+ Some(layout)
+ }
+}
+
+pub(crate) fn lay_out_child_run_job(callbacks: LayoutPass<'_>, job: ChildRunJob) -> ChildLayout {
+ run_formatting_context_after_probe(
+ job.parent_collects_fragments,
+ job.root_cells,
+ job.child,
+ job.root_containing_block,
+ None,
+ job.fc_type,
+ job.should_collect_devtools_layout_data,
+ callbacks,
+ job.input,
+ None,
+ job.attempt,
+ )
+}
+
/// Hands what the layout of a child handed its placement to the run's fragment builder, where the child is laid out
/// but not placed.
pub(crate) fn leave_child_unplaced(
@@ -3666,7 +3897,10 @@ fn compute_root_layout(input: LayoutStageInput<'_>, should_collect_devtools_layo
stage,
} = input;
let host_findings_outside_runs = super::run_state::HostFindingsSink::default();
- let callbacks = LayoutPass::new(arena, scratch, &host_findings_outside_runs, stage);
+ let mut callbacks = LayoutPass::new(arena, scratch, &host_findings_outside_runs, stage);
+ if !should_collect_devtools_layout_data {
+ callbacks = callbacks.forking_runs();
+ }
let viewport_inline_size = stage.viewport_inline_size;
let viewport_block_size = stage.viewport_block_size;
@@ -3821,7 +4055,7 @@ fn compute_subtree_layout_fragments(input: LayoutStageInput<'_>, containing_bloc
stage,
} = input;
let host_findings_outside_runs = super::run_state::HostFindingsSink::default();
- let callbacks = LayoutPass::new(arena, scratch, &host_findings_outside_runs, stage);
+ let callbacks = LayoutPass::new(arena, scratch, &host_findings_outside_runs, stage).forking_runs();
// NB: Either way, the boundary root's own geometry lies in the frame of its containing block.
let callbacks = if containing_block.is_invalid() {
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs b/Libraries/LibWeb/Rust/src/layout/layout_pass.rs
index 41c8247d7ae..3825ae76ead 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_pass.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_pass.rs
@@ -43,6 +43,7 @@ pub(crate) struct LayoutPass<'arena> {
/// The innermost of the position options the boxes this pass view lays out are laid out with.
position_option_styles: Option<&'arena PositionOptionStyle<'arena>>,
records_trace: bool,
+ forks_runs: bool,
worker_scratch: WorkerScratchOfThisThread,
}
@@ -130,15 +131,45 @@ impl<'arena> LayoutPass<'arena> {
reads_no_memoized_layout: false,
position_option_styles: None,
records_trace: scratch.layout_trace.is_recording(),
+ forks_runs: false,
worker_scratch: WorkerScratchOfThisThread::get(),
}
}
+ pub(super) fn on_this_thread(self) -> Self {
+ Self {
+ worker_scratch: WorkerScratchOfThisThread::get(),
+ ..self
+ }
+ }
+
#[inline]
pub(super) fn worker_scratch(&self) -> &WorkerScratch {
self.worker_scratch.scratch()
}
+ pub(crate) fn forking_runs(self) -> Self {
+ Self {
+ forks_runs: true,
+ ..self
+ }
+ }
+
+ pub(super) fn forks_runs(&self) -> bool {
+ self.forks_runs && !self.reads_no_memoized_layout && !self.records_trace
+ }
+
+ pub(super) fn noting_host_findings_in<'findings>(
+ self,
+ host_findings: &'findings super::run_state::HostFindingsSink,
+ ) -> LayoutPass<'findings>
+ where
+ 'arena: 'findings,
+ {
+ let pass: LayoutPass<'findings> = self;
+ LayoutPass { host_findings, ..pass }
+ }
+
/// A pass over `arena` and `scratch` with no viewport, in no-quirks mode.
#[cfg(test)]
pub(crate) fn for_test(
@@ -311,6 +342,7 @@ impl<'arena> LayoutPass<'arena> {
key: &super::rendered_text::TextChunkCacheKey,
compute: impl FnOnce() -> super::text_chunker::ChunkedText,
) -> std::sync::Arc<super::rendered_text::CachedTextChunks> {
+ super::parallel_layout::check_row_reached_by_forked_task(node.slot_index() as usize, true);
self.scratch.text_memos().text_chunks(
self.text_state_index(node),
self.text_content(node).rendered(),
@@ -344,6 +376,7 @@ impl<'arena> LayoutPass<'arena> {
node: Node,
read: impl FnOnce(&super::text_chunker::GraphemeSegmenter) -> R,
) -> R {
+ super::parallel_layout::check_row_reached_by_forked_task(node.slot_index() as usize, true);
self.scratch.text_memos().with_grapheme_segmenter(
self.text_state_index(node),
self.text_content(node).rendered(),
diff --git a/Libraries/LibWeb/Rust/src/layout/mod.rs b/Libraries/LibWeb/Rust/src/layout/mod.rs
index bdd542b434e..69aab01a056 100644
--- a/Libraries/LibWeb/Rust/src/layout/mod.rs
+++ b/Libraries/LibWeb/Rust/src/layout/mod.rs
@@ -41,6 +41,7 @@ pub(crate) mod math_formatting_context;
mod memo_invalidations;
pub mod node_data;
pub(crate) mod node_facts;
+mod parallel_layout;
mod pass_column;
pub(crate) mod tree_shape;
pub use libcompositing_rust::node_slot_id;
diff --git a/Libraries/LibWeb/Rust/src/layout/parallel_layout.rs b/Libraries/LibWeb/Rust/src/layout/parallel_layout.rs
new file mode 100644
index 00000000000..e9fd94988e7
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/layout/parallel_layout.rs
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+use rayon::prelude::*;
+use std::sync::LazyLock;
+
+enum ForkMode {
+ Sequential,
+ OnStyleLayoutThreads,
+ ReversedOnCallingThread,
+}
+
+struct ForkSettings {
+ mode: ForkMode,
+ forces_forks: bool,
+ verifies_subtree_leases: bool,
+}
+
+static SUBTREE_LEASES_ARE_VERIFIED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
+static FORK_SETTINGS: LazyLock<ForkSettings> = LazyLock::new(|| {
+ let verification = std::env::var("LIBWEB_VERIFY_LAYOUT_FORKS").unwrap_or_default();
+ let mode = if verification == "reversed" {
+ ForkMode::ReversedOnCallingThread
+ } else if std::env::var("LIBWEB_LAYOUT_THREADS").is_ok_and(|threads| threads == "1") {
+ ForkMode::Sequential
+ } else {
+ ForkMode::OnStyleLayoutThreads
+ };
+ let verifies_subtree_leases = std::env::var("LIBWEB_VERIFY_LAYOUT_FORK_SCOPE").is_ok_and(|value| value == "1");
+ SUBTREE_LEASES_ARE_VERIFIED.store(verifies_subtree_leases, std::sync::atomic::Ordering::Relaxed);
+ ForkSettings {
+ mode,
+ forces_forks: matches!(verification.as_str(), "always" | "reversed"),
+ verifies_subtree_leases,
+ }
+});
+
+const BOXES_COUNTED_PER_JOB: usize = 16;
+const MINIMUM_BOXES_FORKED_FROM_A_STYLE_LAYOUT_THREAD: usize = 64;
+const MINIMUM_BOXES_FORKED_ONTO_STYLE_LAYOUT_THREADS: usize = 128;
+
+pub(crate) fn fork_candidates<T: Copy>(
+ pass: &LayoutPass<'_>,
+ items: impl IntoIterator<Item = T>,
+ root_of: impl Fn(T) -> Node,
+) -> Vec<T> {
+ let settings = &*FORK_SETTINGS;
+ let on_style_layout_thread = rayon::current_thread_index().is_some();
+ if matches!(settings.mode, ForkMode::Sequential)
+ || !pass.forks_runs()
+ || (matches!(settings.mode, ForkMode::OnStyleLayoutThreads)
+ && !on_style_layout_thread
+ && style_layout_pool(pass).is_none())
+ {
+ return Vec::new();
+ }
+ let arena = pass.arena();
+ let mut candidates = Vec::new();
+ let mut boxes = 0;
+ let mut sizeable_jobs = 0;
+ for item in items {
+ let root = root_of(item);
+ if arena.data(root).first_child.get().is_invalid() {
+ continue;
+ }
+ let counted = boxes_in_subtree_up_to(arena, root, BOXES_COUNTED_PER_JOB);
+ boxes += counted;
+ sizeable_jobs += usize::from(counted >= BOXES_COUNTED_PER_JOB);
+ candidates.push(item);
+ }
+ if !on_style_layout_thread && sizeable_jobs >= 2 && boxes < MINIMUM_BOXES_FORKED_ONTO_STYLE_LAYOUT_THREADS {
+ let limit = MINIMUM_BOXES_FORKED_ONTO_STYLE_LAYOUT_THREADS.div_ceil(candidates.len());
+ boxes = candidates
+ .iter()
+ .map(|&item| boxes_in_subtree_up_to(arena, root_of(item), limit))
+ .sum();
+ }
+ let worth_forking = settings.forces_forks
+ || (candidates.len() >= 2
+ && if on_style_layout_thread {
+ sizeable_jobs >= 2 || boxes >= MINIMUM_BOXES_FORKED_FROM_A_STYLE_LAYOUT_THREAD
+ } else {
+ boxes >= MINIMUM_BOXES_FORKED_ONTO_STYLE_LAYOUT_THREADS
+ });
+ if !worth_forking {
+ candidates.clear();
+ }
+ candidates
+}
+
+pub(crate) struct ForkedTask<R> {
+ pub(crate) result: R,
+ pub(crate) host_findings: run_state::HostFindings,
+}
+
+pub(crate) fn lay_out_in_parallel<J: Send, R: Send>(
+ pass: &LayoutPass<'_>,
+ jobs: Vec<J>,
+ root_of: impl Fn(&J) -> Node + Sync,
+ run: impl Fn(LayoutPass<'_>, J) -> R + Sync,
+) -> Result<Vec<ForkedTask<R>>, Vec<J>> {
+ let settings = &*FORK_SETTINGS;
+ if matches!(settings.mode, ForkMode::Sequential)
+ || !pass.forks_runs()
+ || jobs.is_empty()
+ || (jobs.len() < 2 && !settings.forces_forks)
+ {
+ return Err(jobs);
+ }
+ let pass = *pass;
+ let run_task = |job: J| {
+ let host_findings = run_state::HostFindingsSink::default();
+ let lease = SubtreeLease::of(pass.arena(), root_of(&job));
+ let result = lease.while_held(settings.verifies_subtree_leases, || {
+ run(pass.on_this_thread().noting_host_findings_in(&host_findings), job)
+ });
+ ForkedTask {
+ result,
+ host_findings: host_findings.take(),
+ }
+ };
+ match settings.mode {
+ ForkMode::Sequential => Err(jobs),
+ ForkMode::OnStyleLayoutThreads => {
+ if rayon::current_thread_index().is_some() {
+ if !stack_has_room_for_forked_jobs(pass.arena()) {
+ return Err(jobs);
+ }
+ return Ok(jobs.into_par_iter().map(run_task).collect());
+ }
+ let Some(pool) = style_layout_pool(&pass) else {
+ return Err(jobs);
+ };
+ Ok(pool.install(|| jobs.into_par_iter().map(run_task).collect()))
+ }
+ ForkMode::ReversedOnCallingThread => {
+ let mut tasks: Vec<_> = jobs.into_iter().rev().map(run_task).collect();
+ tasks.reverse();
+ Ok(tasks)
+ }
+ }
+}
+
+fn style_layout_pool(pass: &LayoutPass<'_>) -> Option<std::sync::Arc<rayon::ThreadPool>> {
+ pass.arena()
+ .with_style_store(crate::css::style::RetainedState::started_style_layout_pool)
+}
+
+fn boxes_in_subtree_up_to(arena: &LayoutNodeArena, root: Node, limit: usize) -> usize {
+ let mut counted = 0;
+ let mut current = Some(root);
+ while let Some(node) = current {
+ counted += 1;
+ if counted >= limit {
+ break;
+ }
+ current = arena.next_node_in_layout_subtree_in_pre_order(root, node);
+ }
+ counted
+}
+
+fn stack_has_room_for_forked_jobs(arena: &LayoutNodeArena) -> bool {
+ let element_depth = arena.with_style_store(crate::css::style::RetainedState::deepest_element_depth);
+ let box_depth = element_depth.saturating_mul(2).saturating_add(32);
+ crate::render_state::stack_has_room_for_render_job(box_depth.saturating_mul(2))
+}
+
+#[derive(Clone, Copy)]
+struct SubtreeLease {
+ arena: *const LayoutNodeArena,
+ root: Node,
+ first_label: u64,
+ label_past_subtree: u64,
+}
+
+thread_local! {
+ static SUBTREE_LEASE_OF_THIS_THREAD: std::cell::Cell<Option<SubtreeLease>> = const { std::cell::Cell::new(None) };
+}
+
+impl SubtreeLease {
+ fn of(arena: &LayoutNodeArena, root: Node) -> Self {
+ Self {
+ arena: std::ptr::from_ref(arena),
+ root,
+ first_label: arena.node_pre_order_label(root),
+ label_past_subtree: arena.pre_order_label_of_subtree_successor(root),
+ }
+ }
+
+ fn while_held<R>(self, verifies: bool, run: impl FnOnce() -> R) -> R {
+ if !verifies {
+ return run();
+ }
+ let enclosing = SUBTREE_LEASE_OF_THIS_THREAD.replace(Some(self));
+ let result = run();
+ SUBTREE_LEASE_OF_THIS_THREAD.set(enclosing);
+ result
+ }
+
+ fn covers(&self, arena: &LayoutNodeArena, node: Node) -> bool {
+ (self.first_label..self.label_past_subtree).contains(&arena.node_pre_order_label(node))
+ }
+}
+
+#[inline]
+pub(super) fn check_row_reached_by_forked_task(slot: usize, writes: bool) {
+ if SUBTREE_LEASES_ARE_VERIFIED.load(std::sync::atomic::Ordering::Relaxed) {
+ check_row_reached_under_the_lease_of_this_thread(slot, writes);
+ }
+}
+
+#[cold]
+#[inline(never)]
+fn check_row_reached_under_the_lease_of_this_thread(slot: usize, writes: bool) {
+ let Some(lease) = SUBTREE_LEASE_OF_THIS_THREAD.get() else {
+ return;
+ };
+ // SAFETY: A lease is held only while the task it names runs, which borrows the arena.
+ let arena = unsafe { &*lease.arena };
+ let Some(node) = u32::try_from(slot).ok().and_then(|slot| arena.live_slot_at(slot)) else {
+ panic!(
+ "a forked layout task rooted at {:?} reached the row of slot {slot}, which holds no box",
+ lease.root
+ );
+ };
+ if lease.covers(arena, node) || (!writes && is_inclusive_ancestor(arena, node, lease.root)) {
+ return;
+ }
+ panic!(
+ "a forked layout task rooted at {:?} {} the row of {node:?}, outside its subtree",
+ lease.root,
+ if writes { "wrote" } else { "read" }
+ );
+}
+
+fn is_inclusive_ancestor(arena: &LayoutNodeArena, ancestor: Node, node: Node) -> bool {
+ let mut current = node;
+ while !current.is_invalid() {
+ if current == ancestor {
+ return true;
+ }
+ current = arena.data(current).parent.get();
+ }
+ false
+}
diff --git a/Libraries/LibWeb/Rust/src/layout/pass_column.rs b/Libraries/LibWeb/Rust/src/layout/pass_column.rs
index 402752f140b..0aad0c9b00a 100644
--- a/Libraries/LibWeb/Rust/src/layout/pass_column.rs
+++ b/Libraries/LibWeb/Rust/src/layout/pass_column.rs
@@ -52,6 +52,7 @@ impl<T> Drop for OwnedChunk<T> {
pub(crate) struct PassColumn<T> {
chunks: Vec<OwnedChunk<T>>,
+ rows_are_slots: bool,
}
// SAFETY: A pass writes a row only from the run that lays out the row's box. The runs laid out at once on several
@@ -74,7 +75,26 @@ impl<T> ExclusiveRow<T> {
impl<T> Default for PassColumn<T> {
fn default() -> Self {
- Self { chunks: Vec::new() }
+ Self {
+ chunks: Vec::new(),
+ rows_are_slots: true,
+ }
+ }
+}
+
+impl<T> PassColumn<T> {
+ pub(crate) fn with_rows_of_no_slot() -> Self {
+ Self {
+ rows_are_slots: false,
+ ..Self::default()
+ }
+ }
+
+ fn empty_like<OtherRow>(&self) -> PassColumn<OtherRow> {
+ PassColumn {
+ rows_are_slots: self.rows_are_slots,
+ ..PassColumn::default()
+ }
}
}
@@ -98,7 +118,10 @@ impl<T: Default> PassColumn<T> {
#[inline]
fn table(&self) -> ChunkTable<'_, T> {
- ChunkTable { chunks: &self.chunks }
+ ChunkTable {
+ chunks: &self.chunks,
+ rows_are_slots: self.rows_are_slots,
+ }
}
pub(crate) fn row_mut(&mut self, index: usize) -> Option<&mut T> {
@@ -118,6 +141,7 @@ impl<T: Default> PassColumn<T> {
struct ChunkTable<'column, T> {
chunks: &'column [OwnedChunk<T>],
+ rows_are_slots: bool,
}
impl<T> Clone for ChunkTable<'_, T> {
@@ -131,6 +155,9 @@ impl<T> Copy for ChunkTable<'_, T> {}
impl<'column, T: Default> ChunkTable<'column, T> {
#[inline]
fn with_row<R>(self, index: usize, read: impl FnOnce(Option<&T>) -> R) -> R {
+ if self.rows_are_slots {
+ super::parallel_layout::check_row_reached_by_forked_task(index, false);
+ }
let Some(chunk) = self.chunk_for_reading(index / ROWS_PER_CHUNK) else {
return read(None);
};
@@ -142,6 +169,9 @@ impl<'column, T: Default> ChunkTable<'column, T> {
#[inline]
fn with_row_mut<R>(self, index: usize, write: impl FnOnce(&mut T) -> R) -> R {
+ if self.rows_are_slots {
+ super::parallel_layout::check_row_reached_by_forked_task(index, true);
+ }
let chunk = self.chunk_for_writing(index / ROWS_PER_CHUNK);
let _borrow = RowBorrow::exclusive(chunk, index % ROWS_PER_CHUNK);
// SAFETY: Only the run laying out the row's box reaches the row while it writes it (`RowBorrow` checks that in
@@ -260,6 +290,7 @@ pub(crate) struct ForkSharedRows<T> {
struct ChunkTableOfTheHost<T> {
chunks: std::ptr::NonNull<OwnedChunk<T>>,
chunk_count: usize,
+ rows_are_slots: bool,
}
// SAFETY: It points into the chunk table of the host's column, which is Send and Sync as `HostRows` is.
@@ -272,6 +303,7 @@ impl<T> ChunkTableOfTheHost<T> {
Self {
chunks: std::ptr::NonNull::new(column.chunks.as_ptr().cast_mut()).expect("a Vec's pointer is never null"),
chunk_count: column.chunks.len(),
+ rows_are_slots: column.rows_are_slots,
}
}
@@ -279,6 +311,7 @@ impl<T> ChunkTableOfTheHost<T> {
Self {
chunks: std::ptr::NonNull::dangling(),
chunk_count: 0,
+ rows_are_slots: false,
}
}
}
@@ -318,6 +351,10 @@ impl<T> Default for ForkSharedRows<T> {
}
impl<T> ForkSharedRows<T> {
+ pub(crate) fn with_rows_of_no_slot() -> Self {
+ Self::with_host_rows(PassColumn::with_rows_of_no_slot(), PassColumn::with_rows_of_no_slot())
+ }
+
fn with_host_rows(rows: PassColumn<T>, fork_generation_each_row_was_saved_for: PassColumn<u32>) -> Self {
Self {
chunk_table_of_the_host: ChunkTableOfTheHost::of(&rows),
@@ -351,6 +388,7 @@ impl<T: Clone + Default> ForkSharedRows<T> {
self.chunk_table_of_the_host.chunk_count,
)
},
+ rows_are_slots: self.chunk_table_of_the_host.rows_are_slots,
}
}
@@ -372,7 +410,7 @@ impl<T: Clone + Default> ForkSharedRows<T> {
*handed_out += 1;
*handed_out
};
- let mut rows = PassColumn::default();
+ let mut rows = self.host_rows().empty_like();
rows.cover_slots(rows_the_host_held_at_fork);
let rows_saved_by_host = std::sync::Arc::new(RowsSavedForFork {
generation,
@@ -388,7 +426,7 @@ impl<T: Clone + Default> ForkSharedRows<T> {
chunk_table_of_the_host: ChunkTableOfTheHost::of_a_fork(),
fork_side: Some(ForkSide {
rows_saved_by_host,
- own_rows: PassColumn::default(),
+ own_rows: self.host_rows().empty_like(),
reads_host_rows: true,
}),
}
diff --git a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
index d86aca50e4c..33a4da0ce10 100644
--- a/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
+++ b/Libraries/LibWeb/Rust/src/layout/rendered_text.rs
@@ -217,7 +217,6 @@ impl TextContent {
/// What layout keeps beside the rendered text of the text rows it lays out: the chunks the last run that chunked a row
/// made, and the row's grapheme segmenter. Each keeps the rendered text it was made for, which tells whether the row's
/// text is still that text. They are indexed by the row's text state in the arena, so boxes without text take no room.
-#[derive(Default)]
pub(crate) struct TextMemos {
/// Written in place, while a fork of the arena reads them as they were when it was made.
chunks: super::pass_column::ForkSharedRows<Option<ChunksOfText>>,
@@ -238,12 +237,21 @@ struct GraphemeSegmenterOfText {
rendered: Arc<RenderedText>,
}
+impl Default for TextMemos {
+ fn default() -> Self {
+ Self {
+ chunks: super::pass_column::ForkSharedRows::with_rows_of_no_slot(),
+ grapheme_segmenters: super::pass_column::PassColumn::with_rows_of_no_slot(),
+ }
+ }
+}
+
impl TextMemos {
/// The memos of a fork of the arena, which keeps the chunks and makes grapheme segmenters anew.
pub(crate) fn fork(&self) -> Self {
Self {
chunks: self.chunks.fork(),
- grapheme_segmenters: Default::default(),
+ grapheme_segmenters: super::pass_column::PassColumn::with_rows_of_no_slot(),
}
}
diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rs
index 0e0e5543515..510d7e1af6f 100644
--- a/Libraries/LibWeb/Rust/src/render_state.rs
+++ b/Libraries/LibWeb/Rust/src/render_state.rs
@@ -899,7 +899,7 @@ fn wait_for_render_side() {
/// Whether the calling thread's stack has room for a job on a render state that recurses through a tree `tree_depth`
/// levels deep. Only the Render thread's stack is large enough for any tree.
#[cfg(not(test))]
-fn stack_has_room_for_render_job(tree_depth: u32) -> bool {
+pub(crate) fn stack_has_room_for_render_job(tree_depth: u32) -> bool {
/// The stack a job on a render state takes at most per level of the tree it recurses through, as it builds and
/// lays out boxes, with room to spare for the boxes a level adds: release builds took about 1.5 KiB per element,
/// and debug builds about 2 KiB.
@@ -927,7 +927,7 @@ fn stack_has_room_for_render_job(tree_depth: u32) -> bool {
}
#[cfg(test)]
-fn stack_has_room_for_render_job(_: u32) -> bool {
+pub(crate) fn stack_has_room_for_render_job(_: u32) -> bool {
false
}
diff --git a/Libraries/LibWeb/Rust/src/stage_thread.rs b/Libraries/LibWeb/Rust/src/stage_thread.rs
index a875f7d82b5..e40d853f094 100644
--- a/Libraries/LibWeb/Rust/src/stage_thread.rs
+++ b/Libraries/LibWeb/Rust/src/stage_thread.rs
@@ -119,7 +119,7 @@ pub extern "C" fn stage_thread_set_flight_finished(finished: extern "C" fn()) {
// Building and laying out boxes recurse once per tree level. The 8 MiB Linux and macOS give a process's main thread
// overflowed at about 5700 nested elements in release builds and fewer in debug builds. A thread stack is reserved,
// not committed, so the larger size costs address space only.
-const STAGE_THREAD_STACK_SIZE: usize = 64 * 1024 * 1024;
+pub(crate) const STAGE_THREAD_STACK_SIZE: usize = 64 * 1024 * 1024;
impl StageThread {
/// Spawns a thread named `name`, which lives as long as the process.
diff --git a/Libraries/LibWeb/Rust/src/style_layout_pool.rs b/Libraries/LibWeb/Rust/src/style_layout_pool.rs
index 2830ef85f3b..c101bef3ee7 100644
--- a/Libraries/LibWeb/Rust/src/style_layout_pool.rs
+++ b/Libraries/LibWeb/Rust/src/style_layout_pool.rs
@@ -101,6 +101,7 @@ fn workers_for_threads(threads: u32) -> usize {
fn start_threads(workers: usize) -> rayon::ThreadPool {
rayon::ThreadPoolBuilder::new()
.num_threads(workers)
+ .stack_size(crate::stage_thread::STAGE_THREAD_STACK_SIZE)
.thread_name(|index| format!("StyleLayout {index}"))
.build()
.expect("the style and layout thread pool starts")
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 3938dcfff3d..3e618344fed 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -97,6 +97,8 @@ RENDER_STATE_ALLOWED = {
**render_state_entries(
ENVIRONMENT_SWITCH,
[
+ "layout/parallel_layout.rs:FORK_SETTINGS",
+ "layout/parallel_layout.rs:SUBTREE_LEASES_ARE_VERIFIED",
"layout/run_repeatability.rs:ENABLED",
"layout/run_repeatability.rs:VERIFICATION",
"render_state/clock/hover.rs:LOGS",
@@ -125,6 +127,7 @@ RENDER_STATE_ALLOWED = {
["render_state/owner.rs:DROPPED_AFTER_HOLD"],
),
f"{RENDER_STATE_CRATE}/src/render_state.rs:STACK_BASE": "per-thread cache of the thread's own stack bounds",
+ f"{RENDER_STATE_CRATE}/src/layout/parallel_layout.rs:SUBTREE_LEASE_OF_THIS_THREAD": "per-thread lease of the subtree the layout task running on the thread may write, held only while LIBWEB_VERIFY_LAYOUT_FORK_SCOPE checks it and only for that task",
f"{RENDER_STATE_CRATE}/src/layout/layout_pass.rs:WORKER_SCRATCH_OF_THIS_THREAD": "per-thread spare layout buffers and the fragment identities the thread reserved; a thread without one only allocates more and reserves another range",
f"{RENDER_STATE_CRATE}/src/stage_thread.rs:UNFINISHED_HANDED": "per-thread count of the jobs the thread made for each stage thread that have yet to run",
**render_state_entries(
diff --git a/Tests/LibWeb/Text/expected/layout-sibling-subtrees-in-parallel.txt b/Tests/LibWeb/Text/expected/layout-sibling-subtrees-in-parallel.txt
new file mode 100644
index 00000000000..60bc4967428
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/layout-sibling-subtrees-in-parallel.txt
@@ -0,0 +1,4 @@
+340 boxes
+shrink-to-fit root: 800x1040, digest 798898209
+narrower root: 300x1220, digest 806122313
+one grid padded: 300x1220, digest 332182852
diff --git a/Tests/LibWeb/Text/input/layout-sibling-subtrees-in-parallel.html b/Tests/LibWeb/Text/input/layout-sibling-subtrees-in-parallel.html
new file mode 100644
index 00000000000..bba0aa39d08
--- /dev/null
+++ b/Tests/LibWeb/Text/input/layout-sibling-subtrees-in-parallel.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<script src="include.js"></script>
+<style>
+ body { margin: 0; font: 10px/10px SerenitySans; }
+ #root { position: absolute; }
+ .row { display: flex; }
+ .column { display: flex; flex-direction: column; }
+ .grid { display: grid; grid-template-columns: auto auto; }
+</style>
+<div id="root"></div>
+<script>
+ function nestedBoxes(depth, index) {
+ const kinds = ["row", "column", "grid", "block"];
+ const box = document.createElement("div");
+ box.className = kinds[(depth + index) % kinds.length];
+ if (depth === 0) {
+ box.textContent = "word ".repeat(1 + (index % 3));
+ return box;
+ }
+ for (let child = 0; child < 4; ++child)
+ box.appendChild(nestedBoxes(depth - 1, child));
+ return box;
+ }
+
+ function digestOfBoxesIn(root) {
+ let digest = 0;
+ for (const element of root.querySelectorAll("*")) {
+ const rect = element.getBoundingClientRect();
+ const mixed = Math.round((rect.x + rect.y * 3 + rect.width * 5 + rect.height * 7) * 64);
+ digest = (digest * 31 + mixed) % 1000000007;
+ }
+ const rect = root.getBoundingClientRect();
+ return `${rect.width}x${rect.height}, digest ${digest}`;
+ }
+
+ test(() => {
+ const root = document.getElementById("root");
+ for (let index = 0; index < 4; ++index)
+ root.appendChild(nestedBoxes(3, index));
+ println(`${root.querySelectorAll("*").length} boxes`);
+ println(`shrink-to-fit root: ${digestOfBoxesIn(root)}`);
+ root.style.width = "300px";
+ println(`narrower root: ${digestOfBoxesIn(root)}`);
+ root.querySelector(".grid").style.paddingLeft = "7px";
+ println(`one grid padded: ${digestOfBoxesIn(root)}`);
+ });
+</script>