Skip to content

Truly independent web browser

LibWeb: Keep hidden styles that a viewport change does not reach

Andreas Klingb0ec42566a3b
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs
index b381c37fb47..fd602205c11 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/demand.rs
@@ -15,7 +15,9 @@ use super::super::container_queries::ContainerVerdict;
use super::super::publication::{DemandedEngineRecord, RecordDemand, RecordDemandAnswer};
use super::super::*;
use super::live::Live;
-use super::records::{PseudoElementRecords, Record, RecordCells, Records, RetainedRecords};
+use super::records::{ChildImpact, MatchList, PseudoElementRecords, Record, RecordCells, Records, RetainedRecords};
+use super::rule_changes::RuleIndexChanges;
+use super::rules::RuleIndex;
use super::traversal::{self, DemandedPseudoElement, PassContext, PseudoElementRead};
use crate::css::style::input_types::StyleEnvironment;
use std::sync::Arc;
@@ -30,16 +32,29 @@ pub(super) struct DemandOverlay {
computed: HashSet<StyleNodeID>,
}
+/// What an element kept styled below one that is not displayed was computed from.
+struct KeptComputation {
+ /// The parts of the environment it read.
+ environment_reads: StyleEnvironment,
+ /// The entries of the rule index it matched.
+ matches: Option<MatchList>,
+ /// What it computed, which what inherits through it computed from.
+ record: Arc<Record>,
+}
+
/// 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 computed for an installation.
+ computed: HashMap<StyleNodeID, KeptComputation>,
/// 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.
+ /// pass found to compute from something else: what inherits through one computes anew, unless
+ /// it comes out as it was.
moved: HashSet<StyleNodeID>,
+ /// Those of `moved` where a hint reached the elements below too, however it comes out.
+ descendants_moved: HashSet<StyleNodeID>,
}
impl KeptHiddenRecords {
@@ -50,12 +65,55 @@ impl KeptHiddenRecords {
pub(super) fn note_environment_moved(&mut self, environment: StyleEnvironment) {
if !environment.is_empty() {
- self.computed.retain(|_, reads| !reads.intersects(environment));
+ self.moved.extend(
+ self.computed
+ .iter()
+ .filter(|(_, computation)| computation.environment_reads.intersects(environment))
+ .map(|(&node, _)| node),
+ );
}
}
+ /// Only the elements that matched an entry that left, or that match one that arrived, compute
+ /// anew where nothing but the conditions of rules moved, as the same width flips the rules of
+ /// a media query.
+ pub(super) fn note_rule_index_update(
+ &mut self,
+ state: &RetainedState,
+ index: &RuleIndex,
+ records: &RetainedRecords,
+ changes: &RuleIndexChanges,
+ ) {
+ if !changes.conditions_moved_alone {
+ self.forget();
+ return;
+ }
+ if self.computed.is_empty() {
+ return;
+ }
+ let numbering = changes.numbering(index);
+ let mut moves_element = changes.moves_element(state, index, records);
+ self.computed.retain(|&node, computation| {
+ computation.matches.as_ref().is_some_and(|matches| {
+ // NB: An element is computed anew rather than taking a list numbered anew.
+ !moves_element(node, matches)
+ && matches
+ .iter()
+ .all(|&entry| numbering.get(entry as usize).copied().flatten() == Some(entry))
+ })
+ });
+ }
+
pub(super) fn note_moved(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {
- self.moved.extend(nodes);
+ // NB: An element below no computation has nothing to compute anew.
+ if !self.computed.is_empty() {
+ self.moved.extend(nodes);
+ }
+ }
+
+ pub(super) fn note_descendants_moved(&mut self, node: StyleNodeID) {
+ self.moved.insert(node);
+ self.descendants_moved.insert(node);
}
/// Elements that left the tree compute nothing anymore.
@@ -70,6 +128,10 @@ impl KeptHiddenRecords {
self.computed.contains_key(&node)
}
+ pub(super) fn holds_computations(&self) -> bool {
+ !self.computed.is_empty()
+ }
+
/// Whether what `node` computes from stands, as `standing` remembers of the elements it
/// inherits through.
fn stands(
@@ -232,6 +294,9 @@ impl Live {
let records = Records::new(state, &cells, Some(&base));
let context = PassContext {
cache_audit: self.cache_audit,
+ // NB: What an element kept below one that is not displayed matched tells whether a change
+ // to the rules reaches it.
+ keeps_matches: true,
..PassContext::new(
state,
&self.index,
@@ -419,7 +484,7 @@ impl StyleEngine {
kept.sort_unstable();
kept.dedup();
live.note_hints_moved_kept_hidden_records();
- let mut installed = Vec::new();
+ let mut installed = self.settle_moved_kept_hidden();
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) {
@@ -430,34 +495,101 @@ impl StyleEngine {
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),
- };
+ if !stands {
+ installed.extend(self.demand_kept_chain(node));
}
- installed.extend_from_slice(&chain[first_stale..]);
}
if let Some(live) = self.retained.live_style.as_mut() {
live.kept_hidden_records.moved.clear();
+ live.kept_hidden_records.descendants_moved.clear();
}
installed.sort_unstable();
installed.dedup();
installed
}
+ /// Compute the elements an input reached anew, and let those whose children compute from what
+ /// they did stand for what inherits through them, as a viewport change reaches an element that
+ /// reads the viewport for a property its children do not inherit. Answers the elements to
+ /// install.
+ fn settle_moved_kept_hidden(&mut self) -> Vec<StyleNodeID> {
+ let live = self.retained.live_style.as_ref().expect("the engine owns the document");
+ let kept = &live.kept_hidden_records;
+ // NB: The chain of one element can compute another of them, so what each held is taken first.
+ let mut reached: Vec<(StyleNodeID, Arc<Record>)> = kept
+ .moved
+ .iter()
+ .filter(|node| !kept.descendants_moved.contains(node) && self.retained.projection.is_live(**node))
+ .filter_map(|&node| Some((node, kept.computed.get(&node)?.record.clone())))
+ .collect();
+ reached.sort_unstable_by_key(|&(node, _)| node);
+ let mut installed = Vec::new();
+ for (node, held) in reached {
+ let mut demanded = self.demand_kept_chain(node);
+ let state = &self.retained;
+ let live = state.live_style.as_ref().expect("the engine owns the document");
+ let kept = &live.kept_hidden_records;
+ // NB: An element a pass styles now holds its record, not one computed on demand.
+ let current = live.demanded_record(node).filter(|_| kept.computed(node)).cloned();
+ let holds_the_same = current.as_ref().is_some_and(|record| record.holds_the_same_as(&held));
+ let children_stand = current.as_ref().is_some_and(|record| {
+ record.pseudo_element_styles() == held.pseudo_element_styles()
+ && match ChildImpact::of_records(record, &held, &held.payloads) {
+ ChildImpact::None => true,
+ ChildImpact::ResetReaders => state.projection.style_children(node).all(|child| {
+ let record = kept.computed.get(&child).map(|computation| &computation.record);
+ record
+ .or_else(|| live.records.get(child))
+ .is_none_or(|record| !state.reads_parent_reset_values(child, record))
+ }),
+ _ => false,
+ }
+ });
+ let live = self.retained.live_style.as_mut().expect("the engine owns the document");
+ if let (Some(record), Some(computation)) = (current, live.kept_hidden_records.computed.get_mut(&node)) {
+ computation.record = record;
+ }
+ if children_stand {
+ live.kept_hidden_records.moved.remove(&node);
+ }
+ if holds_the_same {
+ demanded.retain(|&element| element != node);
+ }
+ installed.append(&mut demanded);
+ }
+ installed
+ }
+
+ /// Compute the elements of the chain of `node` that hold no current record, and note what they
+ /// computed from. Answers them.
+ fn demand_kept_chain(&mut self, node: StyleNodeID) -> Vec<StyleNodeID> {
+ let live = self.retained.live_style.as_ref().expect("the engine owns the document");
+ let (chain, first_stale) = live.demand_chain(&self.retained, node);
+ let Some(first_stale) = first_stale else {
+ return Vec::new();
+ };
+ 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 computation = live.demanded_record(element).and_then(|record| {
+ // NB: The sizes of containers and the places of elements among their siblings move with no
+ // input an element holding no record is told of.
+ let reads_container = live.demand_records().container_reads(element).is_some();
+ (!reads_container && !record.rare().reads.reads_sibling_position).then(|| KeptComputation {
+ environment_reads: record.rare().reads.environment_reads,
+ matches: live.demand_records().matches_of(element).cloned(),
+ record: record.clone(),
+ })
+ });
+ match computation {
+ Some(computation) => live.kept_hidden_records.computed.insert(element, computation),
+ None => live.kept_hidden_records.computed.remove(&element),
+ };
+ }
+ chain[first_stale..].to_vec()
+ }
+
/// The installation of the current record of `node`, computed on demand where it holds none, for a read of its
/// style, which installs it as a style update does. No transaction lies behind it, and the render side leaves the
/// element's boxes to the host. None for a document with no live style.
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs
index e8ce80f46dc..e7efa5dfc8b 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs
@@ -118,7 +118,7 @@ fn fork_bytes(engine: &StyleEngine) -> i64 {
/// What a fork of the smaller document allocates, and how much more per element a fork of one
/// twice as large does, at most.
-const FORK_BYTES: i64 = 5_100;
+const FORK_BYTES: i64 = 5_150;
const FORK_BYTES_PER_ELEMENT: f64 = 1.5;
#[test]
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
index 73e8ed0fa60..03ea320a782 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs
@@ -556,7 +556,7 @@ impl Live {
self.scratch.matched_declarations.forget();
}
let changes = state.projection.changes();
- if transaction.restyles_everything || !transaction.rule_changes.is_empty() {
+ if transaction.restyles_everything {
self.kept_hidden_records.forget();
} else {
self.kept_hidden_records.note_environment_moved(transaction.environment);
@@ -600,8 +600,13 @@ impl Live {
/// 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);
+ if !kept.holds_computations() {
+ return;
+ }
for &node in &hints.marked {
- if records.get(node).is_none() || kept.computed(node) || hints.get(node) & RESTYLE_DESCENDANTS != 0 {
+ if hints.get(node) & RESTYLE_DESCENDANTS != 0 {
+ kept.note_descendants_moved(node);
+ } else if records.get(node).is_none() || kept.computed(node) {
kept.note_moved([node]);
}
}
@@ -925,6 +930,10 @@ impl Live {
}
let program = &state.rules;
let kind_of = |rule| program.rule_version(rule).kind;
+ // NB: Only what a style rule declares reaches an element through what it matches.
+ if changes.rules.iter().any(|&rule| kind_of(rule) != RuleKind::Style) {
+ self.kept_hidden_records.forget();
+ }
let rules_of = |sheet| program.rules_in_sheet(sheet).into_iter().map(kind_of);
// The `@keyframes` rules that moved, and those that may decide another rule of their name
// where their scope was reordered.
@@ -2036,6 +2045,7 @@ impl Live {
fn rebuild_index(&mut self, state: &RetainedState) {
let index = RuleIndex::build(&state.rules, state.process_rule_indexes());
self.counts.note_index_build(&index);
+ self.kept_hidden_records.forget();
let renumbering = index.renumbering_from(&self.index);
self.records.renumber_matches(&renumbering);
self.hints.renumber_reasons(&renumbering);
@@ -2081,9 +2091,7 @@ 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()
+ if keyframes_moved.is_some()
|| self
.scratch
.matched_declarations_inputs
@@ -2117,6 +2125,8 @@ impl Live {
},
);
self.counts.note_index_update(&self.index, changes.arrived_entries);
+ self.kept_hidden_records
+ .note_rule_index_update(state, &self.index, &self.records, &changes);
if hinted && !changes.is_empty() {
let roots = rule_change_roots(state, root, &changes.scopes);
let hints = &mut self.hints;
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs
index b65e6f5cf9b..26c55f319f4 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs
@@ -545,6 +545,63 @@ const _: () = assert!(
);
impl ChildImpact {
+ /// Which children of an element computing `new` where it computed `old` compute anew, where
+ /// they inherited `inherited`.
+ pub(super) fn of_records(new: &Record, old: &Record, inherited: &crate::css::computed_values::StyleGroups) -> Self {
+ // An inherited longhand no group holds reaches the children through the table alone.
+ let ungrouped_inherited_moved = || {
+ crate::css::computed_values::StyleGroupMasks::get()
+ .ungrouped_inherited()
+ .iter()
+ .any(|&property| {
+ match (
+ computed::ViewLonghands::of_record(new).handle(property),
+ computed::ViewLonghands::of_record(old).handle(property),
+ ) {
+ (Some(new), Some(old)) => !crate::css::style_value::retained_style_values_equal(new, old),
+ (new, old) => new.is_some() != old.is_some(),
+ }
+ })
+ };
+ if new.payloads.current_color() != old.payloads.current_color()
+ || new.payloads.inherited_values() != old.payloads.inherited_values()
+ // https://drafts.csswg.org/css-color-adjust-1/#color-scheme-prop
+ // A child whose `color-scheme` is the one it inherits uses the scheme its parent uses.
+ || new.effective_color_scheme() != old.effective_color_scheme()
+ || new.facts().publication_dependency_flags() != old.facts().publication_dependency_flags()
+ || new.facts().display != old.facts().display
+ || ungrouped_inherited_moved()
+ // https://drafts.csswg.org/css-color-4/#resolving-other-colors
+ // A child inheriting a value that reads `currentcolor` resolves it against its own
+ // color, so the specified values the record retains reach the children where the
+ // colors they resolve to here did not move.
+ || crate::css::computed_longhand_table::inherited_inheritance_dependent_value_moved(
+ old.inheritance_dependent_values(),
+ new.inheritance_dependent_values(),
+ )
+ {
+ return ChildImpact::All;
+ }
+ let impact = match ChildImpact::of_groups(&new.payloads, inherited) {
+ ChildImpact::None
+ if crate::css::computed_longhand_table::non_inherited_inheritance_changes(
+ old.inheritance_dependent_values(),
+ new.inheritance_dependent_values(),
+ ) != 0 =>
+ {
+ Self::ResetReaders
+ }
+ impact => impact,
+ };
+ let stores_moved = !same_arc(new.custom_properties(), old.custom_properties())
+ || !same_arc(new.inheritable_custom_properties(), old.inheritable_custom_properties());
+ match (impact, stores_moved) {
+ (ChildImpact::None, true) => ChildImpact::CustomProperties,
+ (ChildImpact::ResetReaders, true) => ChildImpact::ResetReadersAndCustomProperties,
+ (impact, _) => impact,
+ }
+ }
+
/// Which children of an element moving from the groups `old` to `new` restyle: all of them
/// where an inherited group moved, and the ones reading their parent's values of properties
/// that do not inherit where another did.
@@ -1880,59 +1937,7 @@ impl<'a> Records<'a> {
if self.sampled_custom_properties(node).is_some() {
return ChildImpact::All;
}
- // An inherited longhand no group holds reaches the children through the table alone.
- let ungrouped_inherited_moved = || {
- crate::css::computed_values::StyleGroupMasks::get()
- .ungrouped_inherited()
- .iter()
- .any(|&property| {
- match (
- computed::ViewLonghands::of_record(new).handle(property),
- computed::ViewLonghands::of_record(old).handle(property),
- ) {
- (Some(new), Some(old)) => !crate::css::style_value::retained_style_values_equal(new, old),
- (new, old) => new.is_some() != old.is_some(),
- }
- })
- };
- if new.payloads.current_color() != old.payloads.current_color()
- || new.payloads.inherited_values() != old.payloads.inherited_values()
- // https://drafts.csswg.org/css-color-adjust-1/#color-scheme-prop
- // A child whose `color-scheme` is the one it inherits uses the scheme its parent uses.
- || new.effective_color_scheme() != old.effective_color_scheme()
- || new.facts().publication_dependency_flags() != old.facts().publication_dependency_flags()
- || new.facts().display != old.facts().display
- || ungrouped_inherited_moved()
- // https://drafts.csswg.org/css-color-4/#resolving-other-colors
- // A child inheriting a value that reads `currentcolor` resolves it against its own
- // color, so the specified values the record retains reach the children where the
- // colors they resolve to here did not move.
- || crate::css::computed_longhand_table::inherited_inheritance_dependent_value_moved(
- old.inheritance_dependent_values(),
- new.inheritance_dependent_values(),
- )
- {
- return ChildImpact::All;
- }
- let inherited = composition.map_or(&old.payloads, |view| view.payloads);
- let impact = match ChildImpact::of_groups(&new.payloads, inherited) {
- ChildImpact::None
- if crate::css::computed_longhand_table::non_inherited_inheritance_changes(
- old.inheritance_dependent_values(),
- new.inheritance_dependent_values(),
- ) != 0 =>
- {
- ChildImpact::ResetReaders
- }
- impact => impact,
- };
- let stores_moved = !same_arc(new.custom_properties(), old.custom_properties())
- || !same_arc(new.inheritable_custom_properties(), old.inheritable_custom_properties());
- match (impact, stores_moved) {
- (ChildImpact::None, true) => ChildImpact::CustomProperties,
- (ChildImpact::ResetReaders, true) => ChildImpact::ResetReadersAndCustomProperties,
- (impact, _) => impact,
- }
+ ChildImpact::of_records(new, old, composition.map_or(&old.payloads, |view| view.payloads))
}
/// Whether the records this pass computed for the highlight pseudo-elements of `node` hold
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_changes.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_changes.rs
index 7f8b7b20131..58cfff2c6ed 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_changes.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_changes.rs
@@ -49,7 +49,7 @@ pub(super) struct RuleIndexChanges {
regrouped: Vec<Regrouped>,
/// Whether the entries that died declared what their rules declare now, and those that stayed
/// stand as they stood, which lets what they decide be told from their rules.
- conditions_moved_alone: bool,
+ pub(super) conditions_moved_alone: bool,
/// The segments the update let go of, which alone still tell what their entries were.
pub(super) let_go: Vec<BoundSegment>,
}
@@ -122,6 +122,24 @@ impl<'a> RestyleWalk<'a> {
.collect()
}
+ /// Whether the element `node`, which matched the entries `matched`, matched an entry that left
+ /// or matches one that arrived.
+ fn moves_element(&mut self, node: StyleNodeID, matched: &[u32]) -> bool {
+ let changes = self.changes;
+ let Some(facts) = self.state.projection.facts(node) else {
+ return true;
+ };
+ if changes.left_any && matched.iter().any(|&entry| changes.before[entry as usize]) {
+ return true;
+ }
+ if changes.arrived_entries == 0 || facts.dispatch_bloom(true) & self.reaching_bits == 0 {
+ return false;
+ }
+ self.matches.clear();
+ let matching = self.matcher.match_element(node, facts, &self.filter, &mut self.matches);
+ matching.is_err() || !self.matches.is_empty()
+ }
+
fn restyle_of(&mut self, node: StyleNodeID) -> Option<Restyled> {
let changes = self.changes;
let facts = self.state.projection.facts(node)?;
@@ -330,6 +348,17 @@ impl RuleIndexChanges {
self.scopes.is_empty()
}
+ /// What tells whether the changes reach an element no walk of the records finds, by what it matched.
+ pub(super) fn moves_element<'a>(
+ &'a self,
+ state: &'a RetainedState,
+ index: &'a RuleIndex,
+ records: &'a RetainedRecords,
+ ) -> impl FnMut(StyleNodeID, &[u32]) -> bool + 'a {
+ let mut walk = RestyleWalk::new(self, state, index, records);
+ move |node, matched| walk.moves_element(node, matched)
+ }
+
/// Visit each element under `roots` in the flat tree that the changes restyle, or that takes new
/// matches alone, where `records` holds what the elements matched against the index before and
/// `index` is the updated one, in tree order.
diff --git a/Tests/LibWeb/Crash/CSS/kept-hidden-element-starts-reading-its-container.html b/Tests/LibWeb/Crash/CSS/kept-hidden-element-starts-reading-its-container.html
new file mode 100644
index 00000000000..02bbb399229
--- /dev/null
+++ b/Tests/LibWeb/Crash/CSS/kept-hidden-element-starts-reading-its-container.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<html class="test-wait">
+<style>
+ #container { container-type: inline-size; }
+ @container (min-width: 1px) {
+ .reads-container { color: green; }
+ }
+</style>
+<div id="container">
+ <div id="root" style="display: none">
+ <svg id="older"><linearGradient><stop /></linearGradient></svg>
+ </div>
+</div>
+<script>
+ const nextFrames = async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ };
+ (async () => {
+ // NB: The element made here is newer than the one moved below it, whose chain computes it first.
+ const newer = document.createElement("div");
+ const older = document.getElementById("older");
+ document.getElementById("root").appendChild(newer);
+ newer.appendChild(older);
+ await nextFrames();
+ older.classList.add("moved");
+ newer.classList.add("reads-container");
+ await nextFrames();
+ document.documentElement.classList.remove("test-wait");
+ })();
+</script>
+</html>
diff --git a/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-follows-media-rules-ref.html b/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-follows-media-rules-ref.html
new file mode 100644
index 00000000000..e649a8e2b72
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-follows-media-rules-ref.html
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<style>
+ div { height: 80px; width: 160px; }
+ svg { display: block; float: left; height: 40px; width: 40px; }
+</style>
+<div>
+ <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>
+</div>
diff --git a/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-settles-moved-elements-ref.html b/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-settles-moved-elements-ref.html
new file mode 100644
index 00000000000..6b0b916b09b
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/svg-resource-in-display-none-settles-moved-elements-ref.html
@@ -0,0 +1,7 @@
+<!DOCTYPE html>
+<style>
+ svg { display: inline-block; height: 40px; width: 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>
diff --git a/Tests/LibWeb/Ref/input/svg-resource-in-display-none-follows-media-rules.html b/Tests/LibWeb/Ref/input/svg-resource-in-display-none-follows-media-rules.html
new file mode 100644
index 00000000000..12b7827fcaf
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg-resource-in-display-none-follows-media-rules.html
@@ -0,0 +1,76 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/svg-resource-in-display-none-follows-media-rules-ref.html">
+<style>
+ iframe { border: 0; display: block; height: 80px; width: 100px; }
+</style>
+<iframe srcdoc='<!DOCTYPE html>
+<style>
+ body { margin: 0; }
+ svg.swatch { display: block; float: left; height: 40px; width: 40px; }
+ .arrives { stop-color: red; }
+ .leaves { stop-color: green; }
+ .inherits { stop-color: currentColor; }
+ #hidden-parent { color: red; }
+ @property --opacity { syntax: "<number>"; inherits: true; initial-value: 1; }
+ #reads-viewport { height: 10vw; }
+ #hands-down-viewport { --size: 1vw; --opacity: calc(100vw / 160px); }
+ .sized { fill: green; width: calc(var(--size) * 25); height: 40px; }
+ .opaque { stop-color: green; stop-opacity: var(--opacity); }
+ #reset-value { width: 25vw; }
+ .inherits-reset-value { height: 40px; width: inherit; }
+ @media (min-width: 150px) {
+ .arrives { stop-color: green; }
+ #hidden-parent { color: green; }
+ }
+ @media (max-width: 149px) {
+ .leaves { stop-color: red; }
+ }
+</style>
+<div style="display: none">
+ <svg>
+ <linearGradient id="arrives"><stop class="arrives" /></linearGradient>
+ <linearGradient id="leaves"><stop class="leaves" /></linearGradient>
+ </svg>
+ <div id="hidden-parent">
+ <svg><linearGradient id="inherits"><stop class="inherits" /></linearGradient></svg>
+ </div>
+ <div id="reads-viewport">
+ <svg><linearGradient id="below-reader"><stop class="leaves" /></linearGradient></svg>
+ </div>
+ <svg><clipPath id="reset-value"><rect class="inherits-reset-value" /></clipPath></svg>
+ <div id="hands-down-viewport">
+ <svg>
+ <linearGradient id="custom-property"><stop class="opaque" /></linearGradient>
+ <clipPath id="clip"><rect class="sized" /></clipPath>
+ </svg>
+ </div>
+</div>
+<svg class="swatch"><rect width="40" height="40" fill="url(#arrives)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#leaves)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#inherits)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#below-reader)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#custom-property)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="green" clip-path="url(#clip)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="green" clip-path="url(#reset-value)" /></svg>
+'></iframe>
+<script>
+ const nextFrames = async (target) => {
+ await new Promise(resolve => target.requestAnimationFrame(resolve));
+ await new Promise(resolve => target.requestAnimationFrame(resolve));
+ };
+ window.onload = async () => {
+ const iframe = document.querySelector("iframe");
+ await nextFrames(iframe.contentWindow);
+ // NB: The first width flips a rule that reaches no kept element, so their computations stand as the second
+ // flips the rules that do reach them.
+ iframe.contentDocument.styleSheets[0].insertRule("@media (min-width: 120px) { body { margin: 0; } }");
+ await nextFrames(iframe.contentWindow);
+ iframe.style.width = "130px";
+ await nextFrames(iframe.contentWindow);
+ iframe.style.width = "160px";
+ await nextFrames(iframe.contentWindow);
+ document.documentElement.classList.remove("reftest-wait");
+ };
+</script>
+</html>
diff --git a/Tests/LibWeb/Ref/input/svg-resource-in-display-none-settles-moved-elements.html b/Tests/LibWeb/Ref/input/svg-resource-in-display-none-settles-moved-elements.html
new file mode 100644
index 00000000000..ee46d9ae017
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/svg-resource-in-display-none-settles-moved-elements.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+<link rel="match" href="../expected/svg-resource-in-display-none-settles-moved-elements-ref.html">
+<style>
+ svg.swatch { display: inline-block; height: 40px; width: 40px; }
+ .current-color { stop-color: currentColor; }
+ .position-reader { stop-color: green; stop-opacity: calc(2 - sibling-index()); }
+</style>
+<div style="display: none">
+ <svg>
+ <linearGradient id="position"><stop id="first-stop" stop-color="red" /><stop class="position-reader" /></linearGradient>
+ </svg>
+</div>
+<div id="shown-later" style="display: none">
+ <div>
+ <div id="hidden-again" style="color: red; display: none">
+ <svg><linearGradient id="shown-gradient"><stop class="current-color" /></linearGradient></svg>
+ </div>
+ </div>
+</div>
+<div id="order-root" style="display: none">
+ <svg id="older"><linearGradient><stop /></linearGradient></svg>
+</div>
+<svg class="swatch"><rect width="40" height="40" fill="url(#position)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#shown-gradient)" /></svg>
+<svg class="swatch"><rect width="40" height="40" fill="url(#order-gradient)" /></svg>
+<script>
+ const nextFrames = async () => {
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ };
+ (async () => {
+ // NB: The element made here is newer than the one moved below it.
+ const newer = document.createElement("div");
+ newer.style.color = "red";
+ newer.innerHTML = '<svg><linearGradient id="order-gradient"><stop class="current-color" /></linearGradient></svg>';
+ const older = document.getElementById("older");
+ document.getElementById("order-root").appendChild(newer);
+ newer.appendChild(older);
+ await nextFrames();
+
+ document.getElementById("first-stop").remove();
+ await nextFrames();
+
+ document.getElementById("shown-later").style.display = "block";
+ await nextFrames();
+ document.getElementById("hidden-again").style.color = "green";
+ await nextFrames();
+
+ older.classList.add("moved");
+ newer.style.color = "green";
+ await nextFrames();
+
+ document.documentElement.classList.remove("reftest-wait");
+ })();
+</script>
+</html>