Skip to content

armgit / moli

Public Imported from GitHub
0

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

perf(style): consume subtree invalidation lazily

ldm051eefaf8ee64
diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
index 6d687ed42..b4c518bfc 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
@@ -1462,6 +1462,11 @@ impl JsContextHost {
.computed_cache_generation_for_document(document)
}
+ pub(crate) fn retire_computed_style_for_inactive_handle(&self, handle: DomHandle) {
+ self.style_engine
+ .retire_computed_style_for_inactive_handle(handle);
+ }
+
pub(crate) fn stylesheet_resource_snapshot_for_document(
&self,
document: DomHandle,
diff --git a/moli-renderer-v8/src/native_bridge/element/styles.rs b/moli-renderer-v8/src/native_bridge/element/styles.rs
index 408eed9f4..1715d0e3d 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles.rs
@@ -112,8 +112,8 @@ fn style_object_forces_empty_computed<'s>(
{
return value.boolean_value(scope);
}
- match bridge_handle {
- BridgeHandle::ComputedStyle(handle, descriptor) => match descriptor.target {
+ let empty = match bridge_handle {
+ BridgeHandle::ComputedStyle(handle, ref descriptor) => match descriptor.target {
ComputedStyleTargetKey::ChildFrame(frame_handle) => {
let runtime = unsafe { &*runtime_ptr };
let empty = !child_frame_target_document_is_current(runtime, handle, frame_handle)
@@ -141,7 +141,11 @@ fn style_object_forces_empty_computed<'s>(
}
},
_ => true,
+ };
+ if empty && let BridgeHandle::ComputedStyle(handle, _) = bridge_handle {
+ unsafe { &*runtime_ptr }.retire_computed_style_for_inactive_handle(handle);
}
+ empty
}
fn child_frame_target_document_is_current(
diff --git a/moli-renderer-v8/src/style_engine/cache.rs b/moli-renderer-v8/src/style_engine/cache.rs
index 37c05243f..ed4f03500 100644
--- a/moli-renderer-v8/src/style_engine/cache.rs
+++ b/moli-renderer-v8/src/style_engine/cache.rs
@@ -12,9 +12,9 @@ use crate::document_runtime::DomHandle;
/// Resolution index for canonical Stylo element data plus a pseudo-style cache.
///
/// Primary `ComputedValues` are never duplicated here: they remain owned by
-/// Stylo `ElementData`. Primary entries only let invalidation find already
-/// published elements; pseudo styles have no equivalent canonical slot and are
-/// therefore retained by value until their generation is invalidated.
+/// Stylo `ElementData`. Primary entries record publication for diagnostics and
+/// per-handle pseudo eviction; pseudo styles have no equivalent canonical slot
+/// and are therefore retained by value until their generation is invalidated.
pub(super) struct ComputedStyleCache {
primary_entries: RefCell<HashSet<ComputedElementStyleCacheKey>>,
pseudo_entries: RefCell<HashMap<ComputedElementStyleCacheKey, ServoArc<ComputedValues>>>,
@@ -103,10 +103,6 @@ impl ComputedStyleCache {
}
}
- pub(super) fn handles(&self) -> Vec<DomHandle> {
- self.keys_by_handle.borrow().keys().copied().collect()
- }
-
fn index_key(&self, key: &ComputedElementStyleCacheKey) {
self.keys_by_handle
.borrow_mut()
diff --git a/moli-renderer-v8/src/style_engine/cleanup.rs b/moli-renderer-v8/src/style_engine/cleanup.rs
index e4b05d74c..bdb193cf0 100644
--- a/moli-renderer-v8/src/style_engine/cleanup.rs
+++ b/moli-renderer-v8/src/style_engine/cleanup.rs
@@ -45,19 +45,19 @@ impl<'a> StyleCacheCleanup<'a> {
self.computed_style_cache.clear();
self.document_state.clear_selector_caches();
self.document_state.bump_computed_cache_generation();
+ self.document_state.lazy_invalidation_roots.clear();
}
- /// Expands Stylo's matched stylesheet invalidations to already-published
- /// descendants. Moli resolves demanded elements one at a time, so it does
- /// not have a later full-tree traversal that would propagate inherited
- /// style changes from a `RESTYLE_SELF` ancestor.
- pub(super) fn invalidate_stylesheet_dirty_subtrees(&self, host: &DomHost) {
- let roots = self.existing_subtree_roots(
- host,
- self.dom_adapter
- .dirty_element_style_handles_for_document(self.document),
- );
- self.invalidate_existing_subtree_roots(host, &roots);
+ /// Retains Stylo's top-most dirty elements as lazy subtree roots.
+ /// Descendants inherit the root generation when they are next observed;
+ /// no document-wide published-style scan is performed here.
+ pub(super) fn retain_stylesheet_invalidation_roots(
+ &self,
+ host: &DomHost,
+ roots: impl IntoIterator<Item = DomHandle>,
+ ) {
+ let roots = self.existing_subtree_roots(host, roots);
+ self.record_lazy_invalidation_roots(host, &roots);
}
pub(super) fn invalidate_detached_subtrees(
@@ -74,9 +74,9 @@ impl<'a> StyleCacheCleanup<'a> {
self.dom_adapter
.element_selector_flag_handles_for_document(self.document),
);
- let invalidated_handles = self.invalidate_existing_subtree_roots(host, &roots);
- let cleared = invalidated_handles.is_some();
- if invalidated_handles.is_some() {
+ let eagerly_invalidated_roots = self.record_lazy_invalidation_roots(host, &roots);
+ let cleared = eagerly_invalidated_roots.is_some();
+ if eagerly_invalidated_roots.is_some() {
for &handle in &selector_flag_handles {
self.dom_adapter.clear_element_selector_flags(handle);
}
@@ -92,15 +92,8 @@ impl<'a> StyleCacheCleanup<'a> {
if roots.is_empty() {
return false;
}
- let handles = self.cached_handles_in_style_subtrees(host, &roots);
- for &handle in &handles {
- self.dom_adapter.mark_element_style_dirty(handle);
- }
+ self.record_lazy_invalidation_roots(host, &roots);
self.dom_adapter.clear_inline_style_attribute(root);
- self.computed_style_cache
- .invalidate_handles(handles.iter().copied());
- self.document_state.clear_selector_caches();
- self.document_state.bump_target_context_epoch();
true
}
@@ -112,8 +105,7 @@ impl<'a> StyleCacheCleanup<'a> {
self.document_state
.clear_invalidation_clear_all_fallback_reasons();
let roots = self.existing_subtree_roots(host, roots);
- self.invalidate_existing_subtree_roots(host, &roots)
- .is_some()
+ self.record_lazy_invalidation_roots(host, &roots).is_some()
}
pub(super) fn invalidate_subtrees_and_shadow_cascade_data(
@@ -124,9 +116,7 @@ impl<'a> StyleCacheCleanup<'a> {
self.document_state
.clear_invalidation_clear_all_fallback_reasons();
let roots = self.existing_subtree_roots(host, roots);
- let cleared = self
- .invalidate_existing_subtree_roots(host, &roots)
- .is_some();
+ let cleared = self.record_lazy_invalidation_roots(host, &roots).is_some();
if cleared {
self.clear_shadow_cascade_data_in_subtrees(host, &roots);
}
@@ -152,8 +142,8 @@ impl<'a> StyleCacheCleanup<'a> {
self.document_state
.clear_invalidation_clear_all_fallback_reasons();
let (affected_roots, shadow_cascade_scope_roots) = subtrees.into_root_sets();
- let invalidated_handles = self
- .invalidate_existing_subtree_roots(host, &affected_roots)
+ let eagerly_invalidated_roots = self
+ .record_lazy_invalidation_roots(host, &affected_roots)
.expect("subtree cleanup application should carry an existing root");
let cleared_shadow_cascade_roots =
if context.clears_shadow_cascade_data_for_cleanup_target() {
@@ -165,7 +155,7 @@ impl<'a> StyleCacheCleanup<'a> {
context.trace_scoped_fallback(
self.document,
&affected_roots,
- &invalidated_handles,
+ &eagerly_invalidated_roots,
&cleared_shadow_cascade_roots,
generations_before,
generations_after,
@@ -192,6 +182,7 @@ impl<'a> StyleCacheCleanup<'a> {
}
self.computed_style_cache.clear();
self.document_state.clear_selector_caches();
+ self.document_state.lazy_invalidation_roots.clear();
self.document_state.bump_target_context_epoch();
let generations_after = self.document_state.generation_snapshot();
context.trace_clear_all_fallback(self.document, generations_before, generations_after);
@@ -242,23 +233,6 @@ impl<'a> StyleCacheCleanup<'a> {
.collect()
}
- fn cached_handles_in_style_subtrees(
- &self,
- host: &DomHost,
- roots: &IndexSet<DomHandle>,
- ) -> IndexSet<DomHandle> {
- if roots.is_empty() {
- return IndexSet::new();
- }
- let mut candidates = self
- .dom_adapter
- .element_style_value_handles_for_document(self.document)
- .into_iter()
- .collect::<IndexSet<_>>();
- candidates.extend(self.computed_style_cache.handles());
- self.handles_in_style_subtrees(host, roots, candidates)
- }
-
fn handles_in_style_subtrees(
&self,
host: &DomHost,
@@ -275,7 +249,7 @@ impl<'a> StyleCacheCleanup<'a> {
.collect()
}
- fn invalidate_existing_subtree_roots(
+ fn record_lazy_invalidation_roots(
&self,
host: &DomHost,
roots: &IndexSet<DomHandle>,
@@ -283,15 +257,29 @@ impl<'a> StyleCacheCleanup<'a> {
if roots.is_empty() {
return None;
}
- let handles = self.cached_handles_in_style_subtrees(host, roots);
- for &handle in &handles {
- self.dom_adapter.mark_element_style_dirty(handle);
- }
+ self.document_state.lazy_invalidation_roots.record_roots(
+ host,
+ self.document,
+ roots.iter().copied(),
+ );
+
+ // Dirty the roots themselves immediately. Descendants are handled
+ // lazily from the retained root generation, avoiding O(P * depth)
+ // expansion over every published style in the document. Keep doing
+ // the exact-root retirement even when a deferred mutation is drained
+ // after that root was adopted into another Document: the old world
+ // may still own its publication marker, while the adapter moves its
+ // ElementData to the current owner bucket on this targeted access.
+ let immediately_invalidated = roots
+ .iter()
+ .copied()
+ .filter(|handle| self.dom_adapter.mark_element_style_dirty(*handle))
+ .collect::<IndexSet<_>>();
self.computed_style_cache
- .invalidate_handles(handles.iter().copied());
+ .invalidate_handles(roots.iter().copied());
self.document_state.clear_selector_caches();
self.document_state.bump_target_context_epoch();
- Some(handles)
+ Some(immediately_invalidated)
}
}
diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs
index 08c2d1bee..c5c97d508 100644
--- a/moli-renderer-v8/src/style_engine/computed.rs
+++ b/moli-renderer-v8/src/style_engine/computed.rs
@@ -7,7 +7,7 @@ use style::{
SharedStyleContext, StyleContext, StyleSystemOptions, ThreadLocalStyleContext,
},
data::ElementStyles,
- dom::TElement,
+ dom::{TElement, TNode},
properties::{
ComputedValues, PropertyId,
longhands::{
@@ -46,6 +46,7 @@ use super::{
StyleWorldUpdate, StyleWorldUpdatePlan,
cache::ComputedElementStyleCacheKey,
document_world::DocumentStyleWorld,
+ lazy_invalidation::StyleValidationPathEntry,
source_lifecycle::StyleSourceDocumentContext,
world_key::StyleWorldKey,
world_lifecycle::{
@@ -747,7 +748,11 @@ fn with_resolved_style_in_current_world<R>(
callback: impl FnOnce(&ServoArc<ComputedValues>, Option<&ElementStyles>) -> Option<R>,
) -> Option<R> {
let computed_cache_generation = world.document_state.computed_cache_generation();
- if let Some(pseudo_element) = pseudo_element {
+ let has_retained_invalidation_roots = world
+ .document_state
+ .lazy_invalidation_roots
+ .has_retained_roots();
+ if !has_retained_invalidation_roots && let Some(pseudo_element) = pseudo_element {
let pseudo_key = ComputedElementStyleCacheKey {
computed_cache_generation,
handle,
@@ -757,36 +762,66 @@ fn with_resolved_style_in_current_world<R>(
return callback(&style, None);
}
}
+ let validation_path = has_retained_invalidation_roots.then(|| {
+ world
+ .document_state
+ .lazy_invalidation_roots
+ .validation_path(host, world.document, handle)
+ });
engine.dom_adapter.with_bound_host(host, |dom_adapter| {
let element = dom_adapter.element(host, handle)?;
- let canonical_styles = element
+ let canonical_is_current = element
.borrow_data()
- .filter(|data| data.has_styles() && data.hint.is_empty())
- .map(|data| data.styles.clone())
- .unwrap_or_else(|| {
- populate_inline_style_attributes_for_resolution(
- engine,
- host,
- document_url,
- handle,
- quirks_mode,
- );
- install_shadow_cascade_data_for_resolution(world, dom_adapter);
- // `resolve_style` is the single-node initial-style API. Keep
- // dirty values published until this observation begins, then
- // make only the element being recomputed unstyled.
- unsafe {
- element.ensure_data().styles = ElementStyles::default();
- }
- let styles = resolve_element_styles(world, dom_adapter, element, None);
- unsafe {
- let mut data = element.ensure_data();
- data.styles = styles.clone();
- data.clear_restyle_state();
- }
- styles
+ .is_some_and(|data| data.has_styles() && data.hint.is_empty());
+ let path_needs_resolution = validation_path
+ .as_ref()
+ .map_or(!canonical_is_current, |path| {
+ style_validation_path_needs_resolution(world, dom_adapter, host, path)
});
+ if !path_needs_resolution && let Some(pseudo_element) = pseudo_element {
+ let pseudo_key = ComputedElementStyleCacheKey {
+ computed_cache_generation,
+ handle,
+ pseudo_element: Some(pseudo_element.clone()),
+ };
+ if let Some(style) = world.computed_style_cache.get_pseudo(&pseudo_key) {
+ return callback(&style, None);
+ }
+ }
+
+ let canonical_styles = if path_needs_resolution {
+ populate_inline_style_attributes_for_resolution(
+ engine,
+ host,
+ document_url,
+ handle,
+ quirks_mode,
+ );
+ install_shadow_cascade_data_for_resolution(world, dom_adapter);
+ if validation_path.is_none() {
+ // Initial resolution already walks the ancestor chain. Build
+ // its zero-generation stamps only on this slow path so clean
+ // repeated reads retain the old O(1) fast path.
+ world
+ .document_state
+ .lazy_invalidation_roots
+ .validation_path(host, world.document, handle);
+ }
+ resolve_element_styles(
+ world,
+ dom_adapter,
+ element,
+ None,
+ validation_path.as_deref(),
+ )
+ } else {
+ element
+ .borrow_data()
+ .filter(|data| data.has_styles() && data.hint.is_empty())
+ .map(|data| data.styles.clone())
+ .expect("a current validation path must end in published element styles")
+ };
let style = if let Some(pseudo_element) = pseudo_element {
let style = canonical_styles
@@ -795,10 +830,16 @@ fn with_resolved_style_in_current_world<R>(
.cloned()
.or_else(|| {
install_shadow_cascade_data_for_resolution(world, dom_adapter);
- resolve_element_styles(world, dom_adapter, element, Some(pseudo_element))
- .pseudos
- .get(pseudo_element)
- .cloned()
+ resolve_element_styles(
+ world,
+ dom_adapter,
+ element,
+ Some(pseudo_element),
+ validation_path.as_deref(),
+ )
+ .pseudos
+ .get(pseudo_element)
+ .cloned()
})?;
world.computed_style_cache.insert_pseudo(
ComputedElementStyleCacheKey {
@@ -841,6 +882,7 @@ fn resolve_element_styles(
dom_adapter: &moli_selector::StyloDomHostBinding<'_>,
element: StyloElement<'_>,
pseudo_element: Option<&PseudoElement>,
+ validation_path: Option<&[StyleValidationPathEntry]>,
) -> ElementStyles {
let shared_lock = dom_adapter.shared_lock().clone();
let guard = shared_lock.read();
@@ -870,8 +912,20 @@ fn resolve_element_styles(
shared: &shared,
thread_local: &mut thread_local,
};
- let ancestor_resolution_count =
- materialize_ancestor_styles_for_resolution(&mut context, element);
+ let ancestor_resolution_count = materialize_ancestor_styles_for_resolution(
+ &mut context,
+ element,
+ world,
+ validation_path,
+ );
+ let target = DomHandle::new(element.as_node().debug_id());
+ world.computed_style_cache.invalidate_handles([target]);
+ // `resolve_style` is the single-node initial-style API. Keep dirty
+ // values published until this observation begins, then replace only
+ // the demanded path from ancestors to target.
+ unsafe {
+ element.ensure_data().styles = ElementStyles::default();
+ }
let styles = resolve_style(
&mut context,
element,
@@ -879,6 +933,20 @@ fn resolve_element_styles(
pseudo_element,
None,
);
+ unsafe {
+ let mut data = element.ensure_data();
+ data.styles = styles.clone();
+ data.clear_restyle_state();
+ }
+ let required_generation = world
+ .document_state
+ .lazy_invalidation_roots
+ .required_generation_for_checked_element(target)
+ .unwrap_or_default();
+ world
+ .document_state
+ .lazy_invalidation_roots
+ .mark_element_current(target, required_generation);
std::mem::swap(
&mut context.thread_local.selector_caches,
&mut retained_selector_caches,
@@ -894,25 +962,52 @@ fn resolve_element_styles(
styles
}
-fn materialize_ancestor_styles_for_resolution<E>(context: &mut StyleContext<E>, element: E) -> u64
+fn materialize_ancestor_styles_for_resolution<E>(
+ context: &mut StyleContext<E>,
+ element: E,
+ world: &DocumentStyleWorld,
+ validation_path: Option<&[StyleValidationPathEntry]>,
+) -> u64
where
E: TElement,
{
- let mut ancestors = Vec::new();
- let mut current = element.traversal_parent();
- while let Some(ancestor) = current {
- ancestors.push(ancestor);
- current = ancestor.traversal_parent();
- }
+ let ancestors = validation_path
+ .and_then(|path| validation_path_ancestors(element, path))
+ .unwrap_or_else(|| {
+ let mut ancestors = Vec::new();
+ let mut current = element.traversal_parent();
+ while let Some(ancestor) = current {
+ let handle = DomHandle::new(ancestor.as_node().debug_id());
+ let required_generation = world
+ .document_state
+ .lazy_invalidation_roots
+ .required_generation_for_checked_element(handle)
+ .unwrap_or_default();
+ ancestors.push((ancestor, required_generation));
+ current = ancestor.traversal_parent();
+ }
+ ancestors.reverse();
+ ancestors
+ });
+ world
+ .document_state
+ .note_ancestor_style_validation_visits(ancestors.len() as u64);
let mut resolution_count = 0_u64;
- for ancestor in ancestors.into_iter().rev() {
- if ancestor
+ let mut force_descendants = false;
+ for (ancestor, required_generation) in ancestors {
+ let handle = DomHandle::new(ancestor.as_node().debug_id());
+ let canonical_is_current = ancestor
.borrow_data()
.is_some_and(|data| data.has_styles() && data.hint.is_empty())
- {
+ && world
+ .document_state
+ .lazy_invalidation_roots
+ .element_is_current(handle, required_generation);
+ if canonical_is_current && !force_descendants {
continue;
}
+ world.computed_style_cache.invalidate_handles([handle]);
unsafe {
ancestor.ensure_data().styles = ElementStyles::default();
}
@@ -923,10 +1018,70 @@ where
data.styles = styles;
data.clear_restyle_state();
}
+ world
+ .document_state
+ .lazy_invalidation_roots
+ .mark_element_current(handle, required_generation);
+ force_descendants = true;
}
resolution_count
}
+/// Maps the memoized DOM path suffix back to Stylo ancestors.
+///
+/// `LazyStyleInvalidationRoots::validation_path` stops at the nearest handle
+/// already stamped for the current registry generation. That handle's style
+/// has already been validated by the observation that published the stamp, so
+/// a later child read only needs to inspect the unstamped suffix. If the DOM
+/// and Stylo parent contracts ever disagree, return `None` and conservatively
+/// use the complete ancestor chain above.
+fn validation_path_ancestors<E>(
+ element: E,
+ validation_path: &[StyleValidationPathEntry],
+) -> Option<Vec<(E, u64)>>
+where
+ E: TElement,
+{
+ let (target, ancestor_entries) = validation_path.split_last()?;
+ if target.element != DomHandle::new(element.as_node().debug_id()) {
+ return None;
+ }
+
+ let mut current = element.traversal_parent();
+ let mut ancestors = Vec::with_capacity(ancestor_entries.len());
+ for entry in ancestor_entries.iter().rev() {
+ let ancestor = current?;
+ if entry.element != DomHandle::new(ancestor.as_node().debug_id()) {
+ return None;
+ }
+ ancestors.push((ancestor, entry.required_generation));
+ current = ancestor.traversal_parent();
+ }
+ ancestors.reverse();
+ Some(ancestors)
+}
+
+fn style_validation_path_needs_resolution(
+ world: &DocumentStyleWorld,
+ dom_adapter: &moli_selector::StyloDomHostBinding<'_>,
+ host: &DomHost,
+ validation_path: &[StyleValidationPathEntry],
+) -> bool {
+ validation_path.iter().any(|entry| {
+ !world
+ .document_state
+ .lazy_invalidation_roots
+ .element_is_current(entry.element, entry.required_generation)
+ || dom_adapter
+ .element(host, entry.element)
+ .is_none_or(|element| {
+ element
+ .borrow_data()
+ .is_none_or(|data| !data.has_styles() || !data.hint.is_empty())
+ })
+ })
+}
+
fn with_lazily_resolved_pseudo_style<R>(
engine: &MoliStyleEngine,
host: &DomHost,
@@ -973,15 +1128,9 @@ fn with_lazily_resolved_pseudo_style_in_current_world<R>(
callback: impl FnOnce(&ComputedValues) -> Option<R>,
) -> Option<R> {
debug_assert!(pseudo_element.is_lazy());
- let computed_key = ComputedElementStyleCacheKey {
- computed_cache_generation: world.document_state.computed_cache_generation(),
- handle,
- pseudo_element: Some(pseudo_element.clone()),
- };
- if let Some(style) = world.computed_style_cache.get_pseudo(&computed_key) {
- return callback(&style);
- }
-
+ // Resolve/validate the primary path before consulting the pseudo sidecar.
+ // A retained lazy invalidation root intentionally leaves old pseudo entries
+ // in the cache until their owning element is demanded.
let primary_style = with_resolved_style_in_current_world(
engine,
host,
@@ -993,6 +1142,15 @@ fn with_lazily_resolved_pseudo_style_in_current_world<R>(
|style, _styles| Some(style.clone()),
)?;
+ let computed_key = ComputedElementStyleCacheKey {
+ computed_cache_generation: world.document_state.computed_cache_generation(),
+ handle,
+ pseudo_element: Some(pseudo_element.clone()),
+ };
+ if let Some(style) = world.computed_style_cache.get_pseudo(&computed_key) {
+ return callback(&style);
+ }
+
engine.dom_adapter.with_bound_host(host, |dom_adapter| {
let element = dom_adapter.element(host, handle)?;
diff --git a/moli-renderer-v8/src/style_engine/document_world.rs b/moli-renderer-v8/src/style_engine/document_world.rs
index b46f44b4b..200c9302c 100644
--- a/moli-renderer-v8/src/style_engine/document_world.rs
+++ b/moli-renderer-v8/src/style_engine/document_world.rs
@@ -84,6 +84,16 @@ impl DocumentStyleWorlds {
self.for_document(document).clear_for_document_replacement();
}
+ /// Retires one handle's publication from whichever Document world last
+ /// exposed it. A DOM adoption can change `ownerDocument` before deferred
+ /// style work is drained, so consulting only the current owner would leave
+ /// the old world's marker behind.
+ pub(super) fn invalidate_computed_style_handle(&self, handle: DomHandle) {
+ for world in self.worlds.borrow().values() {
+ world.computed_style_cache.invalidate_handles([handle]);
+ }
+ }
+
pub(super) fn documents_with_adopted_style_sheets(&self) -> Vec<DomHandle> {
self.worlds
.borrow()
diff --git a/moli-renderer-v8/src/style_engine/lazy_invalidation.rs b/moli-renderer-v8/src/style_engine/lazy_invalidation.rs
new file mode 100644
index 000000000..9a2c3157e
--- /dev/null
+++ b/moli-renderer-v8/src/style_engine/lazy_invalidation.rs
@@ -0,0 +1,249 @@
+use std::{
+ cell::{Cell, RefCell},
+ collections::{HashMap, HashSet},
+};
+
+use indexmap::IndexSet;
+
+use crate::{document_runtime::DomHandle, dom::native::DomHost};
+
+/// Bounds sparse invalidation-root history without requiring a scan of
+/// published element styles to retire individual generations.
+const MAX_RETAINED_INVALIDATION_ROOTS: usize = 1_024;
+
+/// One element on the style-parent path to a demanded target.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct StyleValidationPathEntry {
+ pub(super) element: DomHandle,
+ pub(super) required_generation: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct StylePathStamp {
+ registry_generation: u64,
+ required_generation: u64,
+}
+
+/// Document-local retained roots for demand-driven style invalidation.
+///
+/// An invalidation root is stamped with the mutation generation that created
+/// it. Published element styles carry the newest generation against which they
+/// were resolved. Reads walk only their own ancestor path, accumulate the
+/// newest covering root, and recompute stale entries from parent to child.
+/// This is Moli's side-table equivalent of Blink's per-node dirty flags and
+/// `ChildNeedsStyleRecalc` breadcrumbs; it preserves Moli's on-demand style
+/// model without an eager scan over every published `ElementData` entry.
+#[derive(Default)]
+pub(super) struct LazyStyleInvalidationRoots {
+ generation: Cell<u64>,
+ document_floor_generation: Cell<u64>,
+ roots: RefCell<HashMap<DomHandle, u64>>,
+ /// Memoized generation inherited from the nearest invalidation root.
+ ///
+ /// A new mutation generation invalidates these stamps logically, without
+ /// walking the table. While an observation proceeds parent-before-child,
+ /// each next lookup normally reaches an already stamped parent after one
+ /// step. A whole tree observation is therefore linear rather than
+ /// `elements * depth`.
+ path_stamps: RefCell<HashMap<DomHandle, StylePathStamp>>,
+ validated_elements: RefCell<HashMap<DomHandle, u64>>,
+ #[cfg(test)]
+ path_node_visits: Cell<u64>,
+}
+
+impl LazyStyleInvalidationRoots {
+ pub(super) fn record_roots(
+ &self,
+ host: &DomHost,
+ document: DomHandle,
+ roots: impl IntoIterator<Item = DomHandle>,
+ ) -> IndexSet<DomHandle> {
+ let roots = roots
+ .into_iter()
+ .filter(|root| {
+ host.node(*root).is_some()
+ && (*root == document || host.owner_document_handle(*root) == Some(document))
+ })
+ .collect::<IndexSet<_>>();
+ if roots.is_empty() {
+ return roots;
+ }
+
+ let generation = self.next_generation();
+ self.generation.set(generation);
+ let mut retained = self.roots.borrow_mut();
+ for root in roots.iter().copied() {
+ retained.insert(root, generation);
+ }
+
+ if retained.len() > MAX_RETAINED_INVALIDATION_ROOTS {
+ self.document_floor_generation.set(generation);
+ retained.clear();
+ }
+ roots
+ }
+
+ /// Returns whether this document has retained invalidation-root history.
+ ///
+ /// History remains present after individual elements consume it because
+ /// there is intentionally no global "all descendants are current" scan.
+ /// Current-generation path stamps make clean repeated reads O(1).
+ pub(super) fn has_retained_roots(&self) -> bool {
+ self.generation.get() != 0
+ }
+
+ pub(super) fn validation_path(
+ &self,
+ host: &DomHost,
+ document: DomHandle,
+ target: DomHandle,
+ ) -> Vec<StyleValidationPathEntry> {
+ if host.owner_document_handle(target) != Some(document) {
+ return Vec::new();
+ }
+
+ let registry_generation = self.generation.get();
+ let floor_generation = self.document_floor_generation.get();
+ let roots = self.roots.borrow();
+ let mut path_stamps = self.path_stamps.borrow_mut();
+ let mut unstamped_path = Vec::new();
+ let mut seen = HashSet::new();
+ let mut current = Some(target);
+ let mut required_generation = floor_generation;
+ while let Some(handle) = current.filter(|handle| seen.insert(*handle)) {
+ self.note_path_node_visit();
+ if let Some(stamp) = path_stamps
+ .get(&handle)
+ .filter(|stamp| stamp.registry_generation == registry_generation)
+ {
+ required_generation = required_generation.max(stamp.required_generation);
+ break;
+ }
+ unstamped_path.push(handle);
+ current = host
+ .parent_node(handle)
+ .or_else(|| host.shadow_root_host(handle));
+ }
+
+ unstamped_path.reverse();
+ let mut entries = unstamped_path
+ .into_iter()
+ .filter_map(|handle| {
+ if let Some(root_generation) = roots.get(&handle) {
+ required_generation = required_generation.max(*root_generation);
+ }
+ path_stamps.insert(
+ handle,
+ StylePathStamp {
+ registry_generation,
+ required_generation,
+ },
+ );
+ host.node(handle)
+ .and_then(|node| node.as_element())
+ .map(|_| StyleValidationPathEntry {
+ element: handle,
+ required_generation,
+ })
+ })
+ .collect::<Vec<_>>();
+
+ // A fully memoized target still needs one entry so callers can check
+ // the canonical ElementData against its inherited requirement in O(1).
+ if entries.is_empty()
+ && let Some(stamp) = path_stamps
+ .get(&target)
+ .filter(|stamp| stamp.registry_generation == registry_generation)
+ && host
+ .node(target)
+ .and_then(|node| node.as_element())
+ .is_some()
+ {
+ entries.push(StyleValidationPathEntry {
+ element: target,
+ required_generation: stamp.required_generation,
+ });
+ }
+ entries
+ }
+
+ pub(super) fn required_generation_for_checked_element(
+ &self,
+ element: DomHandle,
+ ) -> Option<u64> {
+ let registry_generation = self.generation.get();
+ self.path_stamps
+ .borrow()
+ .get(&element)
+ .filter(|stamp| stamp.registry_generation == registry_generation)
+ .map(|stamp| stamp.required_generation)
+ }
+
+ pub(super) fn element_is_current(&self, element: DomHandle, required_generation: u64) -> bool {
+ required_generation == 0
+ || self
+ .validated_elements
+ .borrow()
+ .get(&element)
+ .copied()
+ .unwrap_or_default()
+ >= required_generation
+ }
+
+ pub(super) fn mark_element_current(&self, element: DomHandle, generation: u64) {
+ if generation == 0 {
+ return;
+ }
+ let mut validated = self.validated_elements.borrow_mut();
+ let entry = validated.entry(element).or_default();
+ *entry = (*entry).max(generation);
+ }
+
+ pub(super) fn clear(&self) {
+ self.generation.set(0);
+ self.document_floor_generation.set(0);
+ self.roots.borrow_mut().clear();
+ self.path_stamps.borrow_mut().clear();
+ self.validated_elements.borrow_mut().clear();
+ #[cfg(test)]
+ self.path_node_visits.set(0);
+ }
+
+ #[cfg(test)]
+ pub(super) fn root_count(&self) -> usize {
+ self.roots.borrow().len()
+ }
+
+ #[cfg(test)]
+ pub(super) fn generation(&self) -> u64 {
+ self.generation.get()
+ }
+
+ #[cfg(test)]
+ pub(super) fn path_node_visit_count(&self) -> u64 {
+ self.path_node_visits.get()
+ }
+
+ fn next_generation(&self) -> u64 {
+ let Some(next) = self.generation.get().checked_add(1) else {
+ // A wrapped generation could make an old validation stamp appear
+ // current. Reset the sparse history and conservatively invalidate
+ // the whole document instead.
+ self.document_floor_generation.set(1);
+ self.roots.borrow_mut().clear();
+ self.path_stamps.borrow_mut().clear();
+ self.validated_elements.borrow_mut().clear();
+ return 1;
+ };
+ next
+ }
+
+ #[cfg(test)]
+ fn note_path_node_visit(&self) {
+ self.path_node_visits
+ .set(self.path_node_visits.get().saturating_add(1));
+ }
+
+ #[cfg(not(test))]
+ fn note_path_node_visit(&self) {}
+}
diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rs
index 1d2d71339..884fef457 100644
--- a/moli-renderer-v8/src/style_engine/mod.rs
+++ b/moli-renderer-v8/src/style_engine/mod.rs
@@ -36,6 +36,7 @@ mod drain;
mod eligibility;
mod fallback;
mod invalidation;
+mod lazy_invalidation;
pub(crate) mod media_list;
mod mutation_effect;
mod outcome;
@@ -408,6 +409,49 @@ impl MoliStyleEngine {
.entry_count_for_handle_for_test(handle)
}
+ #[cfg(test)]
+ pub(crate) fn retained_style_invalidation_root_count_for_document_for_test(
+ &self,
+ document: DomHandle,
+ ) -> usize {
+ self.world_for_document(document)
+ .document_state
+ .lazy_invalidation_roots
+ .root_count()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn style_invalidation_generation_for_document_for_test(
+ &self,
+ document: DomHandle,
+ ) -> u64 {
+ self.world_for_document(document)
+ .document_state
+ .lazy_invalidation_roots
+ .generation()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn style_invalidation_path_node_visit_count_for_document_for_test(
+ &self,
+ document: DomHandle,
+ ) -> u64 {
+ self.world_for_document(document)
+ .document_state
+ .lazy_invalidation_roots
+ .path_node_visit_count()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn ancestor_style_validation_visit_count_for_document_for_test(
+ &self,
+ document: DomHandle,
+ ) -> u64 {
+ self.world_for_document(document)
+ .document_state
+ .ancestor_style_validation_visit_count()
+ }
+
#[cfg(test)]
pub(crate) fn source_dirty_scope_source_ids_for_document_for_test(
&self,
@@ -618,6 +662,18 @@ impl MoliStyleEngine {
.clear_for_document_replacement(document);
}
+ /// Drops the exact target's canonical style and publication markers after
+ /// it leaves every rendered style context.
+ ///
+ /// This is deliberately target-local. Subtree invalidation remains lazy;
+ /// a disconnected `getComputedStyle()` read must not reintroduce the old
+ /// document-wide scan merely to retire the one target it observes.
+ pub(crate) fn retire_computed_style_for_inactive_handle(&self, handle: DomHandle) {
+ self.dom_adapter.clear_element_data(handle);
+ self.document_worlds
+ .invalidate_computed_style_handle(handle);
+ }
+
fn clear_owner_document_indexes_for_document(&self, document: DomHandle) {
retain_owner_documents_except_document(
&mut self.owner_stylesheet_source_documents.borrow_mut(),
diff --git a/moli-renderer-v8/src/style_engine/outcome.rs b/moli-renderer-v8/src/style_engine/outcome.rs
index f3a9174f2..1e93ae823 100644
--- a/moli-renderer-v8/src/style_engine/outcome.rs
+++ b/moli-renderer-v8/src/style_engine/outcome.rs
@@ -530,7 +530,7 @@ impl StyleInvalidationCleanupApplicationContext {
&self,
document: DomHandle,
affected_roots: &IndexSet<DomHandle>,
- invalidated_cache_handles: &IndexSet<DomHandle>,
+ eagerly_invalidated_root_handles: &IndexSet<DomHandle>,
shadow_cascade_roots: &IndexSet<DomHandle>,
generations_before: StyleDocumentGenerationSnapshot,
generations_after: StyleDocumentGenerationSnapshot,
@@ -547,8 +547,8 @@ impl StyleInvalidationCleanupApplicationContext {
self.clear_shadow_cascade_data_for_cleanup_target,
affected_root_count = affected_roots.len(),
affected_roots = ?affected_roots,
- invalidated_cache_handle_count = invalidated_cache_handles.len(),
- invalidated_cache_handles = ?invalidated_cache_handles,
+ eagerly_invalidated_root_handle_count = eagerly_invalidated_root_handles.len(),
+ eagerly_invalidated_root_handles = ?eagerly_invalidated_root_handles,
source_fallback_shadow_cascade_root_count = shadow_cascade_roots.len(),
source_fallback_shadow_cascade_roots = ?shadow_cascade_roots,
source_set_generation_before = generations_before.source_set_generation,
@@ -561,7 +561,7 @@ impl StyleInvalidationCleanupApplicationContext {
generations_after.retained_style_system_generation,
target_context_epoch_before = generations_before.target_context_epoch,
target_context_epoch_after = generations_after.target_context_epoch,
- "style invalidation fallback cleared scoped style caches"
+ "style invalidation fallback recorded lazy dirty roots"
);
}
}
diff --git a/moli-renderer-v8/src/style_engine/state.rs b/moli-renderer-v8/src/style_engine/state.rs
index 2ec0fe97d..f995202dd 100644
--- a/moli-renderer-v8/src/style_engine/state.rs
+++ b/moli-renderer-v8/src/style_engine/state.rs
@@ -16,6 +16,7 @@ use super::{
CssCustomPropertyRegistrationRecord, StyleTreeScopeVersions, StyleViewport,
StyloStyleEnvironment,
active_stylesheets::ActiveStylesheetCollection,
+ lazy_invalidation::LazyStyleInvalidationRoots,
shadow_scopes::ShadowScopeStyles,
source_dirty::{StyleSourceDirtyReason, StyleSourceDirtyScopeSnapshot, StyleSourceDirtyScopes},
source_id::{StyleScopeId, StyleSourceId},
@@ -86,6 +87,7 @@ pub(super) struct StyleDocumentState {
computed_cache_generation: Cell<u64>,
retained_style_system_generation: Cell<u64>,
target_context_epoch: Cell<u64>,
+ pub(super) lazy_invalidation_roots: LazyStyleInvalidationRoots,
#[cfg(debug_assertions)]
completed_style_observation: RefCell<Option<CompletedStyleObservation>>,
#[cfg(all(test, debug_assertions))]
@@ -96,6 +98,8 @@ pub(super) struct StyleDocumentState {
retained_style_system_updates: Cell<u64>,
#[cfg(test)]
element_style_resolutions: Cell<u64>,
+ #[cfg(test)]
+ ancestor_style_validation_visits: Cell<u64>,
}
impl StyleDocumentState {
@@ -108,6 +112,7 @@ impl StyleDocumentState {
computed_cache_generation: Cell::new(0),
retained_style_system_generation: Cell::new(0),
target_context_epoch: Cell::new(0),
+ lazy_invalidation_roots: LazyStyleInvalidationRoots::default(),
#[cfg(debug_assertions)]
completed_style_observation: RefCell::new(None),
#[cfg(all(test, debug_assertions))]
@@ -118,6 +123,8 @@ impl StyleDocumentState {
retained_style_system_updates: Cell::new(0),
#[cfg(test)]
element_style_resolutions: Cell::new(0),
+ #[cfg(test)]
+ ancestor_style_validation_visits: Cell::new(0),
}
}
@@ -208,6 +215,7 @@ impl StyleDocumentState {
pub(super) fn clear_retained_style_system(&self) {
self.retained_style_system.borrow_mut().take();
+ self.lazy_invalidation_roots.clear();
self.clear_source_dirty_scopes();
self.clear_invalidation_clear_all_fallback_reasons();
self.clear_selector_caches();
@@ -365,6 +373,23 @@ impl StyleDocumentState {
self.element_style_resolutions.get()
}
+ #[cfg(test)]
+ pub(super) fn note_ancestor_style_validation_visits(&self, count: u64) {
+ self.ancestor_style_validation_visits.set(
+ self.ancestor_style_validation_visits
+ .get()
+ .saturating_add(count),
+ );
+ }
+
+ #[cfg(not(test))]
+ pub(super) fn note_ancestor_style_validation_visits(&self, _count: u64) {}
+
+ #[cfg(test)]
+ pub(super) fn ancestor_style_validation_visit_count(&self) -> u64 {
+ self.ancestor_style_validation_visits.get()
+ }
+
pub(super) fn with_shadow_cascade_data<R>(
&self,
callback: impl FnOnce(&[(DomHandle, ServoArc<CascadeData>)]) -> R,
diff --git a/moli-renderer-v8/src/style_engine/tests/char_child.rs b/moli-renderer-v8/src/style_engine/tests/char_child.rs
index 7bcbb217a..7e3d53576 100644
--- a/moli-renderer-v8/src/style_engine/tests/char_child.rs
+++ b/moli-renderer-v8/src/style_engine/tests/char_child.rs
@@ -135,14 +135,13 @@ fn character_data_has_empty_dependency_invalidates_ancestor_subjects() {
let mut engine = MoliStyleEngine::new();
let document_url = url::Url::parse("https://example.test/").unwrap();
- engine.set_document_adopted_style_sheet_sources(
- document,
- vec![StyloStylesheetSource::new(
- ".container:has(.child:empty) .target { color: red; }".into(),
- document_url.clone(),
- )],
+ let source = StyloStylesheetSource::new(
+ ".container:has(.child:empty) .target { color: red; }".into(),
+ document_url.clone(),
);
- let inputs = FullStyleWorldSnapshot::default();
+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source);
for handle in [child, target] {
assert!(
engine
@@ -162,7 +161,6 @@ fn character_data_has_empty_dependency_invalidates_ancestor_subjects() {
engine.computed_style_cache_entry_count_for_document_for_test(document),
2
);
-
let media = crate::protocol_types::EmulatedMediaOverrides::default();
engine.invalidate_for_mutations(
&host,
@@ -173,8 +171,10 @@ fn character_data_has_empty_dependency_invalidates_ancestor_subjects() {
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 0
+ 0,
+ "the exact :has(:empty) target query invalidates both published targets"
);
+ assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, target));
}
#[test]
diff --git a/moli-renderer-v8/src/style_engine/tests/dependency.rs b/moli-renderer-v8/src/style_engine/tests/dependency.rs
index 696b11e71..83acbd76f 100644
--- a/moli-renderer-v8/src/style_engine/tests/dependency.rs
+++ b/moli-renderer-v8/src/style_engine/tests/dependency.rs
@@ -2773,13 +2773,22 @@ fn source_scope_fallback_roots_preserve_unrelated_document_cache() {
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 0
+ 1,
+ "document fallback records a lazy root instead of enumerating published descendants"
);
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(detached_document),
1
);
- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, active));
+ assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));
+ assert_eq!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(document),
+ 1
+ );
+ assert_eq!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(detached_document),
+ 0
+ );
assert!(
engine.computed_style_cache_contains_handle_for_document_for_test(
detached_document,
@@ -2847,15 +2856,24 @@ fn source_scope_fallback_roots_preserve_active_document_cache_for_detached_docum
);
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(detached_document),
- 0
+ 1,
+ "detached-document fallback records a lazy root in only that document world"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(
+ engine.computed_style_cache_contains_handle_for_document_for_test(
detached_document,
detached
)
);
+ assert_eq!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(document),
+ 0
+ );
+ assert_eq!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(detached_document),
+ 1
+ );
}
#[test]
fn unsupported_state_change_without_snapshot_uses_source_scope_fallback() {
@@ -2933,13 +2951,18 @@ fn unsupported_state_change_without_snapshot_uses_source_scope_fallback() {
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 0
+ 1,
+ "source-scope fallback must defer descendant recascade until observation"
);
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(detached_document),
1
);
- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, active));
+ assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));
+ assert_eq!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(document),
+ 1
+ );
assert!(
engine.computed_style_cache_contains_handle_for_document_for_test(
detached_document,
diff --git a/moli-renderer-v8/src/style_engine/tests/invalidator.rs b/moli-renderer-v8/src/style_engine/tests/invalidator.rs
index afc2632e1..556411b69 100644
--- a/moli-renderer-v8/src/style_engine/tests/invalidator.rs
+++ b/moli-renderer-v8/src/style_engine/tests/invalidator.rs
@@ -258,7 +258,12 @@ fn has_selector_child_list_invalidation_uses_target_queries_without_rebuilding_s
engine.drain_pending_style_invalidations_for_document_for_test(&host, document);
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 0
+ 2,
+ "the broad :has() cleanup must retain published descendants until observation"
+ );
+ assert!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(document) > 0,
+ "the broad target-query result must be retained as lazy roots"
);
}
@@ -1470,12 +1475,26 @@ fn retained_stylo_invalidator_keeps_self_dependency_inheritance_safe() {
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 2
+ 3,
+ "only the matched parent is evicted eagerly; its child inherits the lazy root"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));
assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, parent));
- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, child));
+ assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, child));
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, unrelated));
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ child,
+ "color",
+ None,
+ &inputs,
+ None,
+ ),
+ Some("rgb(0, 0, 255)".into()),
+ "reading the child must recascade the matched parent before inheriting"
+ );
}
#[test]
fn retained_stylo_invalidator_ignores_unrelated_shadow_cascade_data() {
@@ -2014,7 +2033,7 @@ fn retained_stylo_invalidator_uses_shadow_relative_dependency() {
}
#[test]
-fn retained_stylo_invalidator_clears_shadow_host_for_shadow_tree_has_dependency() {
+fn retained_stylo_invalidator_lazily_refreshes_shadow_tree_has_descendants() {
let mut host = test_host();
let document = host.document_handle();
let outside = host.create_element("aside");
@@ -2079,14 +2098,15 @@ fn retained_stylo_invalidator_clears_shadow_host_for_shadow_tree_has_dependency(
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 2,
+ "the shadow child remains published behind the dirty shadow-host root"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));
assert!(
!engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_host)
);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)
);
assert_eq!(
engine.computed_style_property_value(
@@ -2103,7 +2123,7 @@ fn retained_stylo_invalidator_clears_shadow_host_for_shadow_tree_has_dependency(
}
#[test]
-fn retained_stylo_invalidator_clears_shadow_subject_for_host_context_inside_has_dependency() {
+fn retained_stylo_invalidator_lazily_refreshes_shadow_host_context_subject() {
let mut host = test_host();
let document = host.document_handle();
let host_parent = host.create_element("div");
@@ -2185,10 +2205,11 @@ fn retained_stylo_invalidator_clears_shadow_subject_for_host_context_inside_has_
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 2,
+ "the shadow subject remains published until its dirty scope is observed"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));
- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, subject));
+ assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, subject));
assert_eq!(
engine.computed_style_property_value(
&host,
@@ -2268,14 +2289,28 @@ fn retained_stylo_invalidator_keeps_shadow_host_self_dependency_conservative() {
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 2,
+ "the host is evicted directly while its shadow child is invalidated lazily"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));
assert!(
!engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_host)
);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)
+ );
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ shadow_child,
+ "color",
+ None,
+ &inputs,
+ None,
+ ),
+ Some("rgb(0, 0, 255)".into()),
+ "the shadow child must inherit the refreshed host style on demand"
);
}
#[test]
@@ -4848,7 +4883,10 @@ fn retained_stylo_invalidator_defers_large_child_list_batches_until_drain() {
engine.pending_style_invalidation_work_item_count_for_document_for_test(document),
0
);
- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, subject));
+ assert!(
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, subject),
+ "the coalesced broad invalidation must not enumerate its published descendants"
+ );
assert_eq!(
engine.computed_style_property_value(
&host,
diff --git a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
index a16e875bb..986935e34 100644
--- a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
+++ b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
@@ -317,14 +317,16 @@ fn active_document_light_tree_mutation_matches_related_shadow_sources() {
engine.invalidate_for_mutations(&host, &effect, &media);
engine.drain_pending_style_invalidations_for_document_for_test(&host, document);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(
+ engine.computed_style_cache_contains_handle_for_document_for_test(
document,
descendant_target
- )
+ ),
+ "the related shadow target stays published behind a lazy dirty root"
);
assert!(
engine.computed_style_cache_contains_handle_for_document_for_test(document, sibling_target)
);
+ assert!(engine.retained_style_invalidation_root_count_for_document_for_test(document) > 0);
}
#[test]
fn author_stylesheet_sources_are_owned_by_style_engine() {
diff --git a/moli-renderer-v8/src/style_engine/tests/outcome.rs b/moli-renderer-v8/src/style_engine/tests/outcome.rs
index 86c725e2e..92b4af382 100644
--- a/moli-renderer-v8/src/style_engine/tests/outcome.rs
+++ b/moli-renderer-v8/src/style_engine/tests/outcome.rs
@@ -1699,15 +1699,20 @@ fn target_query_drain_clear_all_when_retained_fallback_has_no_roots() {
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 0
+ 1,
+ "the document fallback is retained as a lazy root"
);
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(detached_document),
1
);
assert!(
- element_style_is_dirty_for_test(&engine, &host, active),
- "scoped fallback should retain the last computed values and mark them dirty"
+ !element_style_is_dirty_for_test(&engine, &host, active),
+ "a document root no longer enumerates and marks published descendants eagerly"
+ );
+ assert_eq!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(document),
+ 1
);
assert!(engine.dom_adapter.has_element_data(detached));
assert!(engine.target_context_epoch_for_document_for_test(document) > target_epoch);
@@ -1942,12 +1947,17 @@ fn detached_document_rootless_source_fallback_clears_only_source_document_world(
);
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(detached_document),
- 0
+ 1,
+ "the detached document root is retained without scanning its published descendants"
);
assert!(engine.dom_adapter.has_element_data(active));
assert!(
- element_style_is_dirty_for_test(&engine, &host, detached),
- "scoped fallback should retain the last computed values and mark them dirty"
+ !element_style_is_dirty_for_test(&engine, &host, detached),
+ "the descendant becomes stale through its document generation, not an eager restyle hint"
+ );
+ assert_eq!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(detached_document),
+ 1
);
}
diff --git a/moli-renderer-v8/src/style_engine/tests/slotted_focus.rs b/moli-renderer-v8/src/style_engine/tests/slotted_focus.rs
index 39e44bef9..4380a27b0 100644
--- a/moli-renderer-v8/src/style_engine/tests/slotted_focus.rs
+++ b/moli-renderer-v8/src/style_engine/tests/slotted_focus.rs
@@ -154,12 +154,12 @@ fn slotted_dependency_change_clears_assigned_descendant_cache_via_subtree_cleanu
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 2,
+ "the assigned descendant is retained until it is observed"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));
assert!(
- !engine
- .computed_style_cache_contains_handle_for_document_for_test(document, assigned_child)
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, assigned_child)
);
assert_eq!(
engine.computed_style_property_value(
@@ -1597,14 +1597,13 @@ fn focus_invalidation_uses_has_focus_relative_dependency() {
let mut engine = MoliStyleEngine::new();
let document_url = url::Url::parse("https://example.test/").unwrap();
- engine.set_document_adopted_style_sheet_sources(
- document,
- vec![StyloStylesheetSource::new(
- ".container:has(:focus) .target { color: blue; }".into(),
- document_url.clone(),
- )],
+ let source_sheet = StyloStylesheetSource::new(
+ ".container:has(:focus) .target { color: blue; }".into(),
+ document_url.clone(),
);
- let inputs = FullStyleWorldSnapshot::default();
+ engine.set_document_adopted_style_sheet_sources(document, vec![source_sheet.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source_sheet);
assert!(
engine
.computed_style_property_value(
@@ -1623,13 +1622,28 @@ fn focus_invalidation_uses_has_focus_relative_dependency() {
1
);
+ host.set_active_element_handle(Some(source));
let media = crate::protocol_types::EmulatedMediaOverrides::default();
engine.invalidate_for_focus_change(&host, None, Some(source), &media);
engine.drain_pending_style_invalidations_for_document_for_test(&host, document);
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 0
+ 0,
+ "the exact :has(:focus) target is invalidated directly"
+ );
+ assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, target));
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ target,
+ "color",
+ None,
+ &inputs,
+ None,
+ ),
+ Some("rgb(0, 0, 255)".into())
);
}
#[test]
@@ -1751,14 +1765,13 @@ fn target_invalidation_uses_has_target_relative_dependency() {
let mut engine = MoliStyleEngine::new();
let document_url = url::Url::parse("https://example.test/").unwrap();
- engine.set_document_adopted_style_sheet_sources(
- document,
- vec![StyloStylesheetSource::new(
- ".container:has(:target) .target { color: blue; }".into(),
- document_url.clone(),
- )],
+ let source_sheet = StyloStylesheetSource::new(
+ ".container:has(:target) .target { color: blue; }".into(),
+ document_url.clone(),
);
- let inputs = FullStyleWorldSnapshot::default();
+ engine.set_document_adopted_style_sheet_sources(document, vec![source_sheet.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source_sheet);
assert!(
engine
.computed_style_property_value(
@@ -1777,13 +1790,28 @@ fn target_invalidation_uses_has_target_relative_dependency() {
1
);
+ assert!(host.set_document_target_element(document, Some(source)));
let media = crate::protocol_types::EmulatedMediaOverrides::default();
engine.invalidate_for_target_change(&host, None, Some(source), &media);
engine.drain_pending_style_invalidations_for_document_for_test(&host, document);
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 0
+ 0,
+ "the exact :has(:target) target is invalidated directly"
+ );
+ assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, target));
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ target,
+ "color",
+ None,
+ &inputs,
+ None,
+ ),
+ Some("rgb(0, 0, 255)".into())
);
}
#[test]
diff --git a/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs b/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs
index e76c3143c..19c599d16 100644
--- a/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs
+++ b/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs
@@ -60,6 +60,286 @@ fn computed_style_is_published_on_canonical_element_data_and_reused() {
);
}
+#[test]
+fn lazy_subtree_invalidation_avoids_eager_scans_and_memoizes_paths() {
+ const UNRELATED_COUNT: usize = 256;
+
+ let mut host = test_host();
+ let document = host.document_handle();
+ let affected_root = host.create_element("section");
+ let affected_leaf = host.create_element("span");
+ let affected_sibling = host.create_element("span");
+ let unrelated_root = host.create_element("main");
+ assert!(host.append_child(document, affected_root));
+ assert!(host.append_child(affected_root, affected_leaf));
+ assert!(host.append_child(affected_root, affected_sibling));
+ assert!(host.append_child(document, unrelated_root));
+ let unrelated = (0..UNRELATED_COUNT)
+ .map(|_| {
+ let element = host.create_element("i");
+ assert!(host.append_child(unrelated_root, element));
+ element
+ })
+ .collect::<Vec<_>>();
+
+ let mut engine = MoliStyleEngine::new();
+ let document_url = url::Url::parse("https://example.test/").unwrap();
+ let inputs = FullStyleWorldSnapshot::default();
+ for handle in [affected_leaf, affected_sibling]
+ .into_iter()
+ .chain(unrelated.iter().copied())
+ {
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ handle,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+ }
+ assert_eq!(
+ engine.computed_style_cache_entry_count_for_document_for_test(document),
+ UNRELATED_COUNT + 2
+ );
+
+ let path_visits_before =
+ engine.style_invalidation_path_node_visit_count_for_document_for_test(document);
+ engine.invalidate_style_subtree(&host, affected_root);
+ assert_eq!(
+ engine.style_invalidation_path_node_visit_count_for_document_for_test(document),
+ path_visits_before,
+ "recording an invalidation root must not inspect any published descendant"
+ );
+ assert_eq!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(document),
+ 1
+ );
+ assert!(engine.style_invalidation_generation_for_document_for_test(document) > 0);
+ assert_eq!(
+ engine.computed_style_cache_entry_count_for_document_for_test(document),
+ UNRELATED_COUNT + 2,
+ "all descendant publication entries remain untouched at mutation time"
+ );
+
+ let resolutions_before = engine.element_style_resolution_count_for_document_for_test(document);
+ for &handle in &unrelated {
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ handle,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+ }
+ assert_eq!(
+ engine.element_style_resolution_count_for_document_for_test(document),
+ resolutions_before,
+ "an unrelated branch must remain canonical"
+ );
+ let unrelated_path_visits = engine
+ .style_invalidation_path_node_visit_count_for_document_for_test(document)
+ .saturating_sub(path_visits_before);
+ assert!(
+ unrelated_path_visits <= (UNRELATED_COUNT as u64).saturating_mul(2).saturating_add(3),
+ "memoized parent breadcrumbs should make a sibling sweep linear; visited {unrelated_path_visits} nodes"
+ );
+
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ affected_leaf,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+ let resolutions_after_first_affected_read =
+ engine.element_style_resolution_count_for_document_for_test(document);
+ assert!(resolutions_after_first_affected_read > resolutions_before);
+ assert!(
+ engine
+ .computed_style_cache_contains_handle_for_document_for_test(document, affected_sibling),
+ "consuming one element must not enumerate or evict an unread sibling"
+ );
+ let visits_before_repeat =
+ engine.style_invalidation_path_node_visit_count_for_document_for_test(document);
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ affected_leaf,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+ assert_eq!(
+ engine.element_style_resolution_count_for_document_for_test(document),
+ resolutions_after_first_affected_read,
+ "a second clean observation must reuse the refreshed ElementData"
+ );
+ assert_eq!(
+ engine.style_invalidation_path_node_visit_count_for_document_for_test(document),
+ visits_before_repeat + 1,
+ "a fully memoized target requires one O(1) generation check"
+ );
+
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ affected_sibling,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+ assert!(
+ engine.element_style_resolution_count_for_document_for_test(document)
+ > resolutions_after_first_affected_read,
+ "the retained root history must independently validate an unread sibling"
+ );
+}
+
+#[test]
+fn repeated_lazy_invalidation_advances_past_previously_validated_elements() {
+ let mut host = test_host();
+ let document = host.document_handle();
+ let root = host.create_element("section");
+ let leaf = host.create_element("span");
+ assert!(host.append_child(document, root));
+ assert!(host.append_child(root, leaf));
+
+ let mut engine = MoliStyleEngine::new();
+ let document_url = url::Url::parse("https://example.test/").unwrap();
+ let inputs = FullStyleWorldSnapshot::default();
+ let read_leaf = |engine: &mut MoliStyleEngine| {
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ leaf,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+ };
+
+ read_leaf(&mut engine);
+ engine.invalidate_style_subtree(&host, root);
+ let first_generation = engine.style_invalidation_generation_for_document_for_test(document);
+ read_leaf(&mut engine);
+ let resolutions_after_first_generation =
+ engine.element_style_resolution_count_for_document_for_test(document);
+
+ engine.invalidate_style_subtree(&host, root);
+ assert!(
+ engine.style_invalidation_generation_for_document_for_test(document) > first_generation
+ );
+ read_leaf(&mut engine);
+ assert!(
+ engine.element_style_resolution_count_for_document_for_test(document)
+ > resolutions_after_first_generation,
+ "a new root generation must invalidate path stamps from the previous observation"
+ );
+}
+
+#[test]
+fn lazy_invalidated_deep_subtree_does_not_rewalk_validated_ancestors() {
+ const DEPTH: usize = 256;
+
+ let mut host = test_host();
+ let document = host.document_handle();
+ let root = host.create_element("section");
+ assert!(host.append_child(document, root));
+ let mut chain = vec![root];
+ let mut parent = root;
+ for _ in 1..DEPTH {
+ let child = host.create_element("div");
+ assert!(host.append_child(parent, child));
+ chain.push(child);
+ parent = child;
+ }
+
+ let mut engine = MoliStyleEngine::new();
+ let document_url = url::Url::parse("https://example.test/").unwrap();
+ let inputs = FullStyleWorldSnapshot::default();
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ parent,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+
+ engine.invalidate_style_subtree(&host, root);
+ let ancestor_visits_before =
+ engine.ancestor_style_validation_visit_count_for_document_for_test(document);
+ let resolutions_before = engine.element_style_resolution_count_for_document_for_test(document);
+ for &handle in &chain {
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ handle,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+ }
+
+ let ancestor_visits = engine
+ .ancestor_style_validation_visit_count_for_document_for_test(document)
+ .saturating_sub(ancestor_visits_before);
+ assert!(
+ ancestor_visits <= DEPTH as u64,
+ "parent-before-child observation should reuse the nearest validated breadcrumb; visited {ancestor_visits} ancestors"
+ );
+ assert_eq!(
+ engine
+ .element_style_resolution_count_for_document_for_test(document)
+ .saturating_sub(resolutions_before),
+ DEPTH as u64,
+ "every dirty element is recascaded exactly once"
+ );
+}
+
#[test]
fn primary_snapshot_carries_applicable_eager_pseudos_without_forcing_absent_ones() {
let mut host = test_host();
@@ -203,26 +483,23 @@ fn scoped_invalidation_marks_canonical_style_dirty_and_preserves_clean_elements(
}
#[test]
-fn inherited_ancestor_change_clears_descendant_cache_via_subtree_cleanup() {
+fn inherited_ancestor_change_lazily_refreshes_descendant_style() {
let mut host = test_host();
let document = host.document_handle();
- let style = host.create_element("style");
let ancestor = host.create_element("section");
let descendant = host.create_element("span");
let unrelated = host.create_element("aside");
- assert!(host.append_child(document, style));
+ let source_text = ".theme { color: rgb(1, 2, 3); }";
assert!(host.append_child(document, ancestor));
assert!(host.append_child(ancestor, descendant));
assert!(host.append_child(document, unrelated));
let mut engine = MoliStyleEngine::new();
- engine.set_owner_style_sheet_text_with_host(
- &host,
- style,
- ".theme { color: rgb(1, 2, 3); }".into(),
- );
let document_url = url::Url::parse("https://example.test/").unwrap();
- let inputs = FullStyleWorldSnapshot::default();
+ let source = StyloStylesheetSource::new(source_text.into(), document_url.clone());
+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source);
for handle in [descendant, unrelated] {
assert!(
engine
@@ -254,37 +531,80 @@ fn inherited_ancestor_change_clears_descendant_cache_via_subtree_cleanup() {
engine.invalidate_for_mutations(&host, &effects, &media);
engine.drain_pending_style_invalidations_for_document_for_test(&host, document);
+ assert!(
+ element_style_is_dirty_for_test(&engine, &host, ancestor),
+ "the directly matched ancestor keeps Stylo's precise restyle hint"
+ );
+ assert!(
+ !element_style_is_dirty_for_test(&engine, &host, descendant),
+ "the descendant is represented by the lazy dirty-root generation"
+ );
+ assert!(
+ engine.retained_style_invalidation_root_count_for_document_for_test(document) > 0,
+ "the finalized invalidation must publish a lazy subtree root"
+ );
+
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 2,
+ "subtree invalidation must not enumerate and evict published descendants"
);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, descendant),
- "inherited ancestor changes must clear descendant cache until direct-handle cleanup has a safety class"
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, descendant),
+ "the descendant remains published until it is observed"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, unrelated));
+ let resolutions_before = engine.element_style_resolution_count_for_document_for_test(document);
+ let descendant_color = engine.computed_style_property_value(
+ &host,
+ &document_url,
+ descendant,
+ "color",
+ None,
+ &inputs,
+ None,
+ );
+ assert!(
+ !element_style_is_dirty_for_test(&engine, &host, ancestor),
+ "observing the descendant must recascade its dirty ancestor first"
+ );
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ ancestor,
+ "color",
+ None,
+ &inputs,
+ None,
+ ),
+ Some("rgb(1, 2, 3)".into()),
+ "the ancestor recascade must publish the newly matched rule"
+ );
+ assert_eq!(descendant_color, Some("rgb(1, 2, 3)".into()));
+ assert!(
+ engine.element_style_resolution_count_for_document_for_test(document) > resolutions_before,
+ "the first descendant observation must consume the retained dirty root"
+ );
}
#[test]
-fn custom_property_ancestor_change_clears_descendant_cache_via_subtree_cleanup() {
+fn custom_property_ancestor_change_lazily_refreshes_descendant_style() {
let mut host = test_host();
let document = host.document_handle();
- let style = host.create_element("style");
let ancestor = host.create_element("section");
let descendant = host.create_element("span");
let unrelated = host.create_element("aside");
- assert!(host.append_child(document, style));
+ let source_text = ".theme { --accent: rgb(1, 2, 3); } span { color: var(--accent, black); }";
assert!(host.append_child(document, ancestor));
assert!(host.append_child(ancestor, descendant));
assert!(host.append_child(document, unrelated));
let mut engine = MoliStyleEngine::new();
- engine.set_owner_style_sheet_text_with_host(
- &host,
- style,
- ".theme { --accent: rgb(1, 2, 3); } span { color: var(--accent, black); }".into(),
- );
let document_url = url::Url::parse("https://example.test/").unwrap();
- let inputs = FullStyleWorldSnapshot::default();
+ let source = StyloStylesheetSource::new(source_text.into(), document_url.clone());
+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source);
for handle in [descendant, unrelated] {
assert!(
engine
@@ -318,36 +638,46 @@ fn custom_property_ancestor_change_clears_descendant_cache_via_subtree_cleanup()
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 2,
+ "subtree invalidation must not enumerate var() consumers"
);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, descendant),
- "custom-property ancestor changes must clear descendant var() consumers before direct-handle cleanup is safe"
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, descendant),
+ "the descendant remains published until it is observed"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, unrelated));
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ descendant,
+ "color",
+ None,
+ &inputs,
+ None,
+ ),
+ Some("rgb(1, 2, 3)".into())
+ );
}
#[test]
-fn non_inherited_exact_change_still_clears_descendant_cache_via_subtree_cleanup() {
+fn non_inherited_exact_change_lazily_recascades_descendant_conservatively() {
let mut host = test_host();
let document = host.document_handle();
- let style = host.create_element("style");
let ancestor = host.create_element("section");
let descendant = host.create_element("span");
let unrelated = host.create_element("aside");
- assert!(host.append_child(document, style));
+ let source_text = ".theme { background-color: rgb(1, 2, 3); }";
assert!(host.append_child(document, ancestor));
assert!(host.append_child(ancestor, descendant));
assert!(host.append_child(document, unrelated));
let mut engine = MoliStyleEngine::new();
- engine.set_owner_style_sheet_text_with_host(
- &host,
- style,
- ".theme { background-color: rgb(1, 2, 3); }".into(),
- );
let document_url = url::Url::parse("https://example.test/").unwrap();
- let inputs = FullStyleWorldSnapshot::default();
+ let source = StyloStylesheetSource::new(source_text.into(), document_url.clone());
+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source);
for handle in [descendant, unrelated] {
assert!(
engine
@@ -367,6 +697,8 @@ fn non_inherited_exact_change_still_clears_descendant_cache_via_subtree_cleanup(
engine.computed_style_cache_entry_count_for_document_for_test(document),
2
);
+ let descendant_before = retained_primary_style_for_test(&engine, &host, descendant)
+ .expect("descendant style should be retained");
assert!(host.set_attribute(ancestor, "class", "theme"));
let effects = [StyleMutationEffect::Attribute {
@@ -381,39 +713,56 @@ fn non_inherited_exact_change_still_clears_descendant_cache_via_subtree_cleanup(
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 2,
+ "subtree invalidation must not enumerate published descendants"
);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, descendant),
- "even non-inherited exact-looking changes currently clear descendant cache until SelfOnly direct-handle cleanup exists"
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, descendant),
+ "the conservative descendant recascade is deferred until observation"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, unrelated));
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ descendant,
+ "background-color",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
+ let descendant_after = retained_primary_style_for_test(&engine, &host, descendant)
+ .expect("observed descendant style should be republished");
+ assert!(
+ !ServoArc::ptr_eq(&descendant_before, &descendant_after),
+ "the lazy subtree contract remains inheritance-safe even for a non-inherited change"
+ );
}
#[test]
-fn shadow_host_inherited_change_clears_shadow_descendant_cache_via_subtree_cleanup() {
+fn shadow_host_inherited_change_lazily_refreshes_shadow_descendant() {
let mut host = test_host();
let document = host.document_handle();
- let style = host.create_element("style");
let shadow_host = host.create_element("section");
let shadow_root = host
.attach_shadow_root(shadow_host, "open")
.expect("section should host a shadow root");
let shadow_child = host.create_element("span");
let unrelated = host.create_element("aside");
- assert!(host.append_child(document, style));
+ let source_text = ".theme { color: rgb(1, 2, 3); }";
assert!(host.append_child(document, shadow_host));
assert!(host.append_child(shadow_root, shadow_child));
assert!(host.append_child(document, unrelated));
let mut engine = MoliStyleEngine::new();
- engine.set_owner_style_sheet_text_with_host(
- &host,
- style,
- ".theme { color: rgb(1, 2, 3); }".into(),
- );
let document_url = url::Url::parse("https://example.test/").unwrap();
- let inputs = FullStyleWorldSnapshot::default();
+ let source = StyloStylesheetSource::new(source_text.into(), document_url.clone());
+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source);
for handle in [shadow_child, unrelated] {
assert!(
engine
@@ -447,36 +796,46 @@ fn shadow_host_inherited_change_clears_shadow_descendant_cache_via_subtree_clean
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 2,
+ "shadow descendants must not be enumerated during invalidation"
);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child),
- "inherited host changes must clear shadow descendant cache before direct-handle cleanup is safe"
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child),
+ "the shadow descendant remains published until observed"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, unrelated));
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ shadow_child,
+ "color",
+ None,
+ &inputs,
+ None,
+ ),
+ Some("rgb(1, 2, 3)".into())
+ );
}
#[test]
-fn lazy_pseudo_inherited_change_clears_pseudo_cache_via_subtree_cleanup() {
+fn lazy_pseudo_inherited_change_is_evicted_when_owner_is_observed() {
let mut host = test_host();
let document = host.document_handle();
- let style = host.create_element("style");
let ancestor = host.create_element("section");
let list_item = host.create_element("li");
let unrelated = host.create_element("aside");
- assert!(host.append_child(document, style));
+ let source_text =
+ ".theme { color: rgb(1, 2, 3); } li { display: list-item; } li::marker { color: inherit; }";
assert!(host.append_child(document, ancestor));
assert!(host.append_child(ancestor, list_item));
assert!(host.append_child(document, unrelated));
let mut engine = MoliStyleEngine::new();
- engine.set_owner_style_sheet_text_with_host(
- &host,
- style,
- ".theme { color: rgb(1, 2, 3); } li { display: list-item; } li::marker { color: inherit; }"
- .into(),
- );
let document_url = url::Url::parse("https://example.test/").unwrap();
- let inputs = FullStyleWorldSnapshot::default();
+ let source = StyloStylesheetSource::new(source_text.into(), document_url.clone());
+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source);
assert!(
engine
.computed_style_property_value(
@@ -531,16 +890,17 @@ fn lazy_pseudo_inherited_change_clears_pseudo_cache_via_subtree_cleanup() {
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 3,
+ "mutation-time invalidation must retain the descendant pseudo sidecar"
);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, list_item),
- "inherited ancestor changes must clear lazy pseudo cache entries keyed by descendant handles"
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, list_item),
+ "the owner and pseudo are evicted together only when the owner is demanded"
);
assert_eq!(
engine
.computed_style_cache_entry_count_for_handle_for_document_for_test(document, list_item),
- 0
+ 2
);
assert_eq!(
engine
@@ -548,30 +908,44 @@ fn lazy_pseudo_inherited_change_clears_pseudo_cache_via_subtree_cleanup() {
1
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, unrelated));
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ list_item,
+ "color",
+ Some("marker"),
+ &inputs,
+ None,
+ ),
+ Some("rgb(1, 2, 3)".into())
+ );
+ assert_eq!(
+ engine
+ .computed_style_cache_entry_count_for_handle_for_document_for_test(document, list_item),
+ 2,
+ "the refreshed primary and pseudo must be republished"
+ );
}
#[test]
-fn lazy_pseudo_custom_property_change_clears_pseudo_cache_via_subtree_cleanup() {
+fn lazy_pseudo_custom_property_change_is_evicted_when_owner_is_observed() {
let mut host = test_host();
let document = host.document_handle();
- let style = host.create_element("style");
let ancestor = host.create_element("section");
let list_item = host.create_element("li");
let unrelated = host.create_element("aside");
- assert!(host.append_child(document, style));
+ let source_text = ".theme { --marker-color: rgb(1, 2, 3); } li { display: list-item; } li::marker { color: var(--marker-color, black); }";
assert!(host.append_child(document, ancestor));
assert!(host.append_child(ancestor, list_item));
assert!(host.append_child(document, unrelated));
let mut engine = MoliStyleEngine::new();
- engine.set_owner_style_sheet_text_with_host(
- &host,
- style,
- ".theme { --marker-color: rgb(1, 2, 3); } li { display: list-item; } li::marker { color: var(--marker-color, black); }"
- .into(),
- );
let document_url = url::Url::parse("https://example.test/").unwrap();
- let inputs = FullStyleWorldSnapshot::default();
+ let source = StyloStylesheetSource::new(source_text.into(), document_url.clone());
+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);
+ let mut inputs = FullStyleWorldSnapshot::default();
+ inputs.document_stylesheet_sources.push(source);
assert!(
engine
.computed_style_property_value(
@@ -626,16 +1000,17 @@ fn lazy_pseudo_custom_property_change_clears_pseudo_cache_via_subtree_cleanup()
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 1
+ 3,
+ "mutation-time invalidation must retain the descendant pseudo sidecar"
);
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, list_item),
- "custom-property ancestor changes must clear lazy pseudo var() consumers before direct-handle cleanup is safe"
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, list_item),
+ "the pseudo var() consumer remains published until its owner is demanded"
);
assert_eq!(
engine
.computed_style_cache_entry_count_for_handle_for_document_for_test(document, list_item),
- 0
+ 2
);
assert_eq!(
engine
@@ -643,6 +1018,18 @@ fn lazy_pseudo_custom_property_change_clears_pseudo_cache_via_subtree_cleanup()
1
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, unrelated));
+ assert_eq!(
+ engine.computed_style_property_value(
+ &host,
+ &document_url,
+ list_item,
+ "color",
+ Some("marker"),
+ &inputs,
+ None,
+ ),
+ Some("rgb(1, 2, 3)".into())
+ );
}
#[test]
@@ -701,11 +1088,12 @@ fn source_local_fallback_roots_preserve_unrelated_document_cache_for_shadow_sour
assert_eq!(
engine.computed_style_cache_entry_count_for_document_for_test(document),
- 2
+ 3,
+ "a scoped fallback records roots instead of enumerating published descendants"
);
assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));
assert!(
- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)
+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)
);
assert!(
engine.computed_style_cache_contains_handle_for_document_for_test(
@@ -713,6 +1101,19 @@ fn source_local_fallback_roots_preserve_unrelated_document_cache_for_shadow_sour
sibling_shadow_child
)
);
+ assert!(
+ engine
+ .computed_style_property_value(
+ &host,
+ &document_url,
+ shadow_child,
+ "display",
+ None,
+ &inputs,
+ None,
+ )
+ .is_some()
+ );
}
#[test]
@@ -5273,11 +5674,15 @@ fn document_stylesheet_change_updates_the_retained_system_in_place() {
ServoArc::ptr_eq(&unrelated_style_before, &unrelated_style_after),
"Stylo stylesheet invalidation must preserve an unrelated source's canonical style"
);
- assert!(element_style_is_dirty_for_test(
- &engine,
- &host,
- inherited_child
- ));
+ assert!(
+ !element_style_is_dirty_for_test(&engine, &host, inherited_child),
+ "the inherited child remains published; its dirty-root generation is consumed on demand"
+ );
+ assert!(
+ engine
+ .computed_style_cache_contains_handle_for_document_for_test(document, inherited_child),
+ "a target read must not enumerate and evict its unobserved descendants"
+ );
assert_eq!(
engine.computed_style_property_value(
&host,
diff --git a/moli-renderer-v8/src/style_engine/world_lifecycle.rs b/moli-renderer-v8/src/style_engine/world_lifecycle.rs
index 6c8d0fe10..a0603a33e 100644
--- a/moli-renderer-v8/src/style_engine/world_lifecycle.rs
+++ b/moli-renderer-v8/src/style_engine/world_lifecycle.rs
@@ -2,6 +2,7 @@
use crate::{document_runtime::DomHandle, dom::native::DomHost};
+use indexmap::IndexSet;
use moli_selector::StyloDomStyleAdapter;
use style::context::QuirksMode;
@@ -302,6 +303,7 @@ fn apply_retained_stylesheet_invalidations(
viewport_size_changed,
used_color_scheme_changed,
} = invalidations;
+ let mut stylesheet_invalidation_roots = IndexSet::new();
if let Some(invalidations) = document_invalidations {
// HTML documents normally have one document element. The native DOM
// also permits fragment-like test documents with several top-level
@@ -319,7 +321,11 @@ fn apply_retained_stylesheet_invalidations(
{
roots.push(root);
}
- dom_adapter.process_stylesheet_invalidations(host, &roots, &invalidations);
+ stylesheet_invalidation_roots.extend(dom_adapter.process_stylesheet_invalidations(
+ host,
+ &roots,
+ &invalidations,
+ ));
}
for (shadow_root, invalidations) in shadow_scopes {
let mut roots = host
@@ -332,15 +338,23 @@ fn apply_retained_stylesheet_invalidations(
if let Some(shadow_host) = host.shadow_root_host(shadow_root) {
roots.push(shadow_host);
}
- dom_adapter.process_stylesheet_invalidations(host, &roots, &invalidations);
+ stylesheet_invalidation_roots.extend(dom_adapter.process_stylesheet_invalidations(
+ host,
+ &roots,
+ &invalidations,
+ ));
}
if viewport_size_changed {
- invalidate_viewport_unit_styles(host, dom_adapter, document);
+ stylesheet_invalidation_roots.extend(invalidate_viewport_unit_styles(
+ host,
+ dom_adapter,
+ document,
+ ));
}
if used_color_scheme_changed {
cache_cleanup.invalidate_subtrees(host, [document]);
}
- cache_cleanup.invalidate_stylesheet_dirty_subtrees(host);
+ cache_cleanup.retain_stylesheet_invalidation_roots(host, stylesheet_invalidation_roots);
if document_scope_fallback {
cache_cleanup.invalidate_subtrees(host, [document]);
}
@@ -356,7 +370,7 @@ fn invalidate_viewport_unit_styles(
host: &DomHost,
dom_adapter: &StyloDomStyleAdapter,
document: DomHandle,
-) {
+) -> Vec<DomHandle> {
let mut roots = host
.child_handles(document)
.filter(|handle| {
@@ -374,11 +388,16 @@ fn invalidate_viewport_unit_styles(
.is_some_and(|node| node.as_element().is_some())
}));
}
- dom_adapter.with_bound_host(host, |binding| {
- for root in roots {
- if let Some(root) = binding.element(host, root) {
- style::invalidation::viewport_units::invalidate(root);
- }
- }
+ let changed_roots = dom_adapter.with_bound_host(host, |binding| {
+ roots
+ .iter()
+ .copied()
+ .filter(|root| {
+ binding
+ .element(host, *root)
+ .is_some_and(style::invalidation::viewport_units::invalidate)
+ })
+ .collect::<Vec<_>>()
});
+ dom_adapter.collect_dirty_style_roots(host, &changed_roots)
}
diff --git a/moli-renderer-v8/src/window_host.rs b/moli-renderer-v8/src/window_host.rs
index 218201356..3ef1b8b38 100644
--- a/moli-renderer-v8/src/window_host.rs
+++ b/moli-renderer-v8/src/window_host.rs
@@ -1138,6 +1138,9 @@ pub(crate) fn build_computed_style_object<'s>(
let host_ref = unsafe { &*host_ptr };
let target_context =
computed_style_target_context(scope, host_ref, handle, child_window_handle);
+ if target_context.returns_empty_style() {
+ host_ref.retire_computed_style_for_inactive_handle(handle);
+ }
let cached_target_empty = match target_context {
ComputedStyleTargetContext::ChildFrameDocument { .. } => {
Some(target_context.returns_empty_style())
diff --git a/moli-selector/src/stylo/style_traversal.rs b/moli-selector/src/stylo/style_traversal.rs
index 967eef7ad..27dfd8eeb 100644
--- a/moli-selector/src/stylo/style_traversal.rs
+++ b/moli-selector/src/stylo/style_traversal.rs
@@ -71,6 +71,13 @@ struct StyloElementDocumentDataStore {
data: HashMap<NodeId, Box<ElementDataWrapper>>,
inline_styles: HashMap<NodeId, Arc<Locked<PropertyDeclarationBlock>>>,
selector_flags: HashMap<NodeId, ElementSelectorFlags>,
+ /// Stylo's equivalent of Blink's `ChildNeedsStyleInvalidation` breadcrumb.
+ ///
+ /// Stylesheet invalidation already calls `TElement::set_dirty_descendants`
+ /// while unwinding from a matched descendant. Keeping that bit in the
+ /// document side table lets Moli follow only dirty branches later instead
+ /// of rediscovering them by scanning every published `ElementData` entry.
+ dirty_descendants: HashSet<NodeId>,
}
#[derive(Default)]
@@ -196,30 +203,33 @@ impl StyloDomStyleAdapter {
.clear_inline_style_attributes_for_document(document);
}
- pub fn element_style_value_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
- self.state
- .element_style_value_handles_for_document(document)
- }
-
- pub fn dirty_element_style_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
- self.state
- .dirty_element_style_handles_for_document(document)
- }
-
pub fn process_stylesheet_invalidations(
&self,
host: &DomHost,
roots: &[NodeId],
invalidations: &StylesheetInvalidationSet,
- ) -> bool {
+ ) -> Vec<NodeId> {
self.with_bound_host(host, |binding| {
- let mut changed = false;
+ let mut changed_roots = Vec::new();
for root in roots.iter().filter_map(|root| binding.element(host, *root)) {
// Every root belongs to an independent Document/ShadowRoot
// scope and must be processed even after an earlier match.
- changed |= invalidations.process_style(root, None);
+ if invalidations.process_style(root, None) {
+ changed_roots.push(root);
+ }
}
- changed
+ collect_dirty_style_roots(changed_roots)
+ })
+ }
+
+ /// Collects the top-most dirty elements by following Stylo's retained
+ /// dirty-descendant breadcrumbs from the supplied scope roots.
+ ///
+ /// This is deliberately proportional to dirty branches. It replaces the
+ /// old document-wide scan over every published `ElementData` entry.
+ pub fn collect_dirty_style_roots(&self, host: &DomHost, roots: &[NodeId]) -> Vec<NodeId> {
+ self.with_bound_host(host, |binding| {
+ collect_dirty_style_roots(roots.iter().filter_map(|root| binding.element(host, *root)))
})
}
@@ -284,6 +294,55 @@ impl StyloDomStyleAdapter {
}
}
+fn collect_dirty_style_roots<'a>(roots: impl IntoIterator<Item = StyleElement<'a>>) -> Vec<NodeId> {
+ fn collect_from_element(
+ element: StyleElement<'_>,
+ roots: &mut Vec<NodeId>,
+ seen: &mut HashSet<NodeId>,
+ covered_by_dirty_ancestor: bool,
+ ) {
+ let handle = element.handle();
+ if !seen.insert(handle) {
+ return;
+ }
+
+ let self_is_dirty = element
+ .borrow_data()
+ .is_some_and(|data| !data.hint.is_empty());
+ let descendants_are_dirty = element.has_dirty_descendants();
+ if self_is_dirty {
+ // Moli resolves demanded elements one at a time. Treating a dirty
+ // element as a lazy subtree root conservatively carries inherited
+ // changes to any descendant resolved after it.
+ if !covered_by_dirty_ancestor {
+ roots.push(handle);
+ }
+ }
+
+ if !descendants_are_dirty {
+ return;
+ }
+ for child in element.traversal_children() {
+ if let Some(child) = child.as_element() {
+ collect_from_element(
+ child,
+ roots,
+ seen,
+ covered_by_dirty_ancestor || self_is_dirty,
+ );
+ }
+ }
+ unsafe { element.unset_dirty_descendants() };
+ }
+
+ let mut dirty_roots = Vec::new();
+ let mut seen = HashSet::new();
+ for root in roots {
+ collect_from_element(root, &mut dirty_roots, &mut seen, false);
+ }
+ dirty_roots
+}
+
impl<'binding> StyleDomHostBinding<'binding> {
pub fn shared_lock(&self) -> &SharedRwLock {
&self.state.shared_lock
@@ -352,16 +411,6 @@ impl<'binding> StyleDomHostBinding<'binding> {
.clear_inline_style_attributes_for_document(document);
}
- pub fn element_style_value_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
- self.state
- .element_style_value_handles_for_document(document)
- }
-
- pub fn dirty_element_style_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
- self.state
- .dirty_element_style_handles_for_document(document)
- }
-
pub fn element_selector_flag_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
self.state
.element_selector_flag_handles_for_document(document)
@@ -447,18 +496,24 @@ impl StyloElementDataStore {
let mut moved_data = None;
let mut moved_inline_style = None;
let mut moved_selector_flags = None;
+ let mut moved_dirty_descendants = false;
let mut previous_is_empty = false;
if let Some(previous_bucket) = documents.get_mut(&previous) {
moved_data = previous_bucket.data.remove(&handle);
moved_inline_style = previous_bucket.inline_styles.remove(&handle);
moved_selector_flags = previous_bucket.selector_flags.remove(&handle);
+ moved_dirty_descendants = previous_bucket.dirty_descendants.remove(&handle);
previous_is_empty = previous_bucket.is_empty();
}
if previous_is_empty {
documents.remove(&previous);
}
- if moved_data.is_none() && moved_inline_style.is_none() && moved_selector_flags.is_none() {
+ if moved_data.is_none()
+ && moved_inline_style.is_none()
+ && moved_selector_flags.is_none()
+ && !moved_dirty_descendants
+ {
return;
}
@@ -472,6 +527,9 @@ impl StyloElementDataStore {
if let Some(selector_flags) = moved_selector_flags {
bucket.selector_flags.insert(handle, selector_flags);
}
+ if moved_dirty_descendants {
+ bucket.dirty_descendants.insert(handle);
+ }
}
pub(super) fn ensure_for_host(&self, host: &DomHost, handle: NodeId) -> ElementDataMut<'_> {
@@ -571,10 +629,12 @@ impl StyloElementDataStore {
.data
.keys()
.chain(bucket.selector_flags.keys())
+ .chain(bucket.dirty_descendants.iter())
.copied()
.collect::<HashSet<_>>();
bucket.data.clear();
bucket.selector_flags.clear();
+ bucket.dirty_descendants.clear();
let orphaned_handles = affected_handles
.into_iter()
.filter(|handle| {
@@ -760,39 +820,35 @@ impl StyloElementDataStore {
self.remove_owner_mappings_for_document(document, orphaned_handles);
}
- fn style_value_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
- let documents = self.documents.borrow();
- let Some(bucket) = documents.get(&document) else {
- return Vec::new();
- };
- let mut handles = HashSet::with_capacity(bucket.data.len() + bucket.inline_styles.len());
- handles.extend(bucket.data.keys().copied());
- handles.extend(bucket.inline_styles.keys().copied());
- handles.into_iter().collect()
- }
-
- fn dirty_style_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
+ fn selector_flag_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
self.documents
.borrow()
.get(&document)
- .map(|bucket| {
- bucket
- .data
- .iter()
- .filter_map(|(handle, data)| {
- (!data.borrow().hint.is_empty()).then_some(*handle)
- })
- .collect()
- })
+ .map(|bucket| bucket.selector_flags.keys().copied().collect())
.unwrap_or_default()
}
- fn selector_flag_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
+ fn has_dirty_descendants_for_document(&self, document: NodeId, handle: NodeId) -> bool {
self.documents
.borrow()
.get(&document)
- .map(|bucket| bucket.selector_flags.keys().copied().collect())
- .unwrap_or_default()
+ .is_some_and(|bucket| bucket.dirty_descendants.contains(&handle))
+ }
+
+ fn set_dirty_descendants_for_document(&self, document: NodeId, handle: NodeId) {
+ self.note_owner_document(handle, document);
+ self.documents
+ .borrow_mut()
+ .entry(document)
+ .or_default()
+ .dirty_descendants
+ .insert(handle);
+ }
+
+ fn unset_dirty_descendants_for_document(&self, document: NodeId, handle: NodeId) {
+ self.remove_from_document(document, handle, |bucket| {
+ bucket.dirty_descendants.remove(&handle);
+ });
}
fn clear_inline_style(&self, handle: NodeId) {
@@ -1073,13 +1129,17 @@ impl StyloElementDataStore {
impl StyloElementDocumentDataStore {
fn is_empty(&self) -> bool {
- self.data.is_empty() && self.inline_styles.is_empty() && self.selector_flags.is_empty()
+ self.data.is_empty()
+ && self.inline_styles.is_empty()
+ && self.selector_flags.is_empty()
+ && self.dirty_descendants.is_empty()
}
fn contains_handle(&self, handle: NodeId) -> bool {
self.data.contains_key(&handle)
|| self.inline_styles.contains_key(&handle)
|| self.selector_flags.contains_key(&handle)
+ || self.dirty_descendants.contains(&handle)
}
}
@@ -1109,6 +1169,13 @@ impl fmt::Debug for StyloElementDataStore {
.map(|bucket| bucket.selector_flags.len())
.sum::<usize>(),
)
+ .field(
+ "dirty_descendants_len",
+ &documents
+ .values()
+ .map(|bucket| bucket.dirty_descendants.len())
+ .sum::<usize>(),
+ )
.finish()
}
}
@@ -1376,14 +1443,6 @@ impl StyleDomState {
self.element_data.clear_inline_styles_for_document(document);
}
- fn element_style_value_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
- self.element_data.style_value_handles_for_document(document)
- }
-
- fn dirty_element_style_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
- self.element_data.dirty_style_handles_for_document(document)
- }
-
fn element_selector_flag_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {
self.element_data
.selector_flag_handles_for_document(document)
@@ -1985,7 +2044,9 @@ impl<'a> TElement for StyleElement<'a> {
}
fn has_dirty_descendants(&self) -> bool {
- false
+ self.style_state()
+ .element_data
+ .has_dirty_descendants_for_document(self.document(), self.handle())
}
fn has_snapshot(&self) -> bool {
@@ -1998,9 +2059,17 @@ impl<'a> TElement for StyleElement<'a> {
unsafe fn set_handled_snapshot(&self) {}
- unsafe fn set_dirty_descendants(&self) {}
+ unsafe fn set_dirty_descendants(&self) {
+ self.style_state()
+ .element_data
+ .set_dirty_descendants_for_document(self.document(), self.handle());
+ }
- unsafe fn unset_dirty_descendants(&self) {}
+ unsafe fn unset_dirty_descendants(&self) {
+ self.style_state()
+ .element_data
+ .unset_dirty_descendants_for_document(self.document(), self.handle());
+ }
fn store_children_to_process(&self, _n: isize) {}
@@ -2446,6 +2515,27 @@ mod element_data_store_tests {
assert!(store.documents.borrow().is_empty());
}
+ #[test]
+ fn dirty_descendant_breadcrumb_moves_and_retires_with_its_owner() {
+ let store = StyloElementDataStore::default();
+ let old_document = NodeId::new(0);
+ let new_document = NodeId::new(1);
+ let handle = NodeId::new(2);
+
+ store.set_dirty_descendants_for_document(old_document, handle);
+ assert!(store.has_dirty_descendants_for_document(old_document, handle));
+ assert_eq!(store.document_for_handle(handle), Some(old_document));
+
+ store.note_owner_document(handle, new_document);
+ assert!(!store.has_dirty_descendants_for_document(old_document, handle));
+ assert!(store.has_dirty_descendants_for_document(new_document, handle));
+ assert_eq!(store.document_for_handle(handle), Some(new_document));
+
+ store.unset_dirty_descendants_for_document(new_document, handle);
+ assert_eq!(store.document_for_handle(handle), None);
+ assert!(store.documents.borrow().is_empty());
+ }
+
#[test]
fn document_bulk_cleanup_updates_only_affected_owner_entries() {
let store = StyloElementDataStore::default();