Truly independent web browser
LibWeb: Splice subtrees with balanced quotes into the layout tree
Aliaksandr Kalenikccd186c70ed5
diff --git a/Libraries/LibWeb/CSS/GeneratedContent.cpp b/Libraries/LibWeb/CSS/GeneratedContent.cppindex fbf1de9c7fb..bca8e735d32 100644--- a/Libraries/LibWeb/CSS/GeneratedContent.cpp+++ b/Libraries/LibWeb/CSS/GeneratedContent.cpp@@ -11,15 +11,10 @@namespace Web::CSS {-static bool style_affects_generated_content_state(ComputedValues const& style)+static bool subtree_has_generated_content_facts(DOM::Node const& node, u8 facts){- return style.generated_content_facts() & (ComputedValuesFFI::GENERATED_CONTENT_DEFINES_COUNTERS | ComputedValuesFFI::GENERATED_CONTENT_HAS_QUOTES);-}--bool subtree_affects_generated_content_state(DOM::Node const& node)-{- auto style_affects_state = [](auto const& style) {- return style && style_affects_generated_content_state(*style);+ auto style_affects_state = [facts](auto const& style) {+ return style && (style->generated_content_facts() & facts);};bool affects_generated_content_state = false;node.for_each_in_inclusive_subtree([&](DOM::Node const& descendant) {@@ -43,4 +38,14 @@ bool subtree_affects_generated_content_state(DOM::Node const& node)return affects_generated_content_state;}+bool subtree_affects_generated_content_state(DOM::Node const& node)+{+ return subtree_has_generated_content_facts(node, ComputedValuesFFI::GENERATED_CONTENT_DEFINES_COUNTERS | ComputedValuesFFI::GENERATED_CONTENT_HAS_QUOTES);+}++bool subtree_affects_counters(DOM::Node const& node)+{+ return subtree_has_generated_content_facts(node, ComputedValuesFFI::GENERATED_CONTENT_DEFINES_COUNTERS);+}+}diff --git a/Libraries/LibWeb/CSS/GeneratedContent.h b/Libraries/LibWeb/CSS/GeneratedContent.hindex 2d663e20041..1cc7a3f7047 100644--- a/Libraries/LibWeb/CSS/GeneratedContent.h+++ b/Libraries/LibWeb/CSS/GeneratedContent.h@@ -15,5 +15,6 @@ class Node;namespace Web::CSS {bool subtree_affects_generated_content_state(DOM::Node const&);+bool subtree_affects_counters(DOM::Node const&);}diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cppindex d8e29b93718..1029dc347cd 100644--- a/Libraries/LibWeb/DOM/Node.cpp+++ b/Libraries/LibWeb/DOM/Node.cpp@@ -1537,7 +1537,7 @@ void Node::update_layout_tree_for_removal(Layout::BegunRead const& read, Node& pauto* parent_element = as_if<Element>(parent);auto const* element = as_if<Element>(*this);if (removal == LayoutSubtreeRemoval::DetachInPlace && has_layout_box() && parent_element && parent_element->has_layout_box()- && !(element && element->rendered_in_top_layer()) && !CSS::subtree_affects_generated_content_state(*this)) {+ && !(element && element->rendered_in_top_layer()) && !CSS::subtree_affects_counters(*this)) {Layout::RustFFI::render_state_remove_box(document().layout_node_arena().host(), parent_element->style_node_id().value(), Layout::Node::style_node_of(this).value(),detached_box_facts(*this, parent, Layout::RustFFI::FfiDetachedBoxLevel::FromStyle));document().set_needs_repaint(Badge<Node> {}, InvalidateDisplayList::No);diff --git a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs b/Libraries/LibWeb/Rust/src/css/computed_value_views.rsindex f87e410bc9e..b7d00b786f6 100644--- a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs+++ b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs@@ -390,6 +390,58 @@ fn decode_css_preferred_aspect_ratio(ratio: &ComputedAspectRatio) -> (CssPixels,(numerator, denominator)}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct QuoteTransfer {+ outer_quotes_closed: u32,+ quotes_left_open: u32,+}++impl QuoteTransfer {+ pub(crate) const IDENTITY: Self = Self {+ outer_quotes_closed: 0,+ quotes_left_open: 0,+ };++ fn then_quote(self, opens: bool) -> Self {+ match (opens, self.quotes_left_open) {+ (true, quotes_left_open) => Self {+ quotes_left_open: quotes_left_open + 1,+ ..self+ },+ (false, 0) => Self {+ outer_quotes_closed: self.outer_quotes_closed + 1,+ ..self+ },+ (false, quotes_left_open) => Self {+ quotes_left_open: quotes_left_open - 1,+ ..self+ },+ }+ }++ pub(crate) fn then(self, next: Self) -> Self {+ if self.quotes_left_open >= next.outer_quotes_closed {+ Self {+ outer_quotes_closed: self.outer_quotes_closed,+ quotes_left_open: self.quotes_left_open - next.outer_quotes_closed + next.quotes_left_open,+ }+ } else {+ Self {+ outer_quotes_closed: self.outer_quotes_closed + next.outer_quotes_closed - self.quotes_left_open,+ quotes_left_open: next.quotes_left_open,+ }+ }+ }++ pub(crate) fn is_identity(self) -> bool {+ self == Self::IDENTITY+ }++ pub(crate) fn apply(self, depth: u32) -> u32 {+ depth.saturating_sub(self.outer_quotes_closed) + self.quotes_left_open+ }+}+/// A borrowed view over one node's computed style group payloads: the Rust/// twin of the C++ ComputedValues accessor surface. Every read hands out/// payload references or lazy views; the payloads must stay alive and@@ -678,22 +730,36 @@ impl<'a> ComputedValuesView<'a> {/// Whether `content` opens or closes a quote, which moves the quote depth that every quote after it reads.pub(crate) fn content_opens_or_closes_quotes(self) -> bool {- let Some(StyleValueData::Content { content, .. }) = self.content().content.data() else {- return false;- };- let Some(StyleValueData::ValueList { values, .. }) = content.optional_data() else {- return false;+ self.content_quote_keywords().next().is_some()+ }++ pub(crate) fn content_quote_transfer(self) -> QuoteTransfer {+ use crate::css::style_compute::keyword;+ self.content_quote_keywords()+ .fold(QuoteTransfer::IDENTITY, |transfer, quote_keyword| {+ transfer.then_quote(matches!(quote_keyword, keyword::OPEN_QUOTE | keyword::NO_OPEN_QUOTE))+ })+ }++ fn content_quote_keywords(self) -> impl Iterator<Item = u16> + 'a {+ use crate::css::style_compute::keyword;+ let values = match self.content().content.data() {+ Some(StyleValueData::Content { content, .. }) => match content.optional_data() {+ Some(StyleValueData::ValueList { values, .. }) => values.as_slice(),+ _ => &[],+ },+ _ => &[],};- values.as_slice().iter().any(|item| {- use crate::css::style_compute::keyword;- matches!(- item.optional_data(),- Some(StyleValueData::Keyword { keyword })- if matches!(- *keyword,- keyword::OPEN_QUOTE | keyword::CLOSE_QUOTE | keyword::NO_OPEN_QUOTE | keyword::NO_CLOSE_QUOTE- )- )+ values.iter().filter_map(|item| match item.optional_data() {+ Some(StyleValueData::Keyword { keyword })+ if matches!(+ *keyword,+ keyword::OPEN_QUOTE | keyword::CLOSE_QUOTE | keyword::NO_OPEN_QUOTE | keyword::NO_CLOSE_QUOTE+ ) =>+ {+ Some(*keyword)+ }+ _ => None,})}diff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rsindex aff46778775..8cfcdb613e6 100644--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs@@ -18,6 +18,7 @@ use crate::css::computed_longhand_table::{ComputedLonghandTable, DEPENDS_ON_VIEWPORT_METRICS, FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS,IN_DISPLAY_NONE_SUBTREE,};+use crate::css::computed_value_views::QuoteTransfer;use crate::css::computed_values::StyleGroupMasks;use animations::DeclarationScope;pub(super) use demand::WinnerRepublication;@@ -126,8 +127,9 @@ pub(crate) struct SubtreeGeneratedContentEffects {/// The counter can be one that an ancestor or an earlier box created, and that boxes outside the subtree read. An/// inserted `<li>` itself has the DOM renumber the list it joins.pub(crate) increments_or_sets_counters: bool,- /// A `content` opens or closes a quote. The walk stops once it finds one.- pub(crate) opens_or_closes_quotes: bool,+ /// An element's own quotes leave the quote depth after it other than they found it: its `::before` and `::after`+ /// together do, or its `::marker` or its own `content` names a quote. The walk stops once it finds one.+ pub(crate) has_element_with_unbalanced_quotes: bool,}impl RetainedState {@@ -3087,9 +3089,24 @@ impl RetainedState {effects.increments_or_sets_counters |= !view.counter_increment().is_empty()|| !view.counter_set().is_empty()|| (view.display().is_list_item() && !is_root_element);- effects.opens_or_closes_quotes |= view.content_opens_or_closes_quotes();}- if effects.opens_or_closes_quotes {+ let [element_record, before_record, after_record, marker_record] = records;+ let names_quotes = |record| {+ self.published_style_record_view(record)+ .is_some_and(|view| view.content_opens_or_closes_quotes())+ };+ let generated_quote_transfer = |record| {+ self.published_style_record_view(record)+ .filter(|view| !view.display().is_none())+ .map_or(QuoteTransfer::IDENTITY, |view| view.content_quote_transfer())+ };+ if names_quotes(element_record)+ || names_quotes(marker_record)+ || !generated_quote_transfer(before_record)+ .then(generated_quote_transfer(after_record))+ .is_identity()+ {+ effects.has_element_with_unbalanced_quotes = true;return effects;}}diff --git a/Libraries/LibWeb/Rust/src/layout/box_removal.rs b/Libraries/LibWeb/Rust/src/layout/box_removal.rsindex 631ecef5824..ad7a867875d 100644--- a/Libraries/LibWeb/Rust/src/layout/box_removal.rs+++ b/Libraries/LibWeb/Rust/src/layout/box_removal.rs@@ -13,6 +13,7 @@ use super::LayoutNodeArena;use super::layout_changes::LayoutWrite;use super::node_data::{NodeFlag, NodeSlotId};use super::node_facts::{self, has_flag};+use super::quote_depth::box_subtree_moves_quote_depth;use super::tree_builder::node_kind_is_node_with_style;use super::tree_mutation::HostWorkDue;use super::tree_update_marks::FfiLayoutTreeUpdateMark;@@ -237,6 +238,7 @@ impl BoxRemoval {if parent_row.is_invalid()|| child_row.is_invalid()|| !arena.can_detach_box_in_place(parent, parent_row, child_row, &facts)+ || box_subtree_moves_quote_depth(arena, child_row){arena.mark_layout_tree_update(Some(parent), FfiLayoutTreeUpdateMark::NODE_REMOVE);return;diff --git a/Libraries/LibWeb/Rust/src/layout/mod.rs b/Libraries/LibWeb/Rust/src/layout/mod.rsindex d2a97b1ba63..4ca1bb6f6b6 100644--- a/Libraries/LibWeb/Rust/src/layout/mod.rs+++ b/Libraries/LibWeb/Rust/src/layout/mod.rs@@ -43,6 +43,7 @@ pub(crate) mod node_facts;pub(crate) mod tree_shape;pub use libcompositing_rust::node_slot_id;mod partial_relayout;+pub(crate) mod quote_depth;pub(crate) mod rendered_text;mod replaced_with_children_formatting_context;pub(crate) mod row_reads;diff --git a/Libraries/LibWeb/Rust/src/layout/quote_depth.rs b/Libraries/LibWeb/Rust/src/layout/quote_depth.rsnew file mode 100644index 00000000000..8cf559a07e5--- /dev/null+++ b/Libraries/LibWeb/Rust/src/layout/quote_depth.rs@@ -0,0 +1,199 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use super::layout_node_arena::LayoutNodeArena;+use super::node_data::{+ GENERATED_FOR_AFTER, GENERATED_FOR_BACKDROP, GENERATED_FOR_BEFORE, GENERATED_FOR_MARKER, NodeKind, NodeSlotId,+};+use super::node_facts;+use crate::css::computed_value_views::QuoteTransfer;+use crate::css::style::bridge::element_adjustment_fact;+use crate::css::style::fast_hash::FastSet as HashSet;+use crate::css::style::tree::StyleNodeID;+use crate::painting::style_queries::has_style_containment;++#[derive(Clone, Copy, PartialEq, Eq)]+enum QuoteDepthStep {+ DomNodesFrom(StyleNodeID),+ AssignedNodesFrom(StyleNodeID, usize),+ TopLayerMembersFrom(usize),+ TopLayerMember(StyleNodeID),+ PseudoElement(StyleNodeID, u8),+ LeaveBox(StyleNodeID, u32),+}++pub(crate) struct QuoteDepthCursor {+ depth: u32,+ pending_steps: Vec<QuoteDepthStep>,+ document_has_top_layer: bool,+}++impl QuoteDepthCursor {+ pub(crate) fn new(arena: &LayoutNodeArena, document: StyleNodeID) -> Self {+ let mut pending_steps = vec![QuoteDepthStep::TopLayerMembersFrom(0)];+ if let Some(document_element) = arena.first_dom_child(document) {+ pending_steps.push(QuoteDepthStep::DomNodesFrom(document_element));+ }+ Self {+ depth: 0,+ pending_steps,+ document_has_top_layer: arena.top_layer_element(0).is_some(),+ }+ }++ pub(crate) fn depth_before(+ &mut self,+ arena: &LayoutNodeArena,+ element: StyleNodeID,+ generated_for: u8,+ ) -> Option<u32> {+ let target = QuoteDepthStep::PseudoElement(element, generated_for);+ while let Some(&step) = self.pending_steps.last() {+ if step == target {+ return Some(self.depth);+ }+ self.pending_steps.pop();+ self.take_step(arena, step);+ }+ None+ }++ fn take_step(&mut self, arena: &LayoutNodeArena, step: QuoteDepthStep) {+ match step {+ QuoteDepthStep::DomNodesFrom(node) => {+ let mut node = node;+ while node.text_index().is_some() {+ let Some(next) = arena.next_dom_sibling(node) else {+ return;+ };+ node = next;+ }+ if let Some(next) = arena.next_dom_sibling(node) {+ self.pending_steps.push(QuoteDepthStep::DomNodesFrom(next));+ }+ self.enter_element_in_place(arena, node);+ }+ QuoteDepthStep::AssignedNodesFrom(slot, index) => {+ if index < arena.assigned_node_count(Some(slot)) {+ self.pending_steps+ .push(QuoteDepthStep::AssignedNodesFrom(slot, index + 1));+ let node = arena.assigned_node_at(slot, index);+ if node.text_index().is_none() {+ self.enter_element_in_place(arena, node);+ }+ }+ }+ QuoteDepthStep::TopLayerMembersFrom(index) => {+ let Some(member) = arena.top_layer_element(index) else {+ return;+ };+ self.pending_steps.push(QuoteDepthStep::TopLayerMembersFrom(index + 1));+ if is_rendered_in_top_layer(arena, member) {+ self.pending_steps.push(QuoteDepthStep::TopLayerMember(member));+ self.pending_steps+ .push(QuoteDepthStep::PseudoElement(member, GENERATED_FOR_BACKDROP));+ }+ }+ QuoteDepthStep::TopLayerMember(member) => self.enter_element(arena, member),+ QuoteDepthStep::PseudoElement(element, generated_for) => {+ self.depth = pseudo_element_quote_transfer(arena, element, generated_for).apply(self.depth);+ }+ QuoteDepthStep::LeaveBox(element, depth_on_entry) => {+ if self.depth != depth_on_entry+ && node_facts::node_style_view(arena.data(arena.bound_row(element)))+ .is_some_and(has_style_containment)+ {+ self.depth = depth_on_entry;+ }+ }+ }+ }++ fn enter_element_in_place(&mut self, arena: &LayoutNodeArena, element: StyleNodeID) {+ if !(self.document_has_top_layer && is_rendered_in_top_layer(arena, element)) {+ self.enter_element(arena, element);+ }+ }++ fn enter_element(&mut self, arena: &LayoutNodeArena, element: StyleNodeID) {+ let row = arena.bound_row(element);+ if !row.is_invalid() {+ self.pending_steps.push(QuoteDepthStep::LeaveBox(element, self.depth));+ self.pending_steps+ .push(QuoteDepthStep::PseudoElement(element, GENERATED_FOR_AFTER));+ if arena.data(row).kind.get() == NodeKind::ListItemBox {+ self.pending_steps+ .push(QuoteDepthStep::PseudoElement(element, GENERATED_FOR_MARKER));+ }+ } else if arena+ .published_box_facts(Some(element))+ .is_some_and(|facts| facts.display.is_contents())+ {+ self.pending_steps+ .push(QuoteDepthStep::PseudoElement(element, GENERATED_FOR_AFTER));+ } else {+ return;+ }+ let assigned_node_count = arena.assigned_node_count(Some(element));+ if assigned_node_count != 0 {+ self.pending_steps.push(QuoteDepthStep::AssignedNodesFrom(element, 0));+ }+ let first_child = match arena.shadow_root_of(element) {+ Some(shadow_root) => arena.first_dom_child(shadow_root),+ None if assigned_node_count == 0 => arena.first_dom_child(element),+ None => None,+ };+ if let Some(first_child) = first_child {+ self.pending_steps.push(QuoteDepthStep::DomNodesFrom(first_child));+ }+ self.pending_steps+ .push(QuoteDepthStep::PseudoElement(element, GENERATED_FOR_BEFORE));+ }+}++fn is_rendered_in_top_layer(arena: &LayoutNodeArena, element: StyleNodeID) -> bool {+ arena.element_adjustment_facts(Some(element)) & element_adjustment_fact::RENDERED_IN_TOP_LAYER != 0+}++fn pseudo_element_quote_transfer(arena: &LayoutNodeArena, element: StyleNodeID, generated_for: u8) -> QuoteTransfer {+ let row = arena.bound_pseudo_element_row(element, generated_for);+ if row.is_invalid() {+ return QuoteTransfer::IDENTITY;+ }+ node_facts::node_style_view(arena.data(row)).map_or(QuoteTransfer::IDENTITY, |style| style.content_quote_transfer())+}++pub(crate) fn box_subtree_moves_quote_depth(arena: &LayoutNodeArena, root: NodeSlotId) -> bool {+ let mut generators = HashSet::default();+ let mut row = root;+ loop {+ let data = arena.data(row);+ if matches!(+ data.generated_for.get(),+ GENERATED_FOR_BEFORE | GENERATED_FOR_AFTER | GENERATED_FOR_MARKER+ ) && let Some(generator) = arena.node_style_node(row)+ && generators.insert(generator)+ && ![GENERATED_FOR_BEFORE, GENERATED_FOR_MARKER, GENERATED_FOR_AFTER]+ .into_iter()+ .fold(QuoteTransfer::IDENTITY, |transfer, generated_for| {+ transfer.then(pseudo_element_quote_transfer(arena, generator, generated_for))+ })+ .is_identity()+ {+ return true;+ }+ let mut next = data.first_child.get();+ let mut current = row;+ while next.is_invalid() && current != root {+ next = arena.data(current).next_sibling.get();+ current = arena.data(current).parent.get();+ }+ if next.is_invalid() {+ return false;+ }+ row = next;+ }+}diff --git a/Libraries/LibWeb/Rust/src/layout/tree_builder.rs b/Libraries/LibWeb/Rust/src/layout/tree_builder.rsindex 8c1d64e451e..1138d4469ea 100644--- a/Libraries/LibWeb/Rust/src/layout/tree_builder.rs+++ b/Libraries/LibWeb/Rust/src/layout/tree_builder.rs@@ -20,6 +20,7 @@ use crate::layout::node_data::{GENERATED_FOR_AFTER, GENERATED_FOR_BACKDROP, GENERATED_FOR_BEFORE, GENERATED_FOR_FIRST_LETTER,GENERATED_FOR_MARKER, NodeData, NodeFlag, NodeKind, NodeSlotId, pseudo_kind_of,};+use crate::layout::quote_depth::{QuoteDepthCursor, box_subtree_moves_quote_depth};use crate::layout::text_chunker::{GraphemeSegmenter, code_point_at, code_unit_length_for_code_point};use crate::layout::tree_mutation::{HostCalls, OwedHostWork, UnplacedLayoutNode};use crate::layout::tree_update_marks::layout_tree_update_reuse_reason;@@ -31,6 +32,8 @@ type LayoutNode = NodeSlotId;pub(crate) struct TreeBuilderState {pub(crate) ancestor_stack: Vec<LayoutNode>,pub(crate) quote_nesting_level: u32,+ quote_depth_cursor: Option<QuoteDepthCursor>,+ built_quote_owner_count: usize,// Partial-rebuild bookkeeping: boxes replaced in place become rebuild roots, and any tree// restructuring that reaches outside every rebuild root downgrades the update to a full one.current_rebuild_root: LayoutNode,@@ -61,6 +64,8 @@ impl Default for TreeBuilderState {Self {ancestor_stack: Vec::new(),quote_nesting_level: 0,+ quote_depth_cursor: None,+ built_quote_owner_count: 0,current_rebuild_root: NodeSlotId::INVALID,rebuilt_subtree_roots: Vec::new(),reused_child_list_update_roots: Vec::new(),@@ -1112,7 +1117,7 @@ impl ChildListInsertionReuse<'_, '_> {{return false;}- // The rebuild regenerates these after the walk, which leaves the quote depth of the boxes it keeps out.+ // Regenerating these can move the quote depth that the boxes the rebuild keeps were resolved at.for generated_for in [GENERATED_FOR_BEFORE, GENERATED_FOR_AFTER, GENERATED_FOR_MARKER] {if self.engine@@ -1182,7 +1187,7 @@ impl ChildListInsertionReuse<'_, '_> {continue;}let generated_content_effects = self.engine.subtree_generated_content_effects(child);- if generated_content_effects.opens_or_closes_quotes {+ if generated_content_effects.has_element_with_unbalanced_quotes {return false;}if (generated_content_effects.resets_counters || generated_content_effects.increments_or_sets_counters)@@ -1336,7 +1341,7 @@ impl ChildListInsertionReuse<'_, '_> {continue;}let generated_content_effects = self.engine.subtree_generated_content_effects(child);- if generated_content_effects.opens_or_closes_quotes {+ if generated_content_effects.has_element_with_unbalanced_quotes {return false;}if (generated_content_effects.resets_counters || generated_content_effects.increments_or_sets_counters)@@ -1643,6 +1648,9 @@ impl TreeBuildJob {};// Whether the document already had a viewport, read before the build replaces it.let document_had_layout_node = !host.arena().layout_root().is_invalid();+ if document_had_layout_node && !context.document_needs_full_layout_tree_update {+ state.quote_depth_cursor = Some(QuoteDepthCursor::new(host.arena(), document_identity));+ }update_layout_tree_from(host,@@ -1760,13 +1768,34 @@ fn update_layout_tree_for_dom_children() {let mut node = host.first_dom_child(parent);while let Some(current) = node {- if !keeps_its_box_as_it_is(host, current, context, must_create_subtree) {+ if insertion_mode == FfiInsertionMode::InDomOrder && host.arena().bound_row(current).is_invalid() {+ update_layout_tree_for_spliced_child(host, state, current, context, must_create_subtree, insertion_mode);+ } else if !keeps_its_box_as_it_is(host, current, context, must_create_subtree) {update_layout_tree(host, state, current, context, must_create_subtree, insertion_mode);}node = host.next_dom_sibling(current);}}+fn update_layout_tree_for_spliced_child(+ host: &mut TreeBuilderHost<'_>,+ state: &mut TreeBuilderState,+ child: StyleNodeID,+ context: &mut TreeBuilderContext,+ must_create_subtree: bool,+ insertion_mode: FfiInsertionMode,+) {+ let built_quote_owner_count = state.built_quote_owner_count;+ update_layout_tree(host, state, child, context, must_create_subtree, insertion_mode);+ if state.built_quote_owner_count == built_quote_owner_count {+ return;+ }+ let row = host.arena().bound_row(child);+ if row.is_invalid() || box_subtree_moves_quote_depth(host.arena(), row) {+ state.layout_tree_rebuild_requests.push(None);+ }+}+/// OPTIMIZATION: A node that holds no layout tree update mark, and has none below it, keeps its attached box as it/// is, so the walk passes it by without looking at its style, as it passes by every node outside the marked paths./// Inside SVG and top-layer walks, where the walk itself decides which boxes the nodes get, it visits every node.@@ -2670,7 +2699,7 @@ fn rebuild_child_list_from_dom_children(kept_box = host.parent(kept_box);}if kept_box.is_invalid() {- update_layout_tree(host, state, child, context, false, FfiInsertionMode::Append);+ update_layout_tree_for_spliced_child(host, state, child, context, false, FfiInsertionMode::Append);} else if host.arena().needs_layout_tree_update(child)&& (host.arena().layout_tree_update_reuse_reasons(child) == 0|| host.data(kept_box).kind.get() == NodeKind::TableWrapper)@@ -3694,6 +3723,31 @@ fn create_generated_content_item(slot}+fn quote_nesting_level_before(+ host: &TreeBuilderHost<'_>,+ state: &mut TreeBuilderState,+ element: StyleNodeID,+ pseudo_element: FfiPseudoElement,+ layout_node: LayoutNode,+) -> u32 {+ if !host+ .style(layout_node)+ .is_some_and(|style| style.content_opens_or_closes_quotes())+ {+ return state.quote_nesting_level;+ }+ state.built_quote_owner_count += 1;+ let Some(cursor) = state.quote_depth_cursor.as_mut() else {+ return state.quote_nesting_level;+ };+ if let Some(depth) = cursor.depth_before(host.arena(), element, generated_for_of(pseudo_element)) {+ return depth;+ }+ state.quote_depth_cursor = None;+ state.layout_tree_rebuild_requests.push(None);+ state.quote_nesting_level+}+fn create_pseudo_element(host: &mut TreeBuilderHost<'_>,state: &mut TreeBuilderState,@@ -3748,7 +3802,8 @@ fn create_pseudo_element(}}- let initial_quote_nesting_level = state.quote_nesting_level;+ let initial_quote_nesting_level =+ quote_nesting_level_before(host, state, element_identity, pseudo_element, layout_node);let layout_node_kind = host.data(layout_node).kind.get();let is_outside_marker = layout_node_kind == NodeKind::ListItemMarkerBox && !facts.marker_position_is_inside;if let Some(insertion_mode) = insertion_modediff --git a/Tests/LibWeb/Text/expected/layout-tree-update/direct-child-list-preservation.txt b/Tests/LibWeb/Text/expected/layout-tree-update/direct-child-list-preservation.txtindex 228b175ac18..3dbd3260055 100644--- a/Tests/LibWeb/Text/expected/layout-tree-update/direct-child-list-preservation.txt+++ b/Tests/LibWeb/Text/expected/layout-tree-update/direct-child-list-preservation.txt@@ -209,6 +209,44 @@ PASS: rebuild child list when appended counter subtree is followed by generatedPASS: fall back when appending a list-item increment after a reversed list | rebuild parentPASS: fall back when appending a list-item increment after a reversed list | layout tree builds=1PASS: fall back when appending a list-item increment after a reversed list | incremental tree matches full rebuild+PASS: append balanced quotes after an existing quote | preserve parent+PASS: append balanced quotes after an existing quote | preserve before+PASS: append balanced quotes after an existing quote | preserve deep+PASS: append balanced quotes after an existing quote | preserve leaf+PASS: append balanced quotes after an existing quote | layout tree builds=1+PASS: append balanced quotes after an existing quote | incremental tree matches full rebuild+PASS: insert balanced quotes before later quotes | preserve parent+PASS: insert balanced quotes before later quotes | preserve before+PASS: insert balanced quotes before later quotes | preserve after+PASS: insert balanced quotes before later quotes | layout tree builds=1+PASS: insert balanced quotes before later quotes | incremental tree matches full rebuild+PASS: append nested balanced quotes | preserve parent+PASS: append nested balanced quotes | preserve before+PASS: append nested balanced quotes | layout tree builds=1+PASS: append nested balanced quotes | incremental tree matches full rebuild+PASS: append quotes inside an open quote | preserve parent+PASS: append quotes inside an open quote | preserve before+PASS: append quotes inside an open quote | layout tree builds=1+PASS: append quotes inside an open quote | incremental tree matches full rebuild+PASS: append quotes after an unclosed quote outside the parent | preserve parent+PASS: append quotes after an unclosed quote outside the parent | preserve before+PASS: append quotes after an unclosed quote outside the parent | layout tree builds=1+PASS: append quotes after an unclosed quote outside the parent | incremental tree matches full rebuild+PASS: append quotes after an unclosed quote in a style-contained sibling | preserve parent+PASS: append quotes after an unclosed quote in a style-contained sibling | preserve before+PASS: append quotes after an unclosed quote in a style-contained sibling | layout tree builds=1+PASS: append quotes after an unclosed quote in a style-contained sibling | incremental tree matches full rebuild+PASS: append quotes inside a display contents quote pair | preserve parent+PASS: append quotes inside a display contents quote pair | preserve before+PASS: append quotes inside a display contents quote pair | layout tree builds=1+PASS: append quotes inside a display contents quote pair | incremental tree matches full rebuild+PASS: append quotes before a list item marker that opens a quote | preserve parent+PASS: append quotes before a list item marker that opens a quote | preserve before+PASS: append quotes before a list item marker that opens a quote | layout tree builds=1+PASS: append quotes before a list item marker that opens a quote | incremental tree matches full rebuild+PASS: rebuild child list when a block with quotes splits generated inline wrapper | preserve parent+PASS: rebuild child list when a block with quotes splits generated inline wrapper | layout tree builds=1+PASS: rebuild child list when a block with quotes splits generated inline wrapper | incremental tree matches full rebuildPASS: fall back when appending a subtree that opens a quote | rebuild parentPASS: fall back when appending a subtree that opens a quote | layout tree builds=1PASS: fall back when appending a subtree that opens a quote | incremental tree matches full rebuild@@ -407,6 +445,11 @@ PASS: fall back when list-item after marker follows removed item | incremental tPASS: fall back when removed pseudo-element changes quote depth | rebuild parentPASS: fall back when removed pseudo-element changes quote depth | layout tree builds=1PASS: fall back when removed pseudo-element changes quote depth | incremental tree matches full rebuild+PASS: remove balanced quotes between quotes | preserve parent+PASS: remove balanced quotes between quotes | preserve before+PASS: remove balanced quotes between quotes | preserve after+PASS: remove balanced quotes between quotes | layout tree builds=0+PASS: remove balanced quotes between quotes | incremental tree matches full rebuildPASS: fall back when removed pseudo-element affects following counters | rebuild parentPASS: fall back when removed pseudo-element affects following counters | layout tree builds=1PASS: fall back when removed pseudo-element affects following counters | incremental tree matches full rebuilddiff --git a/Tests/LibWeb/Text/expected/layout-tree-update/quote-depth-incremental-builds.txt b/Tests/LibWeb/Text/expected/layout-tree-update/quote-depth-incremental-builds.txtnew file mode 100644index 00000000000..6c0c815c60e--- /dev/null+++ b/Tests/LibWeb/Text/expected/layout-tree-update/quote-depth-incremental-builds.txt@@ -0,0 +1,17 @@+PASS: insert balanced quotes before later quotes | layout tree builds=1+PASS: insert an unclosed quote before later quotes | layout tree builds=1+PASS: insert a lone close quote before later quotes | layout tree builds=1+PASS: remove the lone close quote | layout tree builds=1+PASS: insert balanced quotes after the unclosed quote | layout tree builds=1+PASS: remove the unclosed quote | layout tree builds=1+PASS: remove balanced quotes before later quotes | layout tree builds=0+PASS: insert quotes inside a quote | layout tree builds=1+PASS: append quotes inside an open quote | layout tree builds=1+PASS: append quotes after an unclosed quote in a style-contained element | layout tree builds=1+PASS: append quotes after a style-contained element | layout tree builds=1+PASS: append quotes inside a display contents quote pair | layout tree builds=1+PASS: append quotes before a marker that opens a quote | layout tree builds=1+PASS: append quotes after a marker that opens a quote | layout tree builds=1+PASS: append quotes into slotted content after a quote opened in the shadow tree | layout tree builds=1+PASS: append a shadow tree that opens a quote before later quotes | layout tree builds=2+PASS: append quotes into a top layer element after an unclosed quote | layout tree builds=1diff --git a/Tests/LibWeb/Text/input/layout-tree-update/direct-child-list-preservation.html b/Tests/LibWeb/Text/input/layout-tree-update/direct-child-list-preservation.htmlindex 53fbe490dd7..46d0c930b9e 100644--- a/Tests/LibWeb/Text/input/layout-tree-update/direct-child-list-preservation.html+++ b/Tests/LibWeb/Text/input/layout-tree-update/direct-child-list-preservation.html@@ -14,6 +14,10 @@.parent.first-line::first-line { color: red; }.parent.quotes { quotes: "«" "»" "‹" "›"; }.quote-open::before { content: open-quote; }+ .quote-pair::before { content: open-quote; }+ .quote-pair::after { content: close-quote; }+ .marker-quote::marker { content: open-quote; }+ .style-contained { contain: style; }.pseudo-increment::before { counter-increment: direct-child-counter; content: ""; }.columns { columns: 2; }.list-item { display: list-item; }@@ -356,6 +360,65 @@tracked: ["parent"],preserve: false,},+ {+ name: "append balanced quotes after an existing quote",+ markup: '<div class="parent quotes"><p class="before child"><q>before</q></p><div class="deep child"><p><span class="leaf">leaf</span></p></div></div>',+ mutate: parent => parent.insertAdjacentHTML("beforeend", '<p class="target child"><q>target</q></p>'),+ tracked: ["parent", "before", "deep", "leaf"],+ },+ {+ name: "insert balanced quotes before later quotes",+ markup: '<div class="parent quotes"><p class="before child"><q>before</q></p><p class="after child"><q>after</q><q>last</q></p></div>',+ mutate: parent => parent.querySelector(".after").insertAdjacentHTML("beforebegin", '<p class="target child"><q>target</q></p>'),+ tracked: ["parent", "before", "after"],+ },+ {+ name: "append nested balanced quotes",+ markup: '<div class="parent quotes"><p class="before child"><q>before</q></p></div>',+ mutate: parent => parent.insertAdjacentHTML("beforeend", '<p class="target child"><q>outer <q>inner</q></q></p>'),+ tracked: ["parent", "before"],+ },+ {+ name: "append quotes inside an open quote",+ markup: '<div class="quotes"><q><span class="parent inline-block"><i class="before child">before</i></span> <q>after</q></q></div>',+ parentSelector: ".parent",+ mutate: parent => parent.insertAdjacentHTML("beforeend", '<p class="target child"><q>target</q></p>'),+ tracked: ["parent", "before"],+ },+ {+ name: "append quotes after an unclosed quote outside the parent",+ markup: '<div class="quotes"><i class="quote-open"></i><div class="parent"><i class="before child"></i></div><q>after</q></div>',+ parentSelector: ".parent",+ mutate: parent => parent.insertAdjacentHTML("beforeend", '<p class="target child"><q>target</q></p>'),+ tracked: ["parent", "before"],+ },+ {+ name: "append quotes after an unclosed quote in a style-contained sibling",+ markup: '<div class="quotes"><div class="style-contained"><i class="quote-open"></i></div><div class="parent"><i class="before child"></i></div></div>',+ parentSelector: ".parent",+ mutate: parent => parent.insertAdjacentHTML("beforeend", '<p class="target child"><q>target</q></p>'),+ tracked: ["parent", "before"],+ },+ {+ name: "append quotes inside a display contents quote pair",+ markup: '<div class="quotes"><div class="contents quote-pair"><div class="parent"><i class="before child"></i></div></div><q>after</q></div>',+ parentSelector: ".parent",+ mutate: parent => parent.insertAdjacentHTML("beforeend", '<p class="target child"><q>target</q></p>'),+ tracked: ["parent", "before"],+ },+ {+ name: "append quotes before a list item marker that opens a quote",+ markup: '<ol class="quotes"><li class="parent marker-quote"><i class="before child"></i></li><li><q>after</q></li></ol>',+ parentSelector: ".parent",+ mutate: parent => parent.insertAdjacentHTML("beforeend", '<p class="target child"><q>target</q></p>'),+ tracked: ["parent", "before"],+ },+ {+ name: "rebuild child list when a block with quotes splits generated inline wrapper",+ markup: '<div class="parent inline-generated quotes"></div>',+ mutate: parent => parent.insertAdjacentHTML("beforeend", '<section class="target child"><q>target</q></section>'),+ tracked: ["parent"],+ },{name: "fall back when appending a subtree that opens a quote",markup: '<div class="parent quotes"><i class="before child"></i></div>',@@ -631,6 +694,13 @@tracked: ["parent"],preserve: false,},+ {+ name: "remove balanced quotes between quotes",+ markup: '<div class="parent quotes"><p class="before child"><q>before</q></p><p class="target child"><q>target <q>nested</q></q></p><p class="after child"><q>after</q></p></div>',+ mutate: parent => parent.querySelector(".target").remove(),+ tracked: ["parent", "before", "after"],+ expectNoBuild: true,+ },{name: "fall back when removed pseudo-element affects following counters",markup: '<div class="parent counter"><i class="target child pseudo-increment"></i><i class="after child counter-value"></i></div>',diff --git a/Tests/LibWeb/Text/input/layout-tree-update/quote-depth-incremental-builds.html b/Tests/LibWeb/Text/input/layout-tree-update/quote-depth-incremental-builds.htmlnew file mode 100644index 00000000000..a9bc1ff247b--- /dev/null+++ b/Tests/LibWeb/Text/input/layout-tree-update/quote-depth-incremental-builds.html@@ -0,0 +1,71 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ .open::before { content: open-quote; }+ .close::after { content: close-quote; }+ .marker-open::marker { content: open-quote; }+ .contained { contain: style; }+ .contents-pair { display: contents; }+ .contents-pair::before { content: open-quote; }+ .contents-pair::after { content: close-quote; }+ .inline-block { display: inline-block; }+</style>+<div id="fixture"></div>+<script>+ function check(name, mutate) {+ document.body.offsetHeight;+ const buildsBefore = internals.layoutTreeBuildStats().builds;+ mutate();+ document.body.offsetHeight;+ const builds = internals.layoutTreeBuildStats().builds - buildsBefore;+ const comparison = internals.compareLayoutTreeWithFullRebuild();+ println(`${comparison.matches ? "PASS" : "FAIL"}: ${name} | layout tree builds=${builds}`);+ }++ function byId(id) {+ return document.getElementById(id);+ }++ test(() => {+ fixture.innerHTML = '<div id="list"><p><q>one</q></p><p id="middle"><q>two <q>three</q></q></p><p><q>four</q></p></div>';+ const list = byId("list");+ check("insert balanced quotes before later quotes", () => list.insertAdjacentHTML("afterbegin", '<p><q>zero</q></p>'));+ check("insert an unclosed quote before later quotes", () => list.insertAdjacentHTML("afterbegin", '<p id="opener" class="open"></p>'));+ check("insert a lone close quote before later quotes", () => byId("middle").insertAdjacentHTML("beforebegin", '<p id="closer" class="close"></p>'));+ check("remove the lone close quote", () => byId("closer").remove());+ check("insert balanced quotes after the unclosed quote", () => byId("middle").insertAdjacentHTML("beforebegin", '<p><q>nested by the opener</q></p>'));+ check("remove the unclosed quote", () => byId("opener").remove());+ check("remove balanced quotes before later quotes", () => byId("middle").remove());+ check("insert quotes inside a quote", () => list.querySelector("q").insertAdjacentHTML("beforeend", '<span class="inline-block"><q>nested</q></span>'));++ fixture.innerHTML = '<q><span id="inside-quote" class="inline-block"><span>start</span></span> <q>after</q></q>';+ check("append quotes inside an open quote", () => byId("inside-quote").insertAdjacentHTML("beforeend", '<p><q>inside</q></p>'));++ fixture.innerHTML = '<div class="contained"><span class="open"></span><div id="contained-parent"><p>start</p></div></div><div id="after-contained"><p>start</p></div><q>after</q>';+ check("append quotes after an unclosed quote in a style-contained element", () => byId("contained-parent").insertAdjacentHTML("beforeend", '<p><q>contained</q></p>'));+ check("append quotes after a style-contained element", () => byId("after-contained").insertAdjacentHTML("beforeend", '<p><q>outside</q></p>'));++ fixture.innerHTML = '<div class="contents-pair"><div id="contents-parent"><p>start</p></div></div><q>after</q>';+ check("append quotes inside a display contents quote pair", () => byId("contents-parent").insertAdjacentHTML("beforeend", '<p><q>inside</q></p>'));++ fixture.innerHTML = '<ul><li class="marker-open"><div id="first-item"><p>start</p></div></li><li><div id="second-item"><p>start</p></div></li></ul>';+ check("append quotes before a marker that opens a quote", () => byId("first-item").insertAdjacentHTML("beforeend", '<p><q>before marker</q></p>'));+ check("append quotes after a marker that opens a quote", () => byId("second-item").insertAdjacentHTML("beforeend", '<p><q>after marker</q></p>'));++ fixture.innerHTML = '<div id="host"><div id="slotted"><p>start</p></div></div><q>after</q>';+ const shadow = byId("host").attachShadow({ mode: "open" });+ shadow.innerHTML = '<style>.open::before { content: open-quote; }</style><span class="open"></span><div><slot></slot></div><q>shadow</q>';+ check("append quotes into slotted content after a quote opened in the shadow tree", () => byId("slotted").insertAdjacentHTML("beforeend", '<p><q>slotted</q></p>'));++ fixture.innerHTML = '<div id="shadow-parent"><p>start</p></div><q>after</q>';+ const unbalancedHost = document.createElement("div");+ unbalancedHost.attachShadow({ mode: "open" }).innerHTML = '<style>.open::before { content: open-quote; }</style><span class="open"></span>';+ check("append a shadow tree that opens a quote before later quotes", () => byId("shadow-parent").append(unbalancedHost));++ fixture.innerHTML = '<span class="open"></span><dialog id="dialog"><div id="dialog-parent"><p>start</p></div></dialog>';+ byId("dialog").showModal();+ check("append quotes into a top layer element after an unclosed quote", () => byId("dialog-parent").insertAdjacentHTML("beforeend", '<p><q>top layer</q></p>'));+ byId("dialog").close();+ fixture.innerHTML = "";+ });+</script>