Truly independent web browser
LibWeb: Restyle only elements that read a changed custom property
Tim Ledbetter10e408f3587d
diff --git a/Libraries/LibWeb/CSS/UpdateStyle.cpp b/Libraries/LibWeb/CSS/UpdateStyle.cppindex 80f3dc17c34..759424ee245 100644--- a/Libraries/LibWeb/CSS/UpdateStyle.cpp+++ b/Libraries/LibWeb/CSS/UpdateStyle.cpp@@ -359,17 +359,22 @@ static void move_pseudo_element_environments(Layout::BegunRead const& read, DOM:}}-// An element's custom properties moved from `old_base` to `new_base`: the style engine moves what the element's+// An element's custom properties moved from `old_data` to `new_data`: the style engine moves what the element's// descendants inherit, and calls back for what the move leaves the host.-static void move_custom_property_environment_below(StyleReactionApplication& application, DOM::Element& element, RefPtr<CustomPropertyData const> const& old_base, RefPtr<CustomPropertyData const> const& new_base)+static void move_custom_property_environment_below(StyleReactionApplication& application, DOM::Element& element, RefPtr<CustomPropertyData const> const& old_data, RefPtr<CustomPropertyData const> const& new_data){auto const& read = application.read;auto& document = *application.document;- auto old_inheritable = old_base ? old_base->inheritable(read, document) : nullptr;- auto new_inheritable = new_base ? new_base->inheritable(read, document) : nullptr;+ auto old_inheritable = old_data ? old_data->inheritable(read, document) : nullptr;+ auto new_inheritable = new_data ? new_data->inheritable(read, document) : nullptr;+ auto named = [](CustomPropertyData const* data) -> StyleEngineFFI::FfiNamedEnvironment {+ return { .identity = data ? data->identity() : 0, .store = data ? data->rust_store() : nullptr };+ };StyleEngineFFI::FfiEnvironmentMove const moved {+ .old_environment = named(old_data.ptr()),+ .new_environment = named(new_data.ptr()),.old_inheritable = old_inheritable ? old_inheritable->identity() : 0,- .new_inheritable = { .identity = new_inheritable ? new_inheritable->identity() : 0, .store = new_inheritable ? new_inheritable->rust_store() : nullptr },+ .new_inheritable = named(new_inheritable.ptr()),.new_inheritable_data = new_inheritable.ptr(),.new_inheritable_declares = new_inheritable && new_inheritable->declared_count() > 0,};@@ -433,9 +438,7 @@ static void propagate_custom_property_environment_move(StyleReactionApplication&// Nothing inherits from an element with nothing below it in the flat tree.if (!origin.first_element_child() && !origin.shadow_root() && !is<HTML::HTMLSlotElement>(origin))return;- auto old_origin_base = custom_property_environment_base(origin, move(old_origin_data));- auto new_origin_base = custom_property_environment_base(origin, origin.custom_property_data({}));- move_custom_property_environment_below(application, origin, old_origin_base, new_origin_base);+ move_custom_property_environment_below(application, origin, old_origin_data, origin.custom_property_data({}));}// Install the record the engine settled for a row, and the pseudo-element records beside it. A C++ computation applieddiff --git a/Libraries/LibWeb/Rust/src/css/custom_properties.rs b/Libraries/LibWeb/Rust/src/css/custom_properties.rsindex 21a2940a2d3..0655e038360 100644--- a/Libraries/LibWeb/Rust/src/css/custom_properties.rs+++ b/Libraries/LibWeb/Rust/src/css/custom_properties.rs@@ -600,6 +600,10 @@ impl CustomPropertyStore {Self::animation_overlay(animated, base)}+ pub(crate) fn parent(&self) -> Option<&Arc<CustomPropertyStore>> {+ self.parent.as_ref()+ }+pub(crate) fn get(&self, name_raw: usize) -> Option<&CustomPropertyEntry> {self.own_values.get(&name_raw)diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge.rs b/Libraries/LibWeb/Rust/src/css/style/bridge.rsindex 8171780a316..0facefa6844 100644--- a/Libraries/LibWeb/Rust/src/css/style/bridge.rs+++ b/Libraries/LibWeb/Rust/src/css/style/bridge.rs@@ -2484,6 +2484,8 @@ pub struct FfiNamedEnvironment {#[derive(Clone, Copy)]#[repr(C)]pub struct FfiEnvironmentMove {+ pub old_environment: FfiNamedEnvironment,+ pub new_environment: FfiNamedEnvironment,pub old_inheritable: u64,pub new_inheritable: FfiNamedEnvironment,pub new_inheritable_data: *const c_void,diff --git a/Libraries/LibWeb/Rust/src/css/style/cascade.rs b/Libraries/LibWeb/Rust/src/css/style/cascade.rsindex acedf7e1d6b..e15632af8c0 100644--- a/Libraries/LibWeb/Rust/src/css/style/cascade.rs+++ b/Libraries/LibWeb/Rust/src/css/style/cascade.rs@@ -28,6 +28,7 @@ use super::column::Column;use super::column::PagedColumn;use super::column::PagedColumnPage;use super::column::RemovablePagedColumnPage;+use super::custom_property_cascade::CustomPropertyNames;use super::fast_hash::FastMap as HashMap;use super::fast_hash::fast_hasher;use super::intern_table::InternIdentity;@@ -37,6 +38,7 @@ use super::intern_table::content_hash;use smallvec::SmallVec;use std::hash::Hash;use std::hash::Hasher;+use std::sync::OnceLock;use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};use crate::css::cascaded_properties::CascadeOrigin;@@ -1458,6 +1460,8 @@ pub struct WinnerGroups {/// Each state's [`StateSummary`], packed, decided the first time it is asked where every winner's written value was/// found, and `STATE_SUMMARY_DECIDED` from then on.state_summaries: Vec<crate::fork::ForkCopied<AtomicU64>>,+ /// The custom properties each state's winners read through `var()`. `None` when they cannot be listed.+ state_custom_property_reads: Vec<OnceLock<Option<CustomPropertyNames>>>,groups: InternTable<WinnerGroupID, Box<[SemanticPropertyWinner]>>,provenance_groups: InternTable<WinnerProvenanceGroupID, Box<[WinnerProvenance]>>,priorities: InternTable<CascadePriorityID, CascadePriority>,@@ -1526,6 +1530,7 @@ impl Default for WinnerGroups {state_winning_rules: Vec::new(),state_reads: Vec::new(),state_summaries: Vec::new(),+ state_custom_property_reads: Vec::new(),groups: InternTable::default(),provenance_groups: InternTable::default(),priorities: InternTable::default(),@@ -1582,6 +1587,7 @@ impl WinnerGroups {.iter().map(|summary| crate::fork::ForkCopied::new(AtomicU64::new(summary.load(Ordering::Relaxed)))).collect(),+ state_custom_property_reads: self.state_custom_property_reads.clone(),groups: self.groups.clone(),provenance_groups: self.provenance_groups.clone(),priorities: self.priorities.clone(),@@ -1792,6 +1798,7 @@ impl WinnerGroups {self.state_reads.push(crate::fork::ForkCopied::new(AtomicU8::new(0)));self.state_summaries.push(crate::fork::ForkCopied::new(AtomicU64::new(0)));+ self.state_custom_property_reads.push(OnceLock::new());id}@@ -2095,6 +2102,17 @@ impl WinnerGroups {}}+ pub(super) fn state_custom_property_reads(+ &self,+ state: CascadeStateID,+ decide: impl FnOnce() -> Option<CustomPropertyNames>,+ ) -> Option<CustomPropertyNames> {+ match self.state_custom_property_reads.get(state.0 as usize) {+ Some(slot) => slot.get_or_init(decide).clone(),+ None => decide(),+ }+ }+pub(super) fn winner_count_in_state(&self, state: CascadeStateID) -> usize {self.states[state].iter()@@ -2636,6 +2654,7 @@ impl WinnerGroups {self.state_winning_rules = Vec::new();self.state_reads = Vec::new();self.state_summaries = Vec::new();+ self.state_custom_property_reads = Vec::new();self.groups = InternTable::default();self.provenance_groups = InternTable::default();self.priorities = InternTable::default();diff --git a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rsindex 8a37f7c5716..72c72a48998 100644--- a/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs+++ b/Libraries/LibWeb/Rust/src/css/style/custom_property_cascade.rs@@ -31,7 +31,9 @@ use crate::css::custom_properties::{use crate::css::parser::component_value::{ComponentKind, ComponentValue};use crate::css::parser::value_parser::ParseOutcome;use crate::css::rule::CompiledFunction;-use crate::css::style_value::{RetainedStyleValueData, StyleValueData, utf16_equals_ascii_case_insensitive};+use crate::css::style_value::{+ RetainedStyleValueData, StyleValueData, custom_property_references, utf16_equals_ascii_case_insensitive,+};use custom_property_environments::{CascadedCustomProperty, CustomPropertyName};/// The document's media features as the style update a transaction belongs to saw them, which@@ -384,6 +386,33 @@ fn substituted_tokens(value: &StyleValueData) -> &StyleValueData {}}+/// Custom property names, sorted and without duplicates.+pub(crate) type CustomPropertyNames = Arc<[Arc<[u16]>]>;++pub(super) fn append_custom_property_reads(value: &StyleValueData, names: &mut Vec<Arc<[u16]>>) -> bool {+ let Some((references, all_references_visible)) = custom_property_references(substituted_tokens(value)) else {+ return true;+ };+ names.extend(references.into_iter().map(Arc::from));+ all_references_visible+}++pub(super) fn value_reads_any_of_custom_properties(value: &StyleValueData, names: &[Arc<[u16]>]) -> bool {+ let Some((references, all_references_visible)) = custom_property_references(substituted_tokens(value)) else {+ return false;+ };+ !all_references_visible+ || references+ .into_iter()+ .any(|reference| names.binary_search_by(|name| name.as_ref().cmp(reference)).is_ok())+}++pub(super) fn sorted_custom_property_names(mut names: Vec<Arc<[u16]>>) -> CustomPropertyNames {+ names.sort_unstable();+ names.dedup();+ names.into()+}+/// Whether a written value substitutes `attr()`, which reads the element's attributes.pub(super) fn value_reads_attributes(value: &StyleValueData) -> bool {matches!(@@ -756,6 +785,34 @@ impl RetainedState {self.state_has_substitutions(node, state)}+ pub(super) fn node_style_reads_any_of_custom_properties(&self, node: StyleNodeID, names: &[Arc<[u16]>]) -> bool {+ if names.is_empty() {+ return false;+ }+ let reads_any = |reads: &[Arc<[u16]>]| reads.iter().any(|read| names.binary_search(read).is_ok());+ let groups = self.current_winner_groups();+ let Lookup::Known((_, state)) = groups.token_for(WinnerGroupKey::current(node, self.program.version())) else {+ return true;+ };+ let states_read_any = std::iter::once(state)+ .chain(groups.pseudo_states(node).map(|(_, _, state, _)| state))+ .any(|state| {+ self.state_custom_property_reads(node, state)+ .is_none_or(|reads| reads_any(&reads))+ });+ if states_read_any {+ return true;+ }+ let declarations_read_any = match self.custom_declaration_custom_property_reads.get(&node) {+ Some(reads) => reads.as_ref().is_none_or(|reads| reads_any(reads)),+ None => self.node_declares_custom_properties(node),+ };+ declarations_read_any+ || self+ .animation_effect_descriptions+ .keyframes_read_any_of_custom_properties(node, names)+ }+/// Whether the node's winner inventory is complete once custom properties are set aside: the/// engine computes an environment from those itself, and a rule declaring them is otherwise as/// complete as any, for the element and for each of its pseudo-elements alike.@@ -1262,6 +1319,24 @@ impl RetainedState {})}+ fn cascaded_custom_property_reads(+ &self,+ cascaded: &[(CustomDeclaration, RetainedStyleValueData)],+ ) -> Option<CustomPropertyNames> {+ let mut names = Vec::new();+ for (declared, value) in cascaded {+ if !matches!(declared.operator, CascadeOperator::Declared | CascadeOperator::Initial)+ || !append_custom_property_reads(value.data(), &mut names)+ {+ return None;+ }+ // A declared name counts as a read. An environment leaves out a declared value equal to the+ // one it inherits.+ names.push(self.declared_custom_property_name(declared.name)?.text.clone());+ }+ Some(sorted_custom_property_names(names))+ }+/// The name a cascaded custom declaration names, as its store entry keys it. A block's/// publication notes every custom property name it declares before the block is set, so a/// live declaration's name is always known.@@ -1316,6 +1391,7 @@ impl RetainedState {if !self.any_custom_property_is_declared() {if pseudo.is_none() {self.custom_declaration_reads.remove(&node);+ self.custom_declaration_custom_property_reads.remove(&node);}return Ok(self.custom_property_environments.inheritable(parent_environment));}@@ -1342,6 +1418,26 @@ impl RetainedState {pseudo: Option<u8>,cascaded: &[(CustomDeclaration, RetainedStyleValueData)],) {+ let custom_property_reads = (!cascaded.is_empty()).then(|| self.cascaded_custom_property_reads(cascaded));+ match (custom_property_reads, pseudo) {+ (None, None) => {+ self.custom_declaration_custom_property_reads.remove(&node);+ }+ (None, Some(_)) => {}+ (Some(reads), None) => {+ self.custom_declaration_custom_property_reads.insert(node, reads);+ }+ (Some(reads), Some(_)) => {+ let merged = match (self.custom_declaration_custom_property_reads.remove(&node), reads) {+ (None, reads) => reads,+ (Some(Some(existing)), Some(reads)) => Some(sorted_custom_property_names(+ existing.iter().chain(reads.iter()).cloned().collect(),+ )),+ (Some(_), _) => None,+ };+ self.custom_declaration_custom_property_reads.insert(node, merged);+ }+ }let reads = cascaded.iter().fold(0, |reads, (_, value)| reads | substitution_reads(value.data()));diff --git a/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs b/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rsindex 712e866ecd9..849d795e234 100644--- a/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs+++ b/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs@@ -408,6 +408,31 @@ impl AnimationEffectDescriptions {.map_or(&[], |(_, effects)| effects)}+ pub(crate) fn keyframes_read_any_of_custom_properties(&self, node: StyleNodeID, names: &[Arc<[u16]>]) -> bool {+ let Some(lists) = self.rows.get(&node) else {+ return false;+ };+ let reads_any = |value: &RetainedStyleValueData| {+ super::custom_property_cascade::value_reads_any_of_custom_properties(value.data(), names)+ };+ lists.iter().flat_map(|(_, effects)| effects.iter()).any(|effect| {+ effect.keyframes.iter().any(|keyframe| {+ keyframe.easing_value.as_ref().is_some_and(reads_any)+ || effect+ .declarations_of(keyframe)+ .iter()+ .map(|declaration| &declaration.value)+ .chain(+ effect+ .custom_declarations_of(keyframe)+ .iter()+ .map(|declaration| &declaration.value),+ )+ .any(|value| matches!(value, PublishedValue::Declared(value) if reads_any(value)))+ })+ })+ }+/// Whether one of an element's lists describes exactly these versions of the effects, in this/// order. Every change that moves what a description says moves its effect's generation.#[cfg(test)]diff --git a/Libraries/LibWeb/Rust/src/css/style/environment_move.rs b/Libraries/LibWeb/Rust/src/css/style/environment_move.rsindex c7e8d7e0823..8f9372b92c9 100644--- a/Libraries/LibWeb/Rust/src/css/style/environment_move.rs+++ b/Libraries/LibWeb/Rust/src/css/style/environment_move.rs@@ -7,9 +7,13 @@//! Moving the custom-property environments below an element whose own environment moved.use std::ffi::c_void;+use std::sync::Arc;+use super::custom_property_cascade::{CustomPropertyNames, sorted_custom_property_names};use super::inputs::{HeldCustomPropertyEnvironment, RetainedCustomPropertyData};use super::*;+use crate::css::custom_properties::CustomPropertyStore;+use crate::css::style_value::StyleValueData;/// An environment the host holds, as a move names it: the identity, the store behind it, null for/// the empty environment.@@ -21,6 +25,9 @@ pub(crate) struct NamedEnvironment {/// A move of one element's custom-property environment, as the host made it.pub(crate) struct EnvironmentMove {+ /// What the element held before the move and holds now, including what its animations sampled.+ pub(crate) old_environment: NamedEnvironment,+ pub(crate) new_environment: NamedEnvironment,/// What the element handed its children before the move.pub(crate) old_inheritable: u64,/// What it hands them now. Every element the move hands the environment it inherits takes@@ -51,6 +58,88 @@ pub(crate) enum EnvironmentMoveAction {Recompute(StyleNodeID),}+#[derive(Default)]+pub(super) struct ChangedCustomPropertyNames {+ by_stores: HashMap<(usize, usize), Arc<[usize]>>,+ /// Keeps the stores whose addresses key `by_stores` alive, so that no other store can reuse an address.+ stores: Vec<Arc<CustomPropertyStore>>,+}++impl ChangedCustomPropertyNames {+ pub(super) fn clear(&mut self) {+ self.by_stores.clear();+ self.stores.clear();+ }++ fn between(+ &mut self,+ old: Option<&Arc<CustomPropertyStore>>,+ new: Option<&Arc<CustomPropertyStore>>,+ ) -> Arc<[usize]> {+ let key = (+ old.map_or(0, |store| Arc::as_ptr(store) as usize),+ new.map_or(0, |store| Arc::as_ptr(store) as usize),+ );+ if key.0 == key.1 {+ return Arc::from([]);+ }+ if let Some(names) = self.by_stores.get(&key) {+ return names.clone();+ }+ let inherited = self.between(+ old.and_then(|store| store.parent()),+ new.and_then(|store| store.parent()),+ );+ let mut seen = HashSet::default();+ let mut names: Vec<usize> = old+ .into_iter()+ .chain(new)+ .flat_map(|store| store.own_values.keys().copied())+ .chain(inherited.iter().copied())+ .filter(|&name| seen.insert(name) && custom_property_value_moved(name, old, new))+ .collect();+ names.sort_unstable();+ let names: Arc<[usize]> = names.into();+ self.stores.extend(old.cloned());+ self.stores.extend(new.cloned());+ self.by_stores.insert(key, names.clone());+ names+ }+}++fn custom_property_value_moved(+ name: usize,+ old: Option<&Arc<CustomPropertyStore>>,+ new: Option<&Arc<CustomPropertyStore>>,+) -> bool {+ let old = old.and_then(|store| store.get(name));+ let new = new.and_then(|store| store.get(name));+ let (old, new) = match (old, new) {+ (None, None) => return false,+ (Some(old), Some(new)) => (old.value.pointer(), new.value.pointer()),+ _ => return true,+ };+ if std::ptr::eq(old, new) {+ return false;+ }+ // SAFETY: Both values are kept alive by the stores that hold them.+ matches!(unsafe { &*old }, StyleValueData::PendingSubstitution { .. })+ || !unsafe { crate::css::style_value::rust_style_value_equals(old, new) }+}++/// # Safety+/// `store` must be null or a live raw `Arc` pointer to a `CustomPropertyStore`.+unsafe fn retained_store(store: *const c_void) -> Option<Arc<CustomPropertyStore>> {+ if store.is_null() {+ return None;+ }+ let store = store.cast::<CustomPropertyStore>();+ unsafe {+ Arc::increment_strong_count(store);+ Some(Arc::from_raw(store))+ }+}+impl StyleEngine {/// Move the custom-property environments below `origin`, whose own moved as `moved` says, and/// answer what the host does for the elements the move reaches, in preorder. An element that@@ -74,12 +163,13 @@ impl StyleEngine {.custom_property_environments.retain(moved.new_inheritable.identity, moved.new_inheritable.store);}+ let mut changed_names = None;let mut pending = Vec::new();self.push_flat_tree_element_children(origin, moved.old_inheritable, &mut pending);while let Some((element, old_parent_inheritable)) = pending.pop() {- if let Some(old_inheritable) =- unsafe { self.move_element_environment(element, old_parent_inheritable, moved, &mut act) }- {+ if let Some(old_inheritable) = unsafe {+ self.move_element_environment(element, old_parent_inheritable, moved, &mut changed_names, &mut act)+ } {self.push_flat_tree_element_children(element, old_inheritable, &mut pending);}}@@ -126,6 +216,7 @@ impl StyleEngine {element: StyleNodeID,old_parent_inheritable: u64,moved: &EnvironmentMove,+ changed_names: &mut Option<CustomPropertyNames>,act: &mut impl FnMut(EnvironmentMoveAction),) -> Option<u64> {// An unstyled subtree takes whatever it inherits once it has style.@@ -150,14 +241,14 @@ impl StyleEngine {|| (!declares && !self.retained.node_declares_custom_properties(element));if !holds_inherited_environment {// Its declared values stand while it reads nothing that changed.- if existing == 0 || !declares || self.environment_move_needs_recompute(element) {+ if existing == 0 || !declares || self.environment_move_needs_recompute(element, moved, changed_names) {act(EnvironmentMoveAction::Recompute(element));} else {act(EnvironmentMoveAction::Rebuild(element));}return None;}- if self.environment_move_needs_recompute(element) {+ if self.environment_move_needs_recompute(element, moved, changed_names) {act(EnvironmentMoveAction::Recompute(element));return None;}@@ -225,10 +316,46 @@ impl StyleEngine {}/// Whether a moved environment computes the element again rather than handing it the moved- /// one: its style reads the environment other than through `var()`, or reads custom properties.- fn environment_move_needs_recompute(&mut self, element: StyleNodeID) -> bool {- self.retained.element_recomputes_on_environment_move(element)- || self.retained.node_style_reads_custom_properties(element)+ /// one: its style reads the environment other than through `var()`, or reads a changed custom property.+ fn environment_move_needs_recompute(+ &mut self,+ element: StyleNodeID,+ moved: &EnvironmentMove,+ changed_names: &mut Option<CustomPropertyNames>,+ ) -> bool {+ if self.retained.element_recomputes_on_environment_move(element) {+ return true;+ }+ let changed = changed_names+ .get_or_insert_with(|| self.changed_custom_property_names(moved))+ .clone();+ self.retained+ .node_style_reads_any_of_custom_properties(element, &changed)+ }++ fn changed_custom_property_names(&mut self, moved: &EnvironmentMove) -> CustomPropertyNames {+ // SAFETY: The move's stores are live for the move.+ let (old, new) = unsafe {+ (+ retained_store(moved.old_environment.store),+ retained_store(moved.new_environment.store),+ )+ };+ let names = self+ .host+ .environment_move_changed_names+ .between(old.as_ref(), new.as_ref());+ sorted_custom_property_names(+ names+ .iter()+ .filter_map(|&name| {+ old.as_ref()+ .and_then(|store| store.get(name))+ .or_else(|| new.as_ref().and_then(|store| store.get(name)))+ })+ .map(|entry| entry.name.clone())+ .collect(),+ )}}@@ -243,7 +370,13 @@ mod tests {}fn moved(old_inheritable: u64, new_inheritable: u64) -> EnvironmentMove {+ let empty = NamedEnvironment {+ identity: 0,+ store: std::ptr::null(),+ };EnvironmentMove {+ old_environment: empty,+ new_environment: empty,old_inheritable,new_inheritable: NamedEnvironment {identity: new_inheritable,diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rsindex 4835cd43197..fce113c0115 100644--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs@@ -1904,6 +1904,7 @@ impl StyleEngine {custom_property_environments: Default::default(),nodes_with_substituted_records: HashSet::default(),custom_declaration_reads: HashMap::default(),+ custom_declaration_custom_property_reads: HashMap::default(),nodes_with_tree_counting_records: HashMap::default(),nodes_with_rolled_back_records: HashMap::default(),nodes_with_element_relative_substitutions: HashMap::default(),@@ -2000,6 +2001,7 @@ impl StyleEngine {deferred_element_style_inputs: Vec::new(),deferred_element_style_inputs_moved: false,deferred_element_style_inputs_are_pending: false,+ environment_move_changed_names: Default::default(),deferred_element_style_input_memory: MemoryLease::new(MemoryCategory::NormalizationJournal),initial_tree_batch_applied: false,initial_tree_bulk_load_is_pending: false,@@ -3296,6 +3298,7 @@ impl RetainedState {custom_property_environments: _,nodes_with_substituted_records,custom_declaration_reads,+ custom_declaration_custom_property_reads,nodes_with_tree_counting_records,nodes_with_rolled_back_records,nodes_with_element_relative_substitutions,@@ -3404,6 +3407,7 @@ impl RetainedState {computed_group_sets.remove(node);nodes_with_substituted_records.remove(&node);custom_declaration_reads.remove(&node);+ custom_declaration_custom_property_reads.remove(&node);nodes_with_tree_counting_records.remove(&node);nodes_with_rolled_back_records.remove(&node);nodes_with_element_relative_substitutions.remove(&node);diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rsindex bcced803dd6..4c02b60729a 100644--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs@@ -834,6 +834,10 @@ pub struct RetainedState {/// environment they resolve over, as `FfiNodeRecordReads` bits, for the elements whose/// declarations read anything: what the host notes beside their records.custom_declaration_reads: HashMap<StyleNodeID, u8>,+ /// The custom properties the custom declarations of an element, or of its pseudo-elements,+ /// declare or read through `var()`. `None` when they cannot be listed.+ custom_declaration_custom_property_reads:+ HashMap<StyleNodeID, Option<custom_property_cascade::CustomPropertyNames>>,/// Which of a node's records read its place among its siblings, written or produced by a/// substitution: a bit for its own record and one per synthetic pseudo-element kind, which/// each record the engine derives, or admits from C++, sets or clears as it is installed. A@@ -1090,6 +1094,8 @@ pub struct HostState {/// Whether the deferred element style inputs are owed to the next transaction, as opposed to/// held back by a flush without a document root.deferred_element_style_inputs_are_pending: bool,+ /// The custom properties that changed between pairs of environments during this transaction.+ environment_move_changed_names: crate::fork::ForkReset<environment_move::ChangedCustomPropertyNames>,deferred_element_style_input_memory: MemoryLease,/// Whether any tree input batch has crossed into the engine. A first batch consisting entirely/// of unique arrivals can install its final relation rows as one bulk load.diff --git a/Libraries/LibWeb/Rust/src/css/style/ordering.rs b/Libraries/LibWeb/Rust/src/css/style/ordering.rsindex 136549b3737..f215c3a9bb6 100644--- a/Libraries/LibWeb/Rust/src/css/style/ordering.rs+++ b/Libraries/LibWeb/Rust/src/css/style/ordering.rs@@ -2200,6 +2200,7 @@ impl StyleEngine {.resize_required_to(&mut self.retained.memory, 0);self.retained.facts.release_staging(&mut self.retained.memory);self.host.program_staging.clear();+ self.host.environment_move_changed_names.clear();self.sweep_selector_programs();self.shed_routing_for_detached_sheets();}diff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rsindex 07c1f4a35e3..d44765221b0 100644--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs@@ -3158,6 +3158,22 @@ impl RetainedState {self.state_summary(node, state).has_substitutions}+ pub(super) fn state_custom_property_reads(+ &self,+ node: StyleNodeID,+ state: CascadeStateID,+ ) -> Option<custom_property_cascade::CustomPropertyNames> {+ self.winner_groups.state_custom_property_reads(state, || {+ let mut names = Vec::new();+ for value in self.state_substitution_values(node, state) {+ if !custom_property_cascade::append_custom_property_reads(value.data(), &mut names) {+ return None;+ }+ }+ Some(custom_property_cascade::sorted_custom_property_names(names))+ })+ }+/// What a state's winners read beyond the cascade, as `cascade::STATE_READS_*` bits, decided/// once for each state.pub(super) fn state_reads(&self, node: StyleNodeID, state: CascadeStateID) -> u8 {diff --git a/Libraries/LibWeb/Rust/src/css/style/reaction_application.rs b/Libraries/LibWeb/Rust/src/css/style/reaction_application.rsindex 2ccef24f52c..537027aaa1e 100644--- a/Libraries/LibWeb/Rust/src/css/style/reaction_application.rs+++ b/Libraries/LibWeb/Rust/src/css/style/reaction_application.rs@@ -960,6 +960,8 @@ pub unsafe extern "C" fn style_engine_move_custom_property_environment(store: environment.store,};let environment_move = EnvironmentMove {+ old_environment: named(moved.old_environment),+ new_environment: named(moved.new_environment),old_inheritable: moved.old_inheritable,new_inheritable: named(moved.new_inheritable),new_inheritable_data: moved.new_inheritable_data,diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-over-own-declarations.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-over-own-declarations.txtindex d38b0b2eae2..d31bedf9f33 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-over-own-declarations.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-over-own-declarations.txt@@ -1,5 +1,5 @@-records computed: 5-transactions: 3+records computed: 3+transactions: 2reader: rgb(0, 0, 255)reader: rgb(0, 0, 255)scope: blue 4pxdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-reaches-readers-by-name.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-reaches-readers-by-name.txtnew file mode 100644index 00000000000..86b126d57ae--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-reaches-readers-by-name.txt@@ -0,0 +1,6 @@+declarations: 40px+pseudo-element: 20px+keyframes: 20px+element declaring other names: 6px+its child: 20px+child of animated element: 5 20diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-move-reaches-readers-by-name.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-move-reaches-readers-by-name.htmlnew file mode 100644index 00000000000..fc024a8405d--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-move-reaches-readers-by-name.html@@ -0,0 +1,36 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<style>+ @property --glow { syntax: "<number>"; inherits: true; initial-value: 0; }+ @keyframes grow { from { width: calc(var(--moved) * 1px); } to { width: 0px; } }+ @keyframes glow { from { --glow: 5; } to { --glow: 7; } }+ #root { --moved: 10; --stable: 3; }+ #declares-reader { --own: calc(var(--moved) * 2); width: calc(var(--own) * 1px); }+ #pseudo-reader::before { content: ""; display: block; width: calc(var(--moved) * 1px); }+ #keyframes-reader { animation: grow 1s paused; }+ #declares-other { --own: calc(var(--stable) * 2); width: calc(var(--own) * 1px); }+ #declares-other-child { width: calc(var(--moved) * 1px); }+ #animated { animation: glow 1s paused; }+ #animated-child { --own: 1; }+</style>+<div id="root">+ <div id="declares-reader"></div>+ <div id="pseudo-reader"></div>+ <div id="keyframes-reader"></div>+ <div id="declares-other"><div id="declares-other-child"></div></div>+ <div id="animated"><div id="animated-child"></div></div>+</div>+<script>+ promiseTest(async () => {+ await animationFrame();+ const style = (id, pseudo) => getComputedStyle(document.getElementById(id), pseudo);+ document.getElementById("root").style.setProperty("--moved", "20");+ println(`declarations: ${style("declares-reader").width}`);+ println(`pseudo-element: ${style("pseudo-reader", "::before").width}`);+ println(`keyframes: ${style("keyframes-reader").width}`);+ println(`element declaring other names: ${style("declares-other").width}`);+ println(`its child: ${style("declares-other-child").width}`);+ // #animated-child declares its own custom property, so it is rebuilt over its parent's animated values.+ println(`child of animated element: ${style("animated-child").getPropertyValue("--glow")} ${style("animated-child").getPropertyValue("--moved")}`);+ });+</script>