Truly independent web browser
LibWeb: Decide the hover seal from the keys a transaction moves
Andreas Kling373f9fbf1591
diff --git a/Libraries/LibWeb/Rust/src/cow_column.rs b/Libraries/LibWeb/Rust/src/cow_column.rsindex dec8b1d6e7f..0cd67a0dbb1 100644--- a/Libraries/LibWeb/Rust/src/cow_column.rs+++ b/Libraries/LibWeb/Rust/src/cow_column.rs@@ -380,41 +380,6 @@ impl<T, const CHUNK: usize> ColumnSnapshot<T, CHUNK> {spine_heap_size(&self.spine, sizer, &mut row_heap)}- /// The rows of the chunks this snapshot holds other than `older` does, as ranges of row indices: a chunk either- /// holds and the other does not, or that the two hold different allocations of. A group both share is skipped- /// whole, so the cost follows the chunks written between the two generations rather than the column's size.- pub(crate) fn changed_rows_since(&self, older: &Self) -> Vec<std::ops::Range<usize>> {- let mut changed = Vec::new();- if Arc::ptr_eq(&self.spine, &older.spine) {- return changed;- }- for group_index in 0..self.spine.len().max(older.spine.len()) {- let (group, older_group) = (self.spine.get(group_index), older.spine.get(group_index));- if let (Some(group), Some(older_group)) = (group, older_group)- && Arc::ptr_eq(group, older_group)- {- continue;- }- for chunk_in_group in 0..GROUP {- let chunk = group.and_then(|group| group.0[chunk_in_group].as_ref());- let older_chunk = older_group.and_then(|group| group.0[chunk_in_group].as_ref());- let same = match (chunk, older_chunk) {- (Some(chunk), Some(older_chunk)) => Arc::ptr_eq(chunk, older_chunk),- (None, None) => true,- _ => false,- };- if !same {- let start = (group_index * GROUP + chunk_in_group) * CHUNK;- match changed.last_mut() {- Some(last) if last.end == start => last.end = start + CHUNK,- _ => changed.push(start..start + CHUNK),- }- }- }- }- changed- }-/// How many rows the snapshot has room for: every row index below it may be read.pub(crate) fn slot_capacity(&self) -> usize {self.spine.last().map_or(0, |last| {@@ -619,21 +584,6 @@ mod tests {assert_eq!(rows(&column.publish(), 7), [1, 20, 3, 4, 5, 60, 7]);}- #[test]- fn a_snapshot_names_the_rows_of_the_chunks_written_since_an_older_one() {- let mut column = column_of(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);- let first = column.publish();- assert!(column.publish().changed_rows_since(&first).is_empty());- set(&mut column, 5, 60);- set(&mut column, 9, 90);- column.grow_to(13);- let second = column.publish();- assert_eq!(second.changed_rows_since(&first), [4..16]);- set(&mut column, 1, 20);- assert_eq!(column.publish().changed_rows_since(&second), [0..4]);- assert_eq!(first.changed_rows_since(&ColumnSnapshot::default()), [0..12]);- }-#[test]fn a_write_copies_only_the_chunk_a_snapshot_shares_and_only_once() {let mut column = column_of(&[1, 2, 3, 4, 5, 6, 7, 8]);diff --git a/Libraries/LibWeb/Rust/src/css/selector_arena.rs b/Libraries/LibWeb/Rust/src/css/selector_arena.rsindex 702dd37e9cf..c19b07e706b 100644--- a/Libraries/LibWeb/Rust/src/css/selector_arena.rs+++ b/Libraries/LibWeb/Rust/src/css/selector_arena.rs@@ -1036,6 +1036,12 @@ impl<'a> Selector<'a> {.map(|facts| (self.arena.serial, facts.shape))}+ /// What tells the selector from any other of the process, for as long as the process lives.+ #[must_use]+ pub(crate) fn identity(self) -> (SelectorArenaSerial, ComponentOffset) {+ (self.arena.serial, self.at)+ }+/// The ids, as `false`, and the classes, as `true`, the first compound tests, read from its components.pub(crate) fn ids_and_classes(self) -> impl Iterator<Item = IdOrClass> + 'a {let (end, _) = self.first_compound_end();diff --git a/Libraries/LibWeb/Rust/src/css/style/hover_lane.rs b/Libraries/LibWeb/Rust/src/css/style/hover_lane.rsindex 34e317bda6f..2ab00656f0f 100644--- a/Libraries/LibWeb/Rust/src/css/style/hover_lane.rs+++ b/Libraries/LibWeb/Rust/src/css/style/hover_lane.rs@@ -106,12 +106,7 @@ impl StyleEngine {/// Whether a hover needs the style engine to restyle an element or reject a disabled control.pub(crate) fn hover_needs_style_state(&mut self, root: StyleNodeID) -> bool {- if let Some(needs_style_state) = self.memoized_hover_seal(root) {- return needs_style_state;- }- let needs_style_state = self.hover_seal_needs_style_state(root);- self.memoize_hover_seal(root, needs_style_state);- needs_style_state+ self.hover_seal_needs_style_state(root)}/// The element a mouse move aimed at `node`, an element, is dispatched to, as the host dispatches it: none wherediff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rsindex f8328c2351a..90a6f3d7d0a 100644--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs@@ -445,7 +445,7 @@ pub struct HostState {/// The style node identities the end of a transaction released since the job began, which the job's end pays the/// host to mint again.released_style_nodes: Vec<u32>,- /// The hover seal's last answer, with what it read.+ /// What the hover seal keeps between frames.hover_seal: pipeline::HoverSealMemo,}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/invalidation.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/invalidation.rsindex 64e5bff66fb..8c719de0e21 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/invalidation.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/invalidation.rs@@ -24,7 +24,7 @@ use super::super::selector_analysis::dispatch_selectivity;use super::super::selector_evaluation::ElementFeatures;use super::super::*;use super::extent_map::SharedExtentMap;-use super::projection::ProjectionRow;+use super::projection::{CarriedKey, ProjectionRow, WatchedKeys};use super::rules::{RuleIndex, SheetSegment, is_probed, proves_the_whole_selector};use super::shared_prefix::SharedPrefixVec;use crate::css::selector::{@@ -363,6 +363,142 @@ fn compound_carried(selector: Selector<'_>, facts: ProjectionRow<'_>) -> bool {.all(|simple| simple_carried(&simple, facts))}+/// Keys of which every element [`compound_carried`] holds for carries at least one, or none where any element may be+/// such: the keys of one test of the compound, the most selective one, or of the alternatives of its `:is()`, `:where()`+/// or `&`, each in every form an element carries it. A change to one of the two is a change to the other.+fn carried_keys(selector: Selector<'_>) -> Option<SmallVec<[CarriedKey; 4]>> {+ fn of_any<'a>(selectors: impl Iterator<Item = Selector<'a>>) -> Option<SmallVec<[CarriedKey; 4]>> {+ let mut keys = SmallVec::new();+ for selector in selectors {+ keys.extend(carried_keys(selector)?);+ }+ Some(keys)+ }+ fn in_every_form(make: fn(StyleAtomID) -> CarriedKey, name: StyleAtomID) -> SmallVec<[CarriedKey; 4]> {+ let folded = process_atoms().ascii_lowercase(name);+ match folded == name {+ true => smallvec::smallvec![make(name)],+ false => smallvec::smallvec![make(name), make(folded)],+ }+ }+ fn of_simple(simple: &SimpleSelector<'_>) -> Option<SmallVec<[CarriedKey; 4]>> {+ match simple {+ SimpleSelector::Class(name) => Some(in_every_form(CarriedKey::Class, name.name)),+ SimpleSelector::Id(name) => Some(in_every_form(CarriedKey::Id, name.name)),+ SimpleSelector::TagName(name) => Some(in_every_form(CarriedKey::Tag, name.name)),+ SimpleSelector::PseudoClass(pseudo_class)+ if matches!(pseudo_class.pseudo_class, PseudoClassType::Is | PseudoClassType::Where) =>+ {+ of_any(pseudo_class.argument_selector_list.iter())+ }+ SimpleSelector::Nesting(Nesting::Rule(parent)) => of_any(parent.iter()),+ _ => None,+ }+ }+ let selectivity = |keys: &SmallVec<[CarriedKey; 4]>| {+ let tags = keys.iter().any(|key| matches!(key, CarriedKey::Tag(_)));+ (tags, keys.len())+ };+ let compound = selector.first_compound();+ if let Some(SimpleSelector::PseudoElement(pseudo_element)) = compound.simple_selectors.first() {+ let kind = pseudo_element.pseudo_element as u16;+ let backed_kinds = u16::from(super::super::bridge::FIRST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND)+ ..=u16::from(super::super::bridge::LAST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND);+ if backed_kinds.contains(&kind) {+ return Some(smallvec::smallvec![CarriedKey::BackedPseudoElement(+ u8::try_from(kind).expect("a backed pseudo-element kind fits a u8")+ )]);+ }+ if is_transparent(&compound) {+ return match selector.left() {+ Some((Combinator::PseudoElement, left)) => carried_keys(left),+ _ => None,+ };+ }+ }+ compound+ .simple_selectors+ .iter()+ .filter_map(|simple| of_simple(&simple))+ .min_by_key(selectivity)+}++/// The compounds of a map testing `:hover`, by the keys of the elements that may match them, compiled once for the map+/// so that an element is tested by looking up its own keys rather than by reading every compound.+pub(super) struct HoverCompounds {+ /// Whether any element may match a compound no key selects, or an element's hover flips a query.+ every_element: bool,+ by_key: HashMap<CarriedKey, SmallVec<[Dependency; 2]>>,+ keys: Arc<WatchedKeys>,+ /// What tells the compounds from others, which a map testing the same ones says too.+ identities: Vec<(crate::css::selector_arena::SelectorArenaSerial, ComponentOffset)>,+}++impl HoverCompounds {+ #[must_use]+ pub(super) fn every_element(&self) -> bool {+ self.every_element+ }++ #[must_use]+ pub(super) fn keys(&self) -> &Arc<WatchedKeys> {+ &self.keys+ }++ /// Whether the two hold the same compounds, whichever maps they were compiled from.+ #[must_use]+ pub(super) fn are_the_same_as(&self, other: &Self) -> bool {+ self.every_element == other.every_element && self.identities == other.identities+ }++ /// Whether the element `facts` are of may match one of the compounds, by the same test as+ /// [`InvalidationMap::may_match_by_keys`] for each, of the map and index they were compiled from.+ #[must_use]+ pub(super) fn may_match(&self, map: &InvalidationMap, index: &RuleIndex, facts: ProjectionRow<'_>) -> bool {+ facts.carried_keys().any(|key| {+ self.by_key.get(&key).is_some_and(|compounds| {+ compounds+ .iter()+ .any(|&compound| map.may_match_by_keys(index, compound, facts))+ })+ })+ }+}++impl InvalidationMap {+ /// The compounds of the map testing `:hover`, compiled.+ pub(super) fn hover_compounds(&self, index: &RuleIndex) -> HoverCompounds {+ let hover = Trigger::State(StateFact::Hover);+ let mut every_element = self.queries_testing(&hover).next().is_some();+ let mut by_key: HashMap<CarriedKey, SmallVec<[Dependency; 2]>> = HashMap::default();+ let mut identities = Vec::new();+ for compound in self.effects(&hover) {+ let selector = self.resolve(compound, index).1;+ identities.push(selector.identity());+ match carried_keys(selector) {+ Some(keys) => {+ for key in keys {+ by_key.entry(key).or_default().push(compound);+ }+ }+ None => every_element = true,+ }+ }+ identities.sort_unstable();+ identities.dedup();+ if every_element {+ by_key.clear();+ }+ let keys = Arc::new(WatchedKeys::new(by_key.keys().copied()));+ HoverCompounds {+ every_element,+ by_key,+ keys,+ identities,+ }+ }+}+/// Whether `compound` evaluates a `:has()`, or a compound left of it does.fn reads_relative(compound: Selector<'_>) -> bool {compound.compounds().any(|compound| {diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/pending_inputs.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/pending_inputs.rsindex 68e9b9cb34c..3b33421470d 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/pending_inputs.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/pending_inputs.rs@@ -8,41 +8,37 @@//! them where nothing it reads can move: a geometry read reuses the committed layout where no//! pending input may move geometry, and a hover reuses the read-only frame where no element can//! match a compound testing `:hover`.+//!+//! The hover's question is asked of every frame and the host waits for its answer, so no element is read to answer it.+//! The compounds testing `:hover` are compiled once for the rules into the keys of the elements that may match them, and+//! a transaction notes the elements whose keys among those it moved.use super::super::*;-use super::invalidation::{InvalidationMap, Trigger};+use super::invalidation::{HoverCompounds, InvalidationMap, Trigger};use super::live::Live;use super::projection::{ElementChange, ProjectionGeneration};use crate::fast_hash::FastSet;-/// The last answer of whether a hover needs the style engine, with what it read to answer: the-/// projection's generation, the tree's version, the invalidation map and the hover's root. An-/// answer read over the same holds again, so a rendering update over a document nothing changed-/// in asks nothing of its elements.-#[derive(Clone, Default)]+/// What the hover seal keeps between frames.+#[derive(Default)]pub(in crate::css::style) struct HoverSealMemo {- last: Option<HoverSealAnswer>,- candidates: Option<HoverSealCandidates>,+ carriers: Option<HoverCarriers>,cursor_facts: Option<HoverCursorFactsAnswer>,}-/// The elements whose rows may make a hover need the style engine, with the generation of the rows they were read-/// from and the invalidation map they were matched against: a seal over other rows reads again only the rows written-/// since.-#[derive(Clone)]-struct HoverSealCandidates {- projection: ProjectionGeneration,- invalidation: Option<Arc<InvalidationMap>>,- hover_keyed: HoverKeyedElements,+// NB: A fork of the engine seals no frame, and has no use for what the host's seal kept.+impl Clone for HoverSealMemo {+ fn clone(&self) -> Self {+ Self::default()+ }}-/// The elements that may match a compound testing `:hover`, by their keys.-#[derive(Clone)]-enum HoverKeyedElements {- /// Every element may: there is no map describing the rules, or a query tests `:hover`.- Every,- /// Those carrying the keys of a compound testing `:hover`.- Carrying(FastSet<StyleNodeID>),+/// The elements that may match a compound testing `:hover`, which the transactions keep up as they move the keys of the+/// compounds of `map`.+struct HoverCarriers {+ map: Arc<InvalidationMap>,+ compounds: HoverCompounds,+ elements: FastSet<StyleNodeID>,}/// The cursor facts published last, with the generations of what they read: the projection's, the tree's paint facts,@@ -56,39 +52,7 @@ struct HoverCursorFactsAnswer {editable: Arc<FastSet<StyleNodeID>>,}-#[derive(Clone)]-struct HoverSealAnswer {- projection: ProjectionGeneration,- dom_order_version: u64,- invalidation: Option<Arc<InvalidationMap>>,- root: StyleNodeID,- needs_style_state: bool,-}--/// Whether `a` and `b` are the same invalidation map, or both none.-fn same_map(a: Option<&Arc<InvalidationMap>>, b: Option<&Arc<InvalidationMap>>) -> bool {- match (a, b) {- (Some(a), Some(b)) => Arc::ptr_eq(a, b),- (None, None) => true,- _ => false,- }-}-impl StyleEngine {- fn hover_seal_invalidation(&self) -> Option<&Arc<InvalidationMap>> {- self.retained.live_style.as_deref()?.current_invalidation_shared()- }-- /// The answer the hover seal gave last for `root`, where nothing it read moved since.- pub(in super::super) fn memoized_hover_seal(&self, root: StyleNodeID) -> Option<bool> {- let last = self.host.hover_seal.last.as_ref()?;- (last.root == root- && same_map(last.invalidation.as_ref(), self.hover_seal_invalidation())- && last.dom_order_version == self.tree().dom_order_version()- && self.retained.projection.is_at_generation(&last.projection))- .then_some(last.needs_style_state)- }-/// The cursor facts built last, where nothing they read moved since.pub(in super::super) fn memoized_hover_cursor_facts(&self,@@ -125,17 +89,6 @@ impl StyleEngine {});}- /// Keep `needs_style_state`, the hover seal's answer for `root`, with what it read.- pub(in super::super) fn memoize_hover_seal(&mut self, root: StyleNodeID, needs_style_state: bool) {- self.host.hover_seal.last = Some(HoverSealAnswer {- projection: self.retained.projection.generation(),- dom_order_version: self.tree().dom_order_version(),- invalidation: self.hover_seal_invalidation().cloned(),- root,- needs_style_state,- });- }-/// The engine of the document and its invalidation map, where the map describes the/// rules and elements as they stand.fn current_invalidation(&self) -> Option<(&Live, &InvalidationMap)> {@@ -219,98 +172,98 @@ impl StyleEngine {}/// Whether a hover under `root` needs the style engine: whether an element in its shadow-including subtree is a- /// disabled control, or may come to match, or stop matching, a compound testing `:hover`. Reads again only the- /// rows written since the last answer, where the rules are the same.+ /// disabled control, or may come to match, or stop matching, a compound testing `:hover`. Reads only the elements+ /// a transaction moved the keys of those compounds of.pub(in super::super) fn hover_seal_needs_style_state(&mut self, root: StyleNodeID) -> bool {- self.update_hover_seal_candidates();- let candidates = self- .host- .hover_seal- .candidates- .as_ref()- .expect("the hover seal's candidates were just read");let projection = &self.retained.projection;let tree = self.tree();let under_root =|node: &StyleNodeID| tree.is_live(*node) && projection.is_in_shadow_including_subtree_of(*node, root);- projection.written_disabled().iter().any(under_root)- || match &candidates.hover_keyed {- HoverKeyedElements::Every => true,- HoverKeyedElements::Carrying(elements) => elements.iter().any(under_root),- }+ if projection.written_disabled().iter().any(under_root) || !self.update_hover_carriers() {+ return true;+ }+ let projection = &self.retained.projection;+ let tree = self.tree();+ let under_root =+ |node: &StyleNodeID| tree.is_live(*node) && projection.is_in_shadow_including_subtree_of(*node, root);+ self.host+ .hover_seal+ .carriers+ .as_ref()+ .expect("the hover seal's carriers were just brought up")+ .elements+ .iter()+ .any(under_root)}- /// Bring the hover seal's candidates up to the rows as they stand: read the rows written since they were read- /// last, or every row where there are none yet, or the rules moved.- fn update_hover_seal_candidates(&mut self) {- if self.host.hover_seal.candidates.as_ref().is_some_and(|candidates| {- self.retained.projection.is_at_generation(&candidates.projection)- && same_map(candidates.invalidation.as_ref(), self.hover_seal_invalidation())- }) {- return;- }- let generation = self.retained.projection.generation();- let invalidation = self.hover_seal_invalidation().cloned();- let (mut candidates, first_read) = match self.host.hover_seal.candidates.take() {- Some(candidates) => (candidates, false),- None => (- HoverSealCandidates {- projection: generation.clone(),- invalidation: None,- hover_keyed: HoverKeyedElements::Every,- },- true,- ),+ /// Bring the elements that may match a compound testing `:hover` up to the rows and the rules as they stand,+ /// answering whether they say which elements may. They do not where no map describes the rules, or where any element+ /// may.+ fn update_hover_carriers(&mut self) -> bool {+ let Some(live) = self.retained.live_style.as_deref() else {+ return false;};- let projection = &self.retained.projection;- let every_slot: Vec<_> = std::iter::once(0..projection.element_slot_count()).collect();- let element_at = |slot: usize| StyleNodeID::element(u32::try_from(slot).expect("element slot exceeds u32"));- let hover = Trigger::State(StateFact::Hover);- candidates.hover_keyed = match self.current_invalidation() {- Some((live, map)) if map.queries_testing(&hover).next().is_none() => {- let rules_moved = first_read || !same_map(candidates.invalidation.as_ref(), invalidation.as_ref());- let (mut elements, keyed_slots) =- match std::mem::replace(&mut candidates.hover_keyed, HoverKeyedElements::Every) {- HoverKeyedElements::Carrying(elements) if !rules_moved => (- elements,- generation.committed_slots_changed_since(&candidates.projection),- ),- _ => (FastSet::default(), every_slot),- };- if map.has_effects(&hover) {- for node in keyed_slots- .into_iter()- .flatten()- .filter(|&slot| slot != 0)- .map(element_at)- {- let carries_keys = projection.row_of(node).is_some_and(|row| {- map.effects(&hover)- .any(|effect| map.may_match_by_keys(&live.index, effect, row))- });- if carries_keys {- elements.insert(node);- } else {- elements.remove(&node);- }+ let Some(map) = live.current_invalidation_shared() else {+ return false;+ };+ let projection = &mut self.retained.projection;+ let known = self+ .host+ .hover_seal+ .carriers+ .take()+ .filter(|carriers| projection.watches_keys(carriers.compounds.keys()));+ let mut carriers = match known {+ Some(carriers) if Arc::ptr_eq(&carriers.map, map) => carriers,+ known => {+ let compounds = map.hover_compounds(&live.index);+ let elements = match known {+ // NB: The rules moved around the same compounds: no key moved, and no element is read again.+ Some(carriers) if carriers.compounds.are_the_same_as(&compounds) => carriers.elements,+ _ => {+ let writes = projection.take_watched_key_writes();+ projection.reuse_watched_key_writes(writes);+ projection+ .committed_carriers_of(compounds.keys())+ .filter(|&node| {+ projection+ .row_of(node)+ .is_some_and(|row| compounds.may_match(map, &live.index, row))+ })+ .collect()}- } else {- elements.clear();+ };+ projection.watch_keys(compounds.keys().clone());+ HoverCarriers {+ map: map.clone(),+ compounds,+ elements,}- HoverKeyedElements::Carrying(elements)}- _ => HoverKeyedElements::Every,};- candidates.projection = generation;- candidates.invalidation = invalidation;- self.host.hover_seal.candidates = Some(candidates);+ let writes = projection.take_watched_key_writes();+ for &node in &writes {+ let carries = projection+ .row_of(node)+ .is_some_and(|row| carriers.compounds.may_match(&carriers.map, &live.index, row));+ if carries {+ carriers.elements.insert(node);+ } else {+ carriers.elements.remove(&node);+ }+ }+ projection.reuse_watched_key_writes(writes);+ let says = !carriers.compounds.every_element();+ self.host.hover_seal.carriers = Some(carriers);+ says}}#[cfg(test)]mod tests {use super::super::test_support::{- add_class, add_rules, add_sheet, linear_document, remove_class, set_tag, start_live,+ add_class, add_rules, add_sheet, linear_document, relations, remove_class, run_style_update, set_tag,+ start_live,};use super::*;@@ -404,4 +357,116 @@ mod tests {assert!(engine.hover_needs_style_state(nodes[3]));assert!(engine.hover_needs_style_state(nodes[0]));}++ #[test]+ fn hover_compounds_select_what_reading_every_compound_selects() {+ for selector in [+ "A:hover",+ ".a.b:hover",+ ".a.c:hover",+ "#i:hover",+ "span.a:hover",+ "div.c:hover",+ ":is(.a, span):hover",+ ":is(.c, em):hover",+ ":where(:is(.b)):hover",+ ":is(.c):is(.a):hover",+ ] {+ let (mut engine, nodes) = document_with_rules(&format!("{selector} {{ color: red; }}"));+ add_class(&mut engine, nodes[1], "a");+ add_class(&mut engine, nodes[1], "b");+ set_tag(&mut engine, nodes[2], "span");+ add_class(&mut engine, nodes[3], "a");+ start_live(&mut engine, nodes[0]);+ let (live, map) = engine.current_invalidation().expect("the map describes the rules");+ let compounds = map.hover_compounds(&live.index);+ assert!(!compounds.every_element(), "{selector}");+ let hover = Trigger::State(StateFact::Hover);+ for &node in &nodes {+ let row = engine.retained.projection.row_of(node).expect("the element has facts");+ assert_eq!(+ compounds.may_match(map, &live.index, row),+ map.effects(&hover)+ .any(|effect| map.may_match_by_keys(&live.index, effect, row)),+ "{selector}"+ );+ }+ }+ }++ #[test]+ fn hover_compounds_with_no_key_answer_for_every_element() {+ for selector in ["*:hover", ":hover", ":not(:hover)", "[data-x]:hover", ":not(.a):hover"] {+ let (engine, _) = document_with_rules(&format!("{selector} {{ color: red; }}"));+ let (live, map) = engine.current_invalidation().expect("the map describes the rules");+ assert!(map.hover_compounds(&live.index).every_element(), "{selector}");+ }+ }++ #[test]+ fn a_hover_seal_follows_each_key_of_a_compound_as_transactions_move_them() {+ let (mut engine, nodes) = document_with_rules(".a.b:hover { color: red; }");+ assert!(!engine.hover_needs_style_state(nodes[0]));+ add_class(&mut engine, nodes[2], "a");+ run_style_update(&mut engine, nodes[0]);+ assert!(!engine.hover_needs_style_state(nodes[0]));+ add_class(&mut engine, nodes[2], "b");+ run_style_update(&mut engine, nodes[0]);+ assert!(engine.hover_needs_style_state(nodes[0]));+ remove_class(&mut engine, nodes[2], "a");+ run_style_update(&mut engine, nodes[0]);+ assert!(!engine.hover_needs_style_state(nodes[0]));+ }++ #[test]+ fn a_hover_seal_hears_of_no_element_but_those_whose_watched_keys_moved() {+ let (mut engine, nodes) = document_with_rules(".menu:hover { color: red; }");+ assert!(!engine.hover_needs_style_state(nodes[0]));+ add_class(&mut engine, nodes[1], "other");+ run_style_update(&mut engine, nodes[0]);+ assert!(engine.retained.projection.take_watched_key_writes().is_empty());+ add_class(&mut engine, nodes[1], "menu");+ add_class(&mut engine, nodes[2], "other");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(engine.retained.projection.take_watched_key_writes(), [nodes[1]]);+ add_class(&mut engine, nodes[1], "another");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(engine.retained.projection.take_watched_key_writes(), [nodes[1]]);+ }++ #[test]+ fn a_hover_seal_reads_no_element_for_rules_that_leave_its_compounds_alone() {+ let (mut engine, nodes) = document_with_rules(".menu:hover { color: red; }");+ assert!(!engine.hover_needs_style_state(nodes[0]));+ // NB: Nothing carries the key of the compound: an element read again would be found not to carry it.+ let carriers = engine.host.hover_seal.carriers.as_mut().expect("the seal answered");+ carriers.elements.insert(nodes[3]);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".other { color: green; }");+ run_style_update(&mut engine, nodes[0]);+ assert!(engine.hover_needs_style_state(nodes[0]));+ }++ #[test]+ fn a_hover_seal_finds_the_elements_a_rule_added_later_may_match() {+ let (mut engine, nodes) = document_with_rules(".other { color: green; }");+ add_class(&mut engine, nodes[2], "menu");+ run_style_update(&mut engine, nodes[0]);+ assert!(!engine.hover_needs_style_state(nodes[0]));+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".menu:hover { color: red; }");+ run_style_update(&mut engine, nodes[0]);+ assert!(engine.hover_needs_style_state(nodes[0]));+ }++ #[test]+ fn a_hover_seal_lets_go_of_an_element_that_leaves() {+ let (mut engine, nodes) = document_with_rules(".menu:hover { color: red; }");+ add_class(&mut engine, nodes[3], "menu");+ run_style_update(&mut engine, nodes[0]);+ assert!(engine.hover_needs_style_state(nodes[0]));+ engine.record_tree_delta(nodes[3], Some(relations(Some(nodes[0]), None, Some(nodes[2]))), None);+ run_style_update(&mut engine, nodes[0]);+ assert!(!engine.hover_needs_style_state(nodes[0]));+ }}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rsindex 2502a859f8c..bbcd6804ca1 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs@@ -156,6 +156,70 @@ impl PendingChangeScan {}}+/// A key of an element, which a compound can require of the elements it matches: a name its row holds, or the+/// element-backed pseudo-element of its shadow host it stands for.+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]+pub(in crate::css::style) enum CarriedKey {+ Tag(StyleAtomID),+ Class(StyleAtomID),+ Id(StyleAtomID),+ BackedPseudoElement(u8),+}++/// The keys a [`Projection`] notes the elements of: those that carried one, or carry one, and whose keys moved.+#[derive(Default)]+pub(in crate::css::style) struct WatchedKeys {+ keys: HashSet<CarriedKey>,+ /// A Bloom summary of the names among the keys, which rules out most elements without a lookup.+ names_bloom: u64,+ watches_pseudo_elements: bool,+}++impl WatchedKeys {+ pub(in crate::css::style) fn new(keys: impl IntoIterator<Item = CarriedKey>) -> Self {+ let keys: HashSet<CarriedKey> = keys.into_iter().collect();+ let mut watched = Self {+ names_bloom: 0,+ watches_pseudo_elements: false,+ keys: HashSet::default(),+ };+ for &key in &keys {+ match key {+ CarriedKey::Tag(tag) => watched.names_bloom |= dispatch_bloom_bit(DispatchKey::TagName(tag)),+ CarriedKey::Class(class) => watched.names_bloom |= dispatch_bloom_bit(DispatchKey::Class(class)),+ CarriedKey::Id(id) => watched.names_bloom |= dispatch_bloom_bit(DispatchKey::Id(id)),+ CarriedKey::BackedPseudoElement(_) => watched.watches_pseudo_elements = true,+ }+ }+ watched.keys = keys;+ watched+ }++ /// Whether an element with `facts` carries a key, without reading more of it than its names where its Bloom+ /// summary says it may.+ fn carried_by(&self, facts: &ElementFacts, host_fact_sets: &HostFactSets) -> bool {+ (facts.dispatch_bloom & self.names_bloom != 0 && facts.named_keys().any(|key| self.keys.contains(&key)))+ || (self.watches_pseudo_elements+ && backed_pseudo_element_key(facts, host_fact_sets).is_some_and(|key| self.keys.contains(&key)))+ }+}++fn backed_pseudo_element_key(facts: &ElementFacts, host_fact_sets: &HostFactSets) -> Option<CarriedKey> {+ host_fact_sets+ .get(facts.host_facts)+ .associated_pseudo_kind()+ .map(CarriedKey::BackedPseudoElement)+}++/// Whether the two say the same of the keys their elements carry.+fn carry_the_same_keys(was: &ElementFacts, is: &ElementFacts, host_fact_sets: &HostFactSets) -> bool {+ was.tag == is.tag+ && was.folded_tag() == is.folded_tag()+ && was.id() == is.id()+ && was.classes() == is.classes()+ && backed_pseudo_element_key(was, host_fact_sets) == backed_pseudo_element_key(is, host_fact_sets)+}+/// A list of atoms or pairs a row holds, shared by every copy of the row. An empty one holds no/// allocation.#[derive(Clone, PartialEq)]@@ -354,6 +418,19 @@ impl ElementFacts {self.lists.custom_states()}+ /// The keys of the element that name something of its own.+ fn named_keys(&self) -> impl Iterator<Item = CarriedKey> + '_ {+ let (folded_tag, id) = (self.folded_tag(), self.id());+ [+ Some(CarriedKey::Tag(self.tag)),+ (!folded_tag.is_none()).then_some(CarriedKey::Tag(folded_tag)),+ (!id.is_none()).then_some(CarriedKey::Id(id)),+ ]+ .into_iter()+ .flatten()+ .chain(self.classes().iter().copied().map(CarriedKey::Class))+ }+/// The Bloom summary of the dispatch keys the element carries.#[must_use]pub(in crate::css::style) fn dispatch_bloom(&self, is_document_root: bool) -> u64 {@@ -606,11 +683,6 @@ impl ProjectionGeneration {.and_then(|shadow| shadow.host);Some(host.unwrap_or(parent))}-- /// The element slots whose committed rows may differ between `older` and this generation.- pub(in crate::css::style) fn committed_slots_changed_since(&self, older: &Self) -> Vec<std::ops::Range<usize>> {- self.committed.changed_rows_since(&older.committed)- }}/// What the selectors matched against an element read of its children's places among their siblings, and of itself@@ -707,6 +779,10 @@ pub(in crate::css::style) struct Projection {changes: Vec<(StyleNodeID, ElementChange)>,/// The elements the render owner's hover places in the hover state, beside the rows.hover: HoverOverlay,+ /// The keys the transactions note the elements of, as the hover seal last said.+ watched_keys: Option<Arc<WatchedKeys>>,+ /// The elements the transactions since the hover seal last asked moved the watched keys of.+ watched_key_writes: WrittenRows,/// The elements whose links were written since the last transaction was released: those the/// tree has to settle at the next barrier, and those it settled at the barrier of the/// transaction being taken.@@ -814,6 +890,9 @@ impl Projection {}bytes += sizer.arc_shallow(&self.text_assigned_slots) + map_bytes(&self.text_assigned_slots);bytes += sizer.arc_shallow(&self.disabled) + crate::heap_size::set_bytes(&self.disabled);+ if let Some(watched_keys) = &self.watched_keys {+ bytes += sizer.arc_shallow(watched_keys) + crate::heap_size::set_bytes(&watched_keys.keys);+ }if sizer.arc_shallow(&self.structural_flags) != 0 {bytes += crate::heap_size::ARC_HEADER_BYTES+ size_of::<StructuralFlagsColumn>()@@ -824,6 +903,7 @@ impl Projection {&self.written_since_seal,&self.links_written,&self.relations_written,+ &self.watched_key_writes,].iter().map(|rows| rows.heap_size())@@ -913,6 +993,7 @@ impl Projection {note_changes(pass, node, (before, after), hovered, &mut self.changes);}}+ self.note_watched_key_writes(&written);self.written.reuse(written);if self.flushing_seal {for index in 0..self.written_since_seal.nodes.len() {@@ -925,6 +1006,66 @@ impl Projection {}}+ /// Note those of the elements `written`, in the transaction being taken, that carried a watched key or carry one,+ /// and whose keys moved.+ fn note_watched_key_writes(&mut self, written: &[StyleNodeID]) {+ let Some(watched) = self.watched_keys.as_ref().filter(|watched| !watched.keys.is_empty()) else {+ return;+ };+ let sets = &*self.host_fact_sets;+ let carries = |row: Option<&Row>| row.is_some_and(|row| watched.carried_by(&row.facts, sets));+ let empty = ElementFacts::default();+ for &node in written {+ let slot = node.element_slot();+ let (before, after) = (self.before.get(slot), self.committed.get(slot));+ if (carries(before) || carries(after))+ && !carry_the_same_keys(+ before.map_or(&empty, |row| &row.facts),+ after.map_or(&empty, |row| &row.facts),+ sets,+ )+ {+ self.watched_key_writes.insert(node, slot);+ }+ }+ }++ /// Have the transactions from here on note the elements of `keys`, in place of those they noted till now.+ pub(in crate::css::style) fn watch_keys(&mut self, keys: Arc<WatchedKeys>) {+ self.watched_keys = Some(keys);+ }++ /// Whether the transactions noted the elements of `keys` all along since the hover seal said to.+ #[must_use]+ pub(in crate::css::style) fn watches_keys(&self, keys: &Arc<WatchedKeys>) -> bool {+ self.watched_keys+ .as_ref()+ .is_some_and(|watched| Arc::ptr_eq(watched, keys))+ }++ /// The elements noted since this was last asked, each once.+ pub(in crate::css::style) fn take_watched_key_writes(&mut self) -> Vec<StyleNodeID> {+ self.watched_key_writes.take()+ }++ /// Hand back the list [`Self::take_watched_key_writes`] answered, as the next one's allocation.+ pub(in crate::css::style) fn reuse_watched_key_writes(&mut self, writes: Vec<StyleNodeID>) {+ self.watched_key_writes.reuse(writes);+ }++ /// The elements that carry one of `keys` as the last transaction committed them.+ pub(in crate::css::style) fn committed_carriers_of<'a>(+ &'a self,+ keys: &'a WatchedKeys,+ ) -> impl Iterator<Item = StyleNodeID> + 'a {+ let sets = &*self.host_fact_sets;+ (1..self.slot_count).filter_map(move |slot| {+ let row = self.committed.get(slot)?;+ keys.carried_by(&row.facts, sets)+ .then(|| StyleNodeID::element(u32::try_from(slot).expect("element slot exceeds u32")))+ })+ }+fn forget_written_since_seal(&mut self) {let written = self.written_since_seal.take();self.written_since_seal.reuse(written);@@ -2122,6 +2263,13 @@ impl<'a> ProjectionRow<'a> {self.projection.backing_pseudo_kind(self.facts)}+ /// The keys of the element, which a compound can require of it.+ pub(in crate::css::style) fn carried_keys(self) -> impl Iterator<Item = CarriedKey> + 'a {+ self.facts+ .named_keys()+ .chain(backed_pseudo_element_key(self.facts, &self.projection.host_fact_sets))+ }+#[must_use]pub(in crate::css::style) fn id(self) -> StyleAtomID {self.facts.id()diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rsindex de8cfaedc03..1c1a6def35a 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs@@ -535,8 +535,9 @@ impl ProjectionWriter {self.host_fact_sets.get(id)}- /// Change the host facts of the element with `edit`, without noting its row written for a transaction: the host- /// facts are none of its selectors' facts. Answers the facts as they were.+ /// Change the host facts of the element with `edit`, without noting its row written for a transaction, but where+ /// the element-backed pseudo-element it stands for moves, which is a key of the element: the host facts change+ /// nothing a transaction reads. Answers the facts as they were.pub(in crate::css::style) fn edit_host_facts(&mut self,node: StyleNodeID,@@ -562,6 +563,9 @@ impl ProjectionWriter {.facts.host_facts = id;self.host_facts_written = true;+ if previous.associated_pseudo_kind() != set.associated_pseudo_kind() {+ self.note_written(node, slot);+ }previous}