Skip to content

Truly independent web browser

LibWeb: Stop demanding kept hidden styles that still stand

Andreas Klingf0666265b990
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs
index 19959de2bfd..b381c37fb47 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs
@@ -17,6 +17,7 @@ use super::super::*;
use super::live::Live;
use super::records::{PseudoElementRecords, Record, RecordCells, Records, RetainedRecords};
use super::traversal::{self, DemandedPseudoElement, PassContext, PseudoElementRead};
+use crate::css::style::input_types::StyleEnvironment;
use std::sync::Arc;
/// The records computed on demand in one generation of the engine.
@@ -29,6 +30,82 @@ pub(super) struct DemandOverlay {
computed: HashSet<StyleNodeID>,
}
+/// Which records of the elements that keep their style below an element that is not displayed
+/// still stand. No pass styles these elements or notes what they read, so an installation computes
+/// them on demand, and nothing but what is noted here can move how they compute.
+#[derive(Default)]
+pub(in super::super) struct KeptHiddenRecords {
+ /// The elements computed for an installation, with the parts of the environment they read.
+ computed: HashMap<StyleNodeID, StyleEnvironment>,
+ /// The elements an input or a hint reached since the last installation, or whose children a
+ /// pass found to compute from something else: what inherits through one computes anew.
+ moved: HashSet<StyleNodeID>,
+}
+
+impl KeptHiddenRecords {
+ /// Every element computes anew, as for a change to the rules.
+ pub(super) fn forget(&mut self) {
+ self.computed.clear();
+ }
+
+ pub(super) fn note_environment_moved(&mut self, environment: StyleEnvironment) {
+ if !environment.is_empty() {
+ self.computed.retain(|_, reads| !reads.intersects(environment));
+ }
+ }
+
+ pub(super) fn note_moved(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {
+ self.moved.extend(nodes);
+ }
+
+ /// Elements that left the tree compute nothing anymore.
+ pub(super) fn note_left(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {
+ for node in nodes {
+ self.computed.remove(&node);
+ }
+ }
+
+ /// Whether `node` is one this holds a computation of.
+ pub(super) fn computed(&self, node: StyleNodeID) -> bool {
+ self.computed.contains_key(&node)
+ }
+
+ /// Whether what `node` computes from stands, as `standing` remembers of the elements it
+ /// inherits through.
+ fn stands(
+ &self,
+ state: &RetainedState,
+ records: &RetainedRecords,
+ node: StyleNodeID,
+ standing: &mut HashMap<StyleNodeID, bool>,
+ ) -> bool {
+ if !self.computed.contains_key(&node) {
+ return false;
+ }
+ let mut walked: SmallVec<[StyleNodeID; 32]> = SmallVec::new();
+ let mut current = Some(node);
+ let mut stands = true;
+ while let Some(element) = current {
+ if let Some(&known) = standing.get(&element) {
+ stands = known;
+ break;
+ }
+ walked.push(element);
+ // NB: The sampled values of animations move with no input.
+ if self.moved.contains(&element)
+ || state.projection.adjustment_facts(element) & bridge::element_adjustment_fact::HAS_ANIMATIONS != 0
+ || !(self.computed.contains_key(&element) || records.get(element).is_some())
+ {
+ stands = false;
+ break;
+ }
+ current = state.projection.inheritance_parent(element);
+ }
+ standing.extend(walked.into_iter().map(|element| (element, stands)));
+ stands
+ }
+}
+
/// What a computation of an element's style for a clock frame found: its record, with those of the
/// pseudo-elements it generates a box for.
enum DerivedElement {
@@ -341,22 +418,41 @@ impl StyleEngine {
let mut kept = std::mem::take(&mut live.kept_hidden);
kept.sort_unstable();
kept.dedup();
+ live.note_hints_moved_kept_hidden_records();
let mut installed = Vec::new();
+ let mut standing = HashMap::default();
for node in kept {
if !self.retained.projection.is_live(node) || !self.retained.keeps_style_in_display_none_subtree(node) {
continue;
}
- let live = self.retained.live_style.as_ref().expect("the engine owns the document");
- let (chain, first_stale) = live.demand_chain(&self.retained, node);
- if let Some(live) = self.retained.live_style.as_mut() {
- live.kept_hidden.push(node);
- }
- let Some(first_stale) = first_stale else {
+ let mut live = self.retained.live_style.take().expect("the engine owns the document");
+ live.kept_hidden.push(node);
+ let stands = live
+ .kept_hidden_records
+ .stands(&self.retained, &live.records, node, &mut standing);
+ let demanded = (!stands).then(|| live.demand_chain(&self.retained, node));
+ self.retained.live_style = Some(live);
+ let Some((chain, Some(first_stale))) = demanded else {
continue;
};
self.demand_element(node, false);
+ let live = self.retained.live_style.as_mut().expect("the engine owns the document");
+ for &element in &chain[first_stale..] {
+ let environment_reads = live.demanded_record(element).and_then(|record| {
+ // NB: The sizes of containers move with no input.
+ let reads_container = live.demand_records().container_reads(element).is_some();
+ (!reads_container).then(|| record.rare().reads.environment_reads)
+ });
+ match environment_reads {
+ Some(reads) => live.kept_hidden_records.computed.insert(element, reads),
+ None => live.kept_hidden_records.computed.remove(&element),
+ };
+ }
installed.extend_from_slice(&chain[first_stale..]);
}
+ if let Some(live) = self.retained.live_style.as_mut() {
+ live.kept_hidden_records.moved.clear();
+ }
installed.sort_unstable();
installed.dedup();
installed
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
index 58a76184ba3..73e8ed0fa60 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
@@ -155,6 +155,9 @@ pub(in super::super) struct Live {
/// is not displayed: the host asks for the styles of the SVG resources such a subtree holds,
/// which paint wherever they are referenced, and of its elements with animations.
pub(super) kept_hidden: Vec<StyleNodeID>,
+ /// Which records computed for `kept_hidden` still stand, so that an installation computes
+ /// only those something could have moved.
+ pub(super) kept_hidden_records: ForkReset<super::demand::KeptHiddenRecords>,
}
/// What passes and the invalidation of transactions work in, which holds nothing between them.
@@ -436,6 +439,15 @@ struct MatchedDeclarationsInputs {
}
impl MatchedDeclarationsInputs {
+ /// Whether these inputs differ from `other` in nothing but the size of the viewport, which the
+ /// records reading it name.
+ fn same_besides_viewport(&self, other: &Self) -> bool {
+ Self {
+ viewport: other.viewport,
+ ..*self
+ } == *other
+ }
+
fn of(inputs: &super::super::bridge::FfiDocumentStyleComputationInputs) -> Self {
Self {
initial_style: InitialStyleInputs::of(inputs),
@@ -544,6 +556,18 @@ impl Live {
self.scratch.matched_declarations.forget();
}
let changes = state.projection.changes();
+ if transaction.restyles_everything || !transaction.rule_changes.is_empty() {
+ self.kept_hidden_records.forget();
+ } else {
+ self.kept_hidden_records.note_environment_moved(transaction.environment);
+ }
+ self.kept_hidden_records
+ .note_moved(transaction.style_inputs.iter().map(|&(node, _)| node));
+ self.kept_hidden_records
+ .note_left(changes.iter().filter_map(|&(node, change)| match change {
+ ElementChange::Relations(_, None) => Some(node),
+ _ => None,
+ }));
if transaction.has_no_element_inputs() && changes.is_empty() && transaction.rule_changes.is_empty() {
return;
}
@@ -571,6 +595,18 @@ impl Live {
self.bump(LiveField::InvalidationNanoseconds, started.elapsed().as_nanos() as u64);
}
+ /// Note what no pass tells of the hints: a pass styles the elements holding a record and tells
+ /// whether their children compute from something else, but not those below an element that is
+ /// not displayed, or what restyling descendants reaches.
+ pub(super) fn note_hints_moved_kept_hidden_records(&mut self) {
+ let (hints, records, kept) = (&self.hints, &self.records, &mut *self.kept_hidden_records);
+ for &node in &hints.marked {
+ if records.get(node).is_none() || kept.computed(node) || hints.get(node) & RESTYLE_DESCENDANTS != 0 {
+ kept.note_moved([node]);
+ }
+ }
+ }
+
/// Whether the next pass has anything to do: an input since the last pass can restyle any
/// element or moved the rules, or something hinted an element.
/// The scratch an installation works in.
@@ -768,6 +804,7 @@ impl Live {
/// so what a record names is compared with what it would name now.
fn note_counter_style_environment_moved(&mut self, state: &RetainedState) {
self.scratch.matched_declarations.forget();
+ self.kept_hidden_records.forget();
self.restyle_records_where(state, |_, target, record| {
record.rare().counter_style_environment_identity
!= state.values_counter_style_environment_identity(target, |property| record.effective_value(property))
@@ -833,6 +870,7 @@ impl Live {
}
self.scratch.matched_declarations.forget();
let raw: HashSet<usize> = names.iter().map(ak::Utf16FlyString::raw_identity).collect();
+ self.kept_hidden_records.forget();
let texts: Vec<std::borrow::Cow<'_, [u16]>> = names.iter().map(ak::Utf16FlyString::to_utf16).collect();
self.restyle_records_where(state, |records, target, record| {
let node = target.node();
@@ -943,6 +981,7 @@ impl Live {
/// substitute something that may.
fn note_custom_functions_moved(&mut self, state: &RetainedState) {
self.scratch.matched_declarations.forget();
+ self.kept_hidden_records.forget();
self.restyle_records_where(state, |_, _, record| {
record.rare().custom_property_reads == LonghandCustomPropertyReads::Any
|| record.custom_declarations().is_some_and(|declarations| {
@@ -2022,6 +2061,7 @@ impl Live {
let state: &RetainedState = retained;
let started = Instant::now();
self.generation += 1;
+ self.note_hints_moved_kept_hidden_records();
let slot_count = state.projection.element_slot_count();
self.hints.reserve(slot_count);
self.scratch.cells.reserve(slot_count);
@@ -2041,6 +2081,16 @@ impl Live {
let reordered_scopes = std::mem::take(&mut self.reordered_scopes);
let layered_scopes = std::mem::take(&mut self.layered_scopes);
let matched_declarations_inputs = MatchedDeclarationsInputs::of(&state.document_style_computation_inputs);
+ if rebuilds_index
+ || updates_index
+ || keyframes_moved.is_some()
+ || self
+ .scratch
+ .matched_declarations_inputs
+ .is_none_or(|inputs| !inputs.same_besides_viewport(&matched_declarations_inputs))
+ {
+ self.kept_hidden_records.forget();
+ }
if rebuilds_index
|| updates_index
|| self.scratch.matched_declarations_inputs != Some(matched_declarations_inputs)
@@ -2330,6 +2380,19 @@ impl Live {
&waiting_restyling_descendants,
);
self.keep_deferred_hints(&state.projection, &statistics.deferred, &waiting);
+ self.kept_hidden_records
+ .note_moved(statistics.children_moved.iter().copied());
+ // NB: A pass tells nothing of the children of an element that is not displayed, as it walks none of them.
+ let records = &self.records;
+ self.kept_hidden_records.note_moved(
+ statistics
+ .styled
+ .iter()
+ .copied()
+ .filter(|&node| records.get(node).is_none_or(|record| !record.is_displayed())),
+ );
+ self.kept_hidden_records
+ .note_moved(statistics.moved_custom_properties.iter().copied());
let styled = Instant::now();
self.bump(LiveField::Passes, 1);
self.bump(LiveField::FullPasses, u64::from(!hinted));
@@ -4153,6 +4216,7 @@ impl StyleEngine {
.style_preorder(root)
.filter(|&node| self.retained.keeps_style_in_display_none_subtree(node))
.collect(),
+ kept_hidden_records: Default::default(),
}));
self.retained
.cold_passes
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
index 8e2d661002d..31153c7b2e9 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
@@ -465,6 +465,8 @@ pub(super) struct Statistics {
pub(super) moved_custom_properties: Vec<StyleNodeID>,
/// How many of those it styled differently than before, in what their children compute from.
pub(super) changed_elements: u64,
+ /// Those elements.
+ pub(super) children_moved: Vec<StyleNodeID>,
/// The children of elements whose records moved beneath the composition of their animations,
/// with the hints the pass kept for them, which the next pass restyles once the host composed
/// the animations over the new records.
@@ -2705,6 +2707,9 @@ fn style_trees<'scope, 'a: 'scope>(
false => ChildImpact::None,
};
scratch.statistics.changed_elements += u64::from(impact != ChildImpact::None);
+ if impact != ChildImpact::None {
+ scratch.statistics.children_moved.push(node);
+ }
let children = match hint & RESTYLE_DESCENDANTS != 0 {
true => {
RESTYLE_SELF
@@ -3121,6 +3126,7 @@ impl Statistics {
statistics.styled.extend(round.styled);
statistics.moved_custom_properties.extend(round.moved_custom_properties);
statistics.changed_elements += round.changed_elements;
+ statistics.children_moved.extend(round.children_moved);
statistics.deferred.extend(round.deferred);
statistics
.restyled_for_pseudo_elements
diff --git a/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-restyles-on-change-ref.html b/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-restyles-on-change-ref.html
new file mode 100644
index 00000000000..39b274c5d58
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-restyles-on-change-ref.html
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<style>
+ svg { display: inline-block; width: 40px; height: 40px; }
+</style>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
+<svg><rect width="40" height="40" fill="green" /></svg>
diff --git a/Tests/LibWeb/Ref/input/svg-resource-in-display-none-restyles-on-change.html b/Tests/LibWeb/Ref/input/svg-resource-in-display-none-restyles-on-change.html
new file mode 100644
index 00000000000..90d40d1fef0
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg-resource-in-display-none-restyles-on-change.html
@@ -0,0 +1,95 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/svg-resource-in-display-none-restyles-on-change-ref.html">
+<style>
+ #custom-property { --stop: red; }
+ #inherited { color: red; }
+ .stop-custom-property { stop-color: var(--stop); }
+ .stop-current-color { stop-color: currentColor; }
+ .stop-red { stop-color: red; }
+ .attribute[data-green] .stop-red { stop-color: green; }
+ #sibling.green ~ svg .stop-red { stop-color: green; }
+ .has:has(.green) .stop-red { stop-color: green; }
+ svg.swatch { display: inline-block; width: 40px; height: 40px; }
+</style>
+<div id="custom-property">
+ <div style="display: none">
+ <svg><linearGradient id="custom-property-gradient"><stop class="stop-custom-property" /></linearGradient></svg>
+ </div>
+</div>
+<div id="inherited">
+ <div style="display: none">
+ <svg><linearGradient id="inherited-gradient"><stop class="stop-current-color" /></linearGradient></svg>
+ </div>
+</div>
+<div id="attribute" class="attribute" style="display: none">
+ <svg><linearGradient id="attribute-gradient"><stop class="stop-red" /></linearGradient></svg>
+</div>
+<div style="display: none">
+ <span id="sibling"></span>
+ <svg><linearGradient id="sibling-gradient"><stop class="stop-red" /></linearGradient></svg>
+</div>
+<div class="has" style="display: none">
+ <span id="has-target"></span>
+ <svg><linearGradient id="has-gradient"><stop class="stop-red" /></linearGradient></svg>
+</div>
+<div style="display: none">
+ <svg><linearGradient id="inline-gradient"><stop id="inline-stop" style="stop-color: red" /></linearGradient></svg>
+</div>
+<div style="display: none">
+ <svg><linearGradient id="rule-gradient"><stop id="rule-stop" /></linearGradient></svg>
+</div>
+<div id="hidden-root-custom-property" style="display: none; --stop: red">
+ <svg><linearGradient id="hidden-root-custom-property-gradient"><stop class="stop-custom-property" /></linearGradient></svg>
+</div>
+<div id="hidden-root-color" style="display: none; color: red">
+ <svg><linearGradient id="hidden-root-color-gradient"><stop class="stop-current-color" /></linearGradient></svg>
+</div>
+<div id="moved-to" style="--stop: green"></div>
+<div id="moved-from" style="--stop: red; display: none">
+ <svg id="moved-svg"><linearGradient id="moved-gradient"><stop class="stop-custom-property" /></linearGradient></svg>
+</div>
+<svg class="swatch"><rect width="40" height="40" fill="url(#custom-property-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#inherited-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#attribute-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#sibling-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#has-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#inline-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#rule-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#hidden-root-custom-property-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#hidden-root-color-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#moved-gradient)" /></svg>
+<script>
+ const nextFrames = async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ };
+ // NB: Each change gets frames of its own, and the one restyling every hidden element, the new rule, goes first:
+ // it would otherwise cover for the others.
+ const changes = [
+ () => document.styleSheets[0].insertRule("#rule-stop { stop-color: green; }"),
+ () => document.getElementById("custom-property").style.setProperty("--stop", "green"),
+ () => (document.getElementById("inherited").style.color = "green"),
+ () => document.getElementById("attribute").setAttribute("data-green", ""),
+ () => document.getElementById("sibling").classList.add("green"),
+ () => document.getElementById("has-target").classList.add("green"),
+ () => (document.getElementById("inline-stop").style.stopColor = "green"),
+ () => document.getElementById("hidden-root-custom-property").style.setProperty("--stop", "green"),
+ () => (document.getElementById("hidden-root-color").style.color = "green"),
+ () => {
+ const hiddenInNewPlace = document.createElement("div");
+ hiddenInNewPlace.style.display = "none";
+ document.getElementById("moved-to").appendChild(hiddenInNewPlace);
+ hiddenInNewPlace.appendChild(document.getElementById("moved-svg"));
+ },
+ ];
+ (async () => {
+ await nextFrames();
+ for (const change of changes) {
+ change();
+ await nextFrames();
+ }
+ document.documentElement.classList.remove("reftest-wait");
+ })();
+</script>
+</html>