Truly independent web browser
LibWeb: Let children wait to arrive below a display:none element
Andreas Klingd7db06bf4bca
diff --git a/Libraries/LibWeb/Animations/Animatable.cpp b/Libraries/LibWeb/Animations/Animatable.cppindex 57abb30a1bc..cf6e93d5317 100644--- a/Libraries/LibWeb/Animations/Animatable.cpp+++ b/Libraries/LibWeb/Animations/Animatable.cpp@@ -226,6 +226,7 @@ void Animatable::associate_with_animation(GC::Ref<Animation> animation)CSS::record_element_animations_changed(as<DOM::Element>(*this));as<DOM::Element>(*this).change_associated_animation_count_in_subtree(1);+ CSS::record_element_associated_with_animation(as<DOM::Element>(*this));as<DOM::Element>(*this).document().associate_with_animation(animation);animation->did_associate_with_target();diff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.cpp b/Libraries/LibWeb/CSS/StyleEngineBridge.cppindex bb805902dbb..4a16ad8eb92 100644--- a/Libraries/LibWeb/CSS/StyleEngineBridge.cpp+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.cpp@@ -286,6 +286,40 @@ void StyleEngine::note_pending_arrivals(size_t count)m_pending_arrival_count += count;}+void StyleEngine::note_waiting_arrivals_may_arrive()+{+ request_frame_for_first_recorded_input(*this, m_style_computer);+ ++m_pending_arrival_count;+}++void StyleEngine::note_waiting_arrivals_if_keys_moved(Layout::BegunRead const& read)+{+ if (m_may_have_waiting_children && m_waiting_children_checked_against_keys_version != relational_arrival_keys(read).version)+ note_waiting_arrivals_may_arrive();+}++namespace {++#include <LibWeb/SelectorStateFactsGenerated.inc>++}++StyleEngine::RelationalArrivalKeys const& StyleEngine::relational_arrival_keys(Layout::BegunRead const& read)+{+ auto keys = StyleEngineFFI::style_engine_relational_arrival_keys(host(), &read);+ if (keys.version == m_relational_arrival_keys.version)+ return m_relational_arrival_keys;+ m_relational_arrival_keys.version = keys.version;+ m_relational_arrival_keys.reached_by_any_arrival = keys.reached_by_any_arrival;+ m_relational_arrival_keys.names.clear();+ for (size_t i = 0; i < keys.name_count; ++i)+ m_relational_arrival_keys.names.set(keys.names[i]);+ m_relational_arrival_keys.state_pseudo_classes.clear();+ for (size_t i = 0; i < keys.state_count; ++i)+ m_relational_arrival_keys.state_pseudo_classes.append(pseudo_classes_by_state_fact[keys.states[i]]);+ return m_relational_arrival_keys;+}+void StyleEngine::record_tree_delta(StyleEngineFFI::FfiTreeDelta const& delta){flush_deferred_geometry_transaction_before_non_replayable_input(*this, m_style_computer);@@ -395,7 +429,7 @@ void StyleEngine::submit_recorded_input()m_style_computer->document().assign_slottables_if_needed();Layout::ForcedReadScope read { render_document() };if (m_style_computer) {- take_in_pending_style_arrivals(m_style_computer->document());+ take_in_pending_style_arrivals(m_style_computer->document(), HiddenChildArrivals::MayWait);publish_pending_element_features(*this, *m_style_computer);}StyleEngineFFI::style_engine_submit_staged_input(host());diff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.h b/Libraries/LibWeb/CSS/StyleEngineBridge.hindex c560faa7804..ca62abf22e1 100644--- a/Libraries/LibWeb/CSS/StyleEngineBridge.h+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.h@@ -20,6 +20,7 @@#include <LibGC/Cell.h>#include <LibGC/Ptr.h>#include <LibWeb/CSS/ParkedRandomBaseValues.h>+#include <LibWeb/CSS/PseudoClass.h>#include <LibWeb/CSS/StyleEngineIdentifiers.h>#include <LibWeb/CSS/StyleRecordID.h>#include <LibWeb/ComputedValuesRustFFI.h>@@ -325,6 +326,32 @@ public:// next submitted.void note_pending_arrivals(size_t count);void forget_pending_arrivals() { m_pending_arrival_count = 0; }+ [[nodiscard]] bool has_pending_arrivals() const { return m_pending_arrival_count > 0; }+ // Children that wait to arrive in a display:none subtree may have to arrive now. Nothing is recorded until the+ // input is next submitted, so this can be noted while a style update applies its reactions.+ void note_waiting_arrivals_may_arrive();++ // What an element's arrival has to carry to reach the anchor of a `:has()` argument: one of `names` as the raw+ // identity of its tag, ID, class or attribute name, or the state of one of `state_pseudo_classes`.+ struct RelationalArrivalKeys {+ u64 version { 0 };+ bool reached_by_any_arrival { false };+ HashTable<FlatPtr> names;+ Vector<PseudoClass> state_pseudo_classes;+ };+ RelationalArrivalKeys const& relational_arrival_keys(Layout::BegunRead const&);+ // The keys as the engine last said, which may have moved since.+ RelationalArrivalKeys const& last_relational_arrival_keys() const { return m_relational_arrival_keys; }+ // The keys the children waiting in display:none subtrees were last found to carry none of.+ Optional<u64> waiting_children_checked_against_keys_version() const { return m_waiting_children_checked_against_keys_version; }+ void set_waiting_children_checked_against_keys_version(u64 version) { m_waiting_children_checked_against_keys_version = version; }+ // Whether children waited in a display:none subtree as of the last take-in that looked at them, or were released+ // since.+ bool may_have_waiting_children() const { return m_may_have_waiting_children; }+ void set_may_have_waiting_children(bool value) { m_may_have_waiting_children = value; }+ // A rule a style update compiled can move the keys the waiting children were looked at against, and the+ // children have to be looked at again before the update ends.+ void note_waiting_arrivals_if_keys_moved(Layout::BegunRead const&);[[nodiscard]] bool has_pending_transaction(Layout::BegunRead const& read) const;[[nodiscard]] bool has_deferred_geometry_transaction(Layout::BegunRead const& read) const;// Whether a geometry read deferred a transaction that has_deferred_geometry_transaction() may still find, which the@@ -444,6 +471,9 @@ private:HashTable<StyleNodeID> m_style_nodes_with_animations_changed_beside_flown_transaction;HashTable<StyleNodeID> m_parents_whose_children_changed_beside_flown_transaction;size_t m_pending_arrival_count { 0 };+ RelationalArrivalKeys m_relational_arrival_keys;+ Optional<u64> m_waiting_children_checked_against_keys_version;+ bool m_may_have_waiting_children { false };bool m_css_transitions_may_observe_style_changes { false };mutable bool m_geometry_read_deferred_transaction { false };StyleAtomID m_html_element_namespace;diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cppindex 172488e9165..6ede30a6b33 100644--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp@@ -37,6 +37,7 @@#include <LibWeb/HTML/HTMLHeadingElement.h>#include <LibWeb/HTML/HTMLImageElement.h>#include <LibWeb/HTML/HTMLInputElement.h>+#include <LibWeb/HTML/HTMLLinkElement.h>#include <LibWeb/HTML/HTMLObjectElement.h>#include <LibWeb/HTML/HTMLSlotElement.h>#include <LibWeb/HTML/HTMLTableCellElement.h>@@ -373,26 +374,167 @@ static void mark_style_arrival_pending(DOM::Node& node, StyleEngine& style_engin}}-// Whether a subtree already waiting to arrive holds the node. An element without an identity is always in one.-static bool waits_to_arrive_with_an_ancestor(DOM::Node& node)+// Whether a subtree already waiting to arrive holds the node, or the children of an element in a display:none subtree+// that wait do. An element without an identity is always in one or the other. Where `holder` is given, the walk goes on+// to the nearest element with an identity, and sets it there if that element's children wait.+static bool waits_to_arrive_with_an_ancestor(DOM::Node& node, DOM::Element** holder = nullptr){+ bool waits = false;for (auto* ancestor = node.parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {- if (ancestor->style_arrival_pending())+ auto* element = as_if<DOM::Element>(*ancestor);+ if (element && element->style_node_id() != no_style_node) {+ if (!element->child_style_arrivals_wait())+ return waits;+ if (holder)+ *holder = element;return true;- if (auto* element = as_if<DOM::Element>(*ancestor))- return element->style_node_id() == no_style_node;+ }+ if (element || ancestor->style_arrival_pending()) {+ waits = true;+ if (!holder)+ return true;+ continue;+ }if (!is<DOM::ShadowRoot>(*ancestor))+ return waits;+ }+ return waits;+}++// The element that arrived alone in a display:none subtree whose waiting children the node is, or is inside of.+static DOM::Element* element_whose_waiting_children_hold(DOM::Node& node)+{+ DOM::Element* holder = nullptr;+ (void)waits_to_arrive_with_an_ancestor(node, &holder);+ return holder;+}++// Whether a name answers to one of the keys. Tag and attribute names are keyed folded, as are IDs and classes in quirks+// mode, and folding a name that is folded already allocates nothing.+static bool name_answers_to_keys(Utf16FlyString const& name, bool folds, StyleEngine::RelationalArrivalKeys const& keys)+{+ return keys.names.contains(name.raw_identity()) || (folds && keys.names.contains(name.to_ascii_lowercase().raw_identity()));+}++// Whether an element can wait to arrive below one in a display:none subtree. A `:has()` argument could reach its anchor+// through the element's keys, and an element that is an SVG element, a style sheet's owner, a slot, a shadow host or in+// the top layer has an effect beyond its subtree, or a place in the engine's tree other than its parent's child, even+// while it is hidden. An animated element keeps its style while hidden.+static bool element_can_wait_to_arrive(DOM::Element& element, StyleEngine::RelationalArrivalKeys const& keys)+{+ if (keys.reached_by_any_arrival || is<SVG::SVGElement>(element) || element.is_html_style_element() || is<HTML::HTMLLinkElement>(element)+ || is<HTML::HTMLSlotElement>(element) || element.shadow_root() || element.in_top_layer() || element.has_associated_animations())+ return false;+ if (!keys.names.is_empty()) {+ auto folds_ids_and_classes = element.document().in_quirks_mode();+ if (name_answers_to_keys(element.local_name(), true, keys))+ return false;+ if (auto const& id = element.id(); id.has_value() && name_answers_to_keys(*id, folds_ids_and_classes, keys))+ return false;+ if (any_of(element.class_names(), [&](auto const& class_name) { return name_answers_to_keys(class_name, folds_ids_and_classes, keys); }))+ return false;+ bool attribute_answers = false;+ element.for_each_attribute([&](DOM::QualifiedName const& name, Utf16String const&) {+ attribute_answers = attribute_answers || name_answers_to_keys(name.local_name(), true, keys);+ });+ if (attribute_answers)return false;}- return false;+ return !any_of(keys.state_pseudo_classes, [&](auto pseudo_class) { return SelectorMatching::element_matches_state(element, pseudo_class); });}-static void record_node_connected(DOM::Node& node, StyleEngine& style_engine)+// The children that waited become subtrees waiting to arrive like any other. Whoever releases them outside of a take-in+// notes that they arrive as the input is next submitted.+static void release_waiting_children(DOM::Element& element){- if (waits_to_arrive_with_an_ancestor(node))- style_engine.note_pending_arrivals(1);+ element.set_child_style_arrivals_wait(false);+ element.set_descendant_style_arrival_pending(true);+ auto mark = [](DOM::Node& child) { child.set_style_arrival_pending(true); };+ if (auto shadow_root = element.shadow_root())+ mark(*shadow_root);+ for (auto* child = element.first_child(); child; child = child->next_sibling()) {+ if (is<DOM::Element>(*child) || is<DOM::Text>(*child))+ mark(*child);+ }+}++static bool s_taking_in_pending_style_arrivals = false;++// Children that waited may have to arrive as the input is next submitted. A style update or a take-in only notes it.+// Script records it as it records an insertion, which the transaction a geometry read deferred must not be waiting for.+static void note_waiting_children_may_arrive(StyleEngine& style_engine, DOM::Document const& document)+{+ if (s_taking_in_pending_style_arrivals || document.is_in_style_stabilization_epoch())+ style_engine.note_waiting_arrivals_may_arrive();else+ style_engine.note_pending_arrivals(1);+}++// Releases the waiting children outside of a take-in, which they arrive at as the input is next submitted.+static void release_waiting_children_until_submitted(DOM::Element& element, StyleEngine& style_engine)+{+ release_waiting_children(element);+ note_waiting_children_may_arrive(style_engine, element.document());+}++// Releases the waiting children that hold the node, if any do.+static void release_waiting_children_holding(DOM::Node& node, StyleEngine& style_engine)+{+ if (auto* holder = element_whose_waiting_children_hold(node))+ release_waiting_children_until_submitted(*holder, style_engine);+}++// What joins children that wait in a display:none subtree is looked at as it connects, against the keys they were last+// looked at against: keys that moved since have them all looked at again anyway. Only a document where children may+// wait walks past the nearest node waiting to arrive to look for them.+static void record_node_connected(DOM::Node& node, StyleEngine& style_engine)+{+ DOM::Element* holder = nullptr;+ if (!waits_to_arrive_with_an_ancestor(node, style_engine.may_have_waiting_children() ? &holder : nullptr)) {mark_style_arrival_pending(node, style_engine);+ return;+ }+ if (!holder) {+ style_engine.note_pending_arrivals(1);+ return;+ }+ if (auto* element = as_if<DOM::Element>(node); element && !element_can_wait_to_arrive(*element, style_engine.last_relational_arrival_keys()))+ release_waiting_children_until_submitted(*holder, style_engine);+}++// A name or state an element waiting in a display:none subtree takes is not recorded, as the element arrives with what+// it is then. One that a `:has()` argument may reach it by could let it reach that argument's anchor, so the children+// waiting with it arrive. The keys the children were last looked at against are the ones to ask: keys that moved since+// have them all looked at again anyway.+enum class NamesFold {+ InQuirksMode,+ Always,+};++static void record_waiting_element_names_changed(DOM::Element& element, ReadonlySpan<Utf16FlyString> names, NamesFold names_fold = NamesFold::InQuirksMode)+{+ auto* style_engine = style_engine_for(element);+ if (!style_engine || element.style_node_id() != no_style_node)+ return;+ auto const& keys = style_engine->last_relational_arrival_keys();+ auto folds = names_fold == NamesFold::Always || element.document().in_quirks_mode();+ if (keys.reached_by_any_arrival || (!keys.names.is_empty() && any_of(names, [&](auto const& name) { return name_answers_to_keys(name, folds, keys); })))+ release_waiting_children_holding(element, *style_engine);+}++static void record_waiting_element_state_changed(DOM::Element& element, PseudoClass pseudo_class)+{+ auto* style_engine = style_engine_for(element);+ if (!style_engine || element.style_node_id() != no_style_node)+ return;+ auto const& keys = style_engine->last_relational_arrival_keys();+ if (keys.reached_by_any_arrival || keys.state_pseudo_classes.contains_slow(pseudo_class))+ release_waiting_children_holding(element, *style_engine);+}++void record_waiting_element_classes_changed(DOM::Element& element)+{+ record_waiting_element_names_changed(element, element.class_names());}void record_element_connected(DOM::Element& element)@@ -454,10 +596,16 @@ void record_subtree_connecting(DOM::Node& root)mark_style_arrival_pending(root, *style_engine);}+// A subtree waiting to arrive, and whether its root arrives alone, its children waiting on in a display:none subtree.+struct PendingArrivalRoot {+ GC::Ref<DOM::Node> node;+ bool children_wait { false };+};+// Every node in the subtrees waiting to arrive, in tree order, takes its identity, and every element records its// arrival. The subtrees are taken in together, so each identity is assigned before the first arrival is recorded:// an arrival names its parent and siblings, and a sibling that waited in another subtree has arrived by then.-static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<GC::Ref<DOM::Node>> roots)+static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<PendingArrivalRoot> roots){auto& style_computer = document.style_computer();auto& style_engine = style_computer.style_engine();@@ -499,8 +647,13 @@ static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<GC::Re}};for (auto const& root : roots) {- ensure_dom_order_parent_identity(root->parent(), style_engine);- for_each_shadow_including_inclusive_descendant_with_scope(*root, tree_scope_of(root->root()), collect);+ ensure_dom_order_parent_identity(root.node->parent(), style_engine);+ if (root.children_wait) {+ collect(root.node, tree_scope_of(root.node->root()));+ root.node->set_child_style_arrivals_wait(true);+ } else {+ for_each_shadow_including_inclusive_descendant_with_scope(root.node, tree_scope_of(root.node->root()), collect);+ }}if (!text_arrivals.is_empty()) {@@ -583,47 +736,177 @@ static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<GC::Re// The insertion that connected a subtree marked it for the layout tree build under the identity it did not have// yet, so the mark is made here, as the insertion would have made it.for (auto const& root : roots) {- auto const* parent = root->parent();+ auto const* parent = root.node->parent();if (parent && (parent->is_html_style_element() || parent->is_svg_style_element()) && !parent->has_layout_box())continue;- root->set_needs_layout_tree_update(true, DOM::SetNeedsLayoutTreeUpdateReason::NodeInsertBefore);+ root.node->set_needs_layout_tree_update(true, DOM::SetNeedsLayoutTreeUpdateReason::NodeInsertBefore);+ }+}++// Whether the element's parent is in a display:none subtree an animation cannot be holding visible: it or an ancestor+// holds a display:none style and runs no animation. The element's own display does not hide its children from+// selectors its siblings match, such as `:empty + *`, so it is not the one asked about.+static bool parent_is_in_display_none_subtree_no_animation_reveals(DOM::Element const& element)+{+ for (auto const* ancestor = element.parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {+ auto const* ancestor_element = as_if<DOM::Element>(*ancestor);+ if (!ancestor_element)+ continue;+ if (ancestor_element->installed_style().display_is_none())+ return !ancestor_element->has_associated_animations();}+ return false;}-// The subtrees waiting to arrive, in tree order, found along the marks their ancestors carry. The marks are cleared on-// the way: a subtree that left the tree before this walk leaves marks behind that nothing waits under.-static void collect_pending_style_arrival_roots(DOM::Node& node, Vector<GC::Ref<DOM::Node>, 16>& roots)+// Whether every descendant of the element can wait to arrive.+static bool descendants_can_wait_to_arrive(DOM::Element& element, StyleEngine::RelationalArrivalKeys const& keys){- node.set_descendant_style_arrival_pending(false);+ if (element.associated_animation_count_in_subtree() != 0)+ return false;+ bool can_wait = true;+ element.for_each_shadow_including_descendant([&](DOM::Node& node) {+ auto* descendant = as_if<DOM::Element>(node);+ if (!descendant || element_can_wait_to_arrive(*descendant, keys))+ return TraversalDecision::Continue;+ can_wait = false;+ return TraversalDecision::Break;+ });+ return can_wait;+}++// Decides, along one take-in, which elements arrive alone in a display:none subtree, their children waiting.+class HiddenChildArrivalDecision {+public:+ HiddenChildArrivalDecision(DOM::Document& document, HiddenChildArrivals hidden_child_arrivals)+ : m_document(document)+ , m_style_engine(document.style_computer().style_engine())+ , m_hidden_child_arrivals(hidden_child_arrivals)+ {+ }++ ~HiddenChildArrivalDecision()+ {+ if (m_keys)+ m_style_engine.set_waiting_children_checked_against_keys_version(m_keys->version);+ }++ // Whether the children of `node`, which arrives now, can wait.+ bool children_of_arrival_can_wait(DOM::Node& node)+ {+ auto* element = as_if<DOM::Element>(node);+ if (!element || !may_wait() || !element->has_children() || element->shadow_root() || is<HTML::HTMLSlotElement>(*element)+ || !parent_is_in_display_none_subtree_no_animation_reveals(*element))+ return false;+ return descendants_can_wait_to_arrive(*element, keys());+ }++ // Whether the children of `element`, which wait, can go on waiting.+ bool waiting_children_can_go_on_waiting(DOM::Element& element)+ {+ if (!may_wait() || element.shadow_root() || !parent_is_in_display_none_subtree_no_animation_reveals(element))+ return false;+ // The children were looked at against these keys, as was whatever joined them or changed a name or state of+ // theirs since.+ if (m_style_engine.waiting_children_checked_against_keys_version() == keys().version)+ return true;+ return descendants_can_wait_to_arrive(element, keys());+ }++private:+ bool may_wait() const { return m_hidden_child_arrivals == HiddenChildArrivals::MayWait; }++ StyleEngine::RelationalArrivalKeys const& keys()+ {+ if (!m_keys)+ m_keys = &m_style_engine.relational_arrival_keys(Layout::ForcedReadScope { *m_document });+ return *m_keys;+ }++ GC::Ref<DOM::Document> m_document;+ StyleEngine& m_style_engine;+ HiddenChildArrivals m_hidden_child_arrivals;+ StyleEngine::RelationalArrivalKeys const* m_keys { nullptr };+};++// The subtrees waiting to arrive, in tree order, found along the marks their ancestors carry, and whether anything+// still waits below the node once they arrive. The marks are cleared on the way, and kept on the path to children+// that go on waiting in a display:none subtree: a subtree that left the tree before this walk leaves marks behind that+// nothing waits under.+static bool collect_pending_style_arrival_roots(DOM::Node& node, Vector<PendingArrivalRoot, 16>& roots, HiddenChildArrivalDecision& decision)+{+ bool waits_below = false;auto visit = [&](DOM::Node& child) {- if (child.style_arrival_pending())- roots.append(child);- else if (child.descendant_style_arrival_pending())- collect_pending_style_arrival_roots(child, roots);+ if (auto* element = as_if<DOM::Element>(child); element && element->child_style_arrivals_wait()) {+ if (decision.waiting_children_can_go_on_waiting(*element)) {+ waits_below = true;+ return;+ }+ release_waiting_children(*element);+ }+ if (child.style_arrival_pending()) {+ auto children_wait = decision.children_of_arrival_can_wait(child);+ roots.append({ child, children_wait });+ waits_below |= children_wait;+ } else if (child.descendant_style_arrival_pending()) {+ waits_below |= collect_pending_style_arrival_roots(child, roots, decision);+ }};if (auto* element = as_if<DOM::Element>(node); element && element->shadow_root())visit(*element->shadow_root());for (auto* child = node.first_child(); child; child = child->next_sibling())visit(*child);+ node.set_descendant_style_arrival_pending(waits_below);+ return waits_below;}-static bool s_taking_in_pending_style_arrivals = false;--void take_in_pending_style_arrivals(DOM::Document& document)+void take_in_pending_style_arrivals(DOM::Document& document, HiddenChildArrivals hidden_child_arrivals){if (s_taking_in_pending_style_arrivals)return;+ auto& style_engine = document.style_computer().style_engine();// Nodes that waited and left the tree again are counted too, and nothing is left of them to take in.- document.style_computer().style_engine().forget_pending_arrivals();+ auto arrivals_were_noted = style_engine.has_pending_arrivals();+ style_engine.forget_pending_arrivals();if (!document.descendant_style_arrival_pending())return;+ // Children that wait in a display:none subtree go on waiting until a node connects, something notes they may have+ // to arrive, or the keys they were looked at against move. Until then, the marks on the path to them lead to nothing+ // that has to arrive.+ if (!arrivals_were_noted && hidden_child_arrivals == HiddenChildArrivals::MayWait+ && style_engine.waiting_children_checked_against_keys_version() == style_engine.relational_arrival_keys(Layout::ForcedReadScope { document }).version)+ return;+ // Only the arrivals of a tracked tree record which children wait.+ if (!document.style_engine_tracks_tree())+ hidden_child_arrivals = HiddenChildArrivals::TakeIn;TemporaryChange taking_in { s_taking_in_pending_style_arrivals, true };- Vector<GC::Ref<DOM::Node>, 16> roots;- collect_pending_style_arrival_roots(document, roots);+ Vector<PendingArrivalRoot, 16> roots;+ {+ HiddenChildArrivalDecision decision { document, hidden_child_arrivals };+ style_engine.set_may_have_waiting_children(collect_pending_style_arrival_roots(document, roots, decision));+ }if (!roots.is_empty() && document.style_engine_tracks_tree())record_subtree_arrivals(document, roots);}+void record_element_associated_with_animation(DOM::Element& element)+{+ auto* style_engine = style_engine_for(element);+ if (!style_engine)+ return;+ // An animated element keeps its style while hidden, so it cannot wait to arrive itself.+ if (element.style_node_id() == no_style_node)+ release_waiting_children_holding(element, *style_engine);+ // An animation can hold a display:none element visible, revealing whatever waited to arrive below it.+ if (element.child_style_arrivals_wait() || element.descendant_style_arrival_pending())+ note_waiting_children_may_arrive(*style_engine, element.document());+}++void record_waiting_children_may_be_revealed(DOM::Element& element)+{+ if (auto* style_engine = style_engine_for(element))+ note_waiting_children_may_arrive(*style_engine, element.document());+}+// A node that is no element hovers the element it is inside of.static DOM::Element const* hovered_element_of(DOM::Node const* node){@@ -1314,9 +1597,15 @@ void record_top_layer_changed(DOM::Document& document)auto const& members = document.top_layer_elements();Vector<StyleNodeID, 8> identities;identities.ensure_capacity(members.size());+ auto& style_engine = document.style_computer().style_engine();for (auto const& member : members) {- if (member->style_node_id() != no_style_node)+ if (member->style_node_id() != no_style_node) {identities.unchecked_append(member->style_node_id());+ continue;+ }+ // A member is rendered whatever display:none subtree it is in, so the children it waits with arrive.+ if (member->is_connected())+ release_waiting_children_holding(*member, style_engine);}StyleEngineFFI::style_engine_set_top_layer_elements(document.style_computer().style_engine().host(), identities.span());}@@ -1871,6 +2160,8 @@ void record_subtree_disconnecting(DOM::Node& root)Vector<StyleNodeID, 64> departing_texts;auto disconnect_element = [&](DOM::Node& node, TreeScopeID tree_scope) {if (auto* element = as_if<DOM::Element>(node)) {+ // Children that waited leave with the element, which takes them in again as a whole wherever it arrives.+ element->set_child_style_arrivals_wait(false);record_element_disconnecting(*element, tree_scope, &node == &root ? PreviousSiblings::Arrived : PreviousSiblings::Departed);} else if (auto* shadow_root = as_if<DOM::ShadowRoot>(node)) {shadow_roots.append(*shadow_root);@@ -1895,6 +2186,12 @@ void record_shadow_root_connected(DOM::ShadowRoot& shadow_root)auto* style_engine = style_engine_for(shadow_root);if (!style_engine)return;+ // A host's shadow tree takes the place of its children in the flat tree, so children that waited below it arrive,+ // as do those a host waits with: a shadow host cannot wait to arrive.+ if (auto* host = shadow_root.host(); host && host->child_style_arrivals_wait())+ release_waiting_children_until_submitted(*host, *style_engine);+ else if (host && host->style_node_id() == no_style_node)+ release_waiting_children_holding(*host, *style_engine);// The root retakes its place here rather than when whatever next needs it happens to ask. A// scope's root is how a sheet attached to that scope is bounded, and an empty shadow tree has no// child whose relations would ask for it, so the scope would be left naming a node that has been@@ -2545,6 +2842,15 @@ void record_stylesheet_detached(StyleSheetState& sheet, DOM::Node& document_or_sbool can_record_element_state_change(DOM::Element& element){+ // A state an element waiting in a display:none subtree takes matters where a `:has()` argument may reach the+ // element by a state, for record_element_state_changed() to release the children waiting with it.+ if (element.style_node_id() == no_style_node) {+ auto* style_engine = style_engine_for(element);+ if (!style_engine)+ return false;+ auto const& keys = style_engine->last_relational_arrival_keys();+ return (keys.reached_by_any_arrival || !keys.state_pseudo_classes.is_empty()) && element_whose_waiting_children_hold(element);+ }return style_engine_for_published(element);}@@ -2561,12 +2867,14 @@ void move_style_hover(DOM::Document& document, GC::Ptr<DOM::Node> node)void record_element_state_changed(DOM::Element& element, PseudoClass pseudo_class, bool new_value){- auto* style_engine = style_engine_for_published(element);- if (!style_engine)- return;auto fact = state_fact_for(pseudo_class);if (!fact.has_value())return;+ auto* style_engine = style_engine_for_published(element);+ if (!style_engine) {+ record_waiting_element_state_changed(element, pseudo_class);+ return;+ }style_engine->record_state_delta({.node = element.style_node_id().value(),@@ -2603,8 +2911,11 @@ static void record_feature(void record_element_id_changed(DOM::Element& element, Optional<Utf16FlyString> const& old_value, Optional<Utf16FlyString> const& new_value){auto* style_engine = style_engine_for_identified(element);- if (!style_engine)+ if (!style_engine) {+ if (new_value.has_value())+ record_waiting_element_names_changed(element, { &*new_value, 1 });return;+ }auto atom_of = [&](Optional<Utf16FlyString> const& value) -> StyleAtomID {return value.has_value() ? intern_id_or_class_atom(*style_engine, element, *value) : 0;@@ -2666,8 +2977,11 @@ void record_element_class_list_changed(DOM::Element& element, ReadonlySpan<Utf16void record_element_attribute_changed(DOM::Element& element, Utf16FlyString const& name, Optional<Utf16FlyString> const& namespace_uri, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value){auto* style_engine = style_engine_for_identified(element);- if (!style_engine)+ if (!style_engine) {+ if (!old_value.has_value() && new_value.has_value())+ record_waiting_element_names_changed(element, { &name, 1 }, NamesFold::Always);return;+ }if (!old_value.has_value() && !new_value.has_value())return;diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.h b/Libraries/LibWeb/CSS/StyleEngineInput.hindex 421c3e3c9e5..3f728715b3c 100644--- a/Libraries/LibWeb/CSS/StyleEngineInput.h+++ b/Libraries/LibWeb/CSS/StyleEngineInput.h@@ -57,7 +57,27 @@ WEB_API void record_text_connected(DOM::Text&);// Gives every node waiting to arrive its style node identity and records its arrival, in tree// order. Whatever reads the style engine, or a connected node's identity, calls this first.-WEB_API void take_in_pending_style_arrivals(DOM::Document&);+//+// The children of an element in a display:none subtree have no boxes, and their styles serve only a+// read of them or the subtree's reveal. Where nothing outside the subtree can observe them either,+// the element may arrive alone and leave its children waiting, until the subtree is revealed, a+// `:has()` argument could reach them, or the caller is one that names them.+enum class HiddenChildArrivals {+ TakeIn,+ MayWait,+};+WEB_API void take_in_pending_style_arrivals(DOM::Document&, HiddenChildArrivals = HiddenChildArrivals::TakeIn);++// Called once an element whose children, or some descendant's, wait to arrive in a display:none+// subtree takes a style that is not display:none, or an animation, either of which may reveal them.+WEB_API void record_waiting_children_may_be_revealed(DOM::Element&);++// Called once an element is associated with an animation, which can hold a display:none element visible and keeps the+// style of an element even while it is hidden.+WEB_API void record_element_associated_with_animation(DOM::Element&);++// Called once the classes of a connected element without a style node identity change.+WEB_API void record_waiting_element_classes_changed(DOM::Element&);// Called whenever a text node's data is replaced. The mirror carries the characters, which the layout tree build// renders, and whether they are nothing but ASCII whitespace.diff --git a/Libraries/LibWeb/CSS/UpdateStyle.cpp b/Libraries/LibWeb/CSS/UpdateStyle.cppindex 08048ab9187..2f03be6490b 100644--- a/Libraries/LibWeb/CSS/UpdateStyle.cpp+++ b/Libraries/LibWeb/CSS/UpdateStyle.cpp@@ -256,7 +256,9 @@ StyleEngineFFI::FfiTakenStyleTransaction StyleEngineFFI::web_css_take_style_tranbool StyleEngineFFI::web_css_has_pending_style_transaction(StyleReactionApplication* application){- return application->document->style_computer().style_engine().has_pending_transaction(application->read);+ auto& style_engine = application->document->style_computer().style_engine();+ style_engine.note_waiting_arrivals_if_keys_moved(application->read);+ return style_engine.has_pending_transaction(application->read);}void StyleEngineFFI::web_css_note_style_update_has_reactions(StyleReactionApplication* application)@@ -703,7 +705,7 @@ static void update_style(Layout::BegunRead const& read, DOM::Document& document,// since the last update under the identities they take here.// NB: What connected beside the transaction that flew is the next transaction's.if constexpr (!drains_flown_transaction)- take_in_pending_style_arrivals(document);+ take_in_pending_style_arrivals(document, HiddenChildArrivals::MayWait);StyleUpdateScope style_update_scope { document.style_computer() };document.begin_style_stabilization_epoch();@@ -884,6 +886,7 @@ static bool update_style_for_element(Layout::BegunRead const& read, DOM::Documen// chain has style throughout, or a display:none element stops the read above every element without.if (mode != StyleUpdateMode::Normal&& !abstract_element.pseudo_element().has_value()+ && abstract_element.element().style_node_id() != 0&& document_has_no_pending_style_work(read, document)&& embedding_document_chain_has_no_pending_style_or_layout_work(document)) {StyleReactionApplication application { read, document };@@ -892,7 +895,11 @@ static bool update_style_for_element(Layout::BegunRead const& read, DOM::Documenreturn answer_style_read(abstract_element, answer);}- take_in_pending_style_arrivals(document);+ // A read of an element in a display:none subtree may be answered by the children waiting to arrive there.+ auto const& read_element = abstract_element.element();+ auto read_may_need_waiting_children = document.descendant_style_arrival_pending()+ && read_element.has_inclusive_ancestor_with_display_none_ignoring_animations();+ take_in_pending_style_arrivals(document, read_may_need_waiting_children ? HiddenChildArrivals::TakeIn : HiddenChildArrivals::MayWait);StyleUpdateScope style_update_scope { document.style_computer() };// Refresh computed properties for an abstract element. An ordinary read first consumes the complete exact// reaction batch. A reentrant layout read leaves that transaction untouched and walks the flat-tree inheritancediff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 6e03ab72b05..8254ef67cfd 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -5377,6 +5377,11 @@ void Element::replace_style_record(CSS::StyleRecordID style_record_identity)layout_node->set_style_record_identity(m_installed_style, held_before);if (style_node_id() != 0)CSS::StyleEngineFFI::style_engine_set_held_style_record(document().style_computer().style_engine().host(), style_node_id(), style_record_identity.value());+ // Children that wait to arrive in a display:none subtree may be revealed as the subtree's root, or an element+ // between it and them, stops being display:none.+ if ((child_style_arrivals_wait() || descendant_style_arrival_pending()) && m_installed_style && !m_installed_style.display_is_none()+ && (!held_before || held_before.display_is_none()))+ CSS::record_waiting_children_may_be_revealed(*this);// The resources an SVG graphics element's `mask`, `clip-path`, `fill` and `stroke` name are published beside its// attributes for the layout tree build to resolve, so they follow every record the element takes.if (is<SVG::SVGGraphicsElement>(*this) && !!style_record_identity)@@ -6436,6 +6441,8 @@ void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16if (old_style_engine_classes.has_value())CSS::record_element_class_list_changed(*this, *old_style_engine_classes, m_classes);+ else if (is_connected())+ CSS::record_waiting_element_classes_changed(*this);} else if (local_name == HTML::AttributeNames::style) {// https://drafts.csswg.org/cssom/#ref-for-cssstyledeclaration-updating-flagif (m_inline_style && m_inline_style->is_updating())diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.hindex 4db7c0079d4..647c74b1bbc 100644--- a/Libraries/LibWeb/DOM/Node.h+++ b/Libraries/LibWeb/DOM/Node.h@@ -389,6 +389,10 @@ public:void set_style_arrival_pending(bool value) { m_style_arrival_pending = value; }bool descendant_style_arrival_pending() const { return m_descendant_style_arrival_pending; }void set_descendant_style_arrival_pending(bool value) { m_descendant_style_arrival_pending = value; }+ // Whether this element arrived alone in a display:none subtree, its children waiting to arrive until something+ // could observe them. See CSS::take_in_pending_style_arrivals().+ bool child_style_arrivals_wait() const { return m_child_style_arrivals_wait; }+ void set_child_style_arrivals_wait(bool value) { m_child_style_arrivals_wait = value; }// Mirrors the slottable's assigned slot; see SlottableMixin::set_assigned_slot().bool has_assigned_slot() const { return m_has_assigned_slot; }@@ -703,6 +707,7 @@ protected:bool m_inside_blocking_wheel_event_handler : 1 { false };bool m_style_arrival_pending : 1 { false };bool m_descendant_style_arrival_pending : 1 { false };+ bool m_child_style_arrivals_wait : 1 { false };bool m_has_spelling_markers : 1 { false };u32 m_child_index_generation { 1 };// The slot of the node directory that names the node by its unique id, or 0 before anything asked for the id.diff --git a/Libraries/LibWeb/Rust/src/css/style/atoms.rs b/Libraries/LibWeb/Rust/src/css/style/atoms.rsindex ddee5a27884..c1466907f13 100644--- a/Libraries/LibWeb/Rust/src/css/style/atoms.rs+++ b/Libraries/LibWeb/Rust/src/css/style/atoms.rs@@ -411,6 +411,24 @@ impl DocumentAtoms {reclaimable}+ /// The raw identity of the name each of `atoms` was interned from, a qualified atom's being its name's, or none+ /// where one was interned from text rather than from a name.+ pub(super) fn raw_identities_of(&self, atoms: impl IntoIterator<Item = StyleAtomID>) -> Option<Vec<usize>> {+ let mut wanted: HashSet<StyleAtomID> = atoms.into_iter().collect();+ for (&(_, name), atom) in &self.qualified {+ if wanted.remove(atom) {+ wanted.insert(StyleAtomID(name));+ }+ }+ let mut raws = Vec::with_capacity(wanted.len());+ for (&raw, atom) in &self.raw {+ if raw < TEXT_KEY_FLOOR && wanted.remove(atom) {+ raws.push(raw);+ }+ }+ wanted.is_empty().then_some(raws)+ }+/// A sweep marks everything live whatever it reclaims, so the next one waits until the table has doubled: its cost/// spreads over as many new atoms as this one left live.fn schedule_next_sweep(&mut self) {diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rsindex 7ee1ca46a3d..9902ca3aa15 100644--- a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs+++ b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs@@ -1196,6 +1196,44 @@ pub extern "C" fn style_engine_has_pending_transaction(host: &DocumentHost, read}}+/// What an element's arrival has to carry to reach the anchor of a `:has()` argument, and where that is: the raw+/// identities of the tags, IDs, classes and attribute names, and the states, any of which reaches one. The spans hold+/// until the host next asks.+#[repr(C)]+pub struct FfiRelationalArrivalKeys {+ pub version: u64,+ pub reached_by_any_arrival: bool,+ pub names: *const usize,+ pub name_count: usize,+ pub states: *const u8,+ pub state_count: usize,+}++#[unsafe(no_mangle)]+pub extern "C" fn style_engine_relational_arrival_keys(+ host: &DocumentHost,+ read: &BegunRead,+) -> FfiRelationalArrivalKeys {+ let (version, keys) = host.known_relational_arrival_keys().unwrap_or_else(|| {+ with_engine(read, host, |engine| {+ engine.resolve_relational_arrival_keys();+ (+ engine.relational_arrival_keys_version(),+ Arc::clone(engine.relational_arrival_keys()),+ )+ })+ });+ let keys = host.lend_relational_arrival_keys(keys);+ FfiRelationalArrivalKeys {+ version,+ reached_by_any_arrival: keys.reached_by_any_arrival,+ names: keys.names.as_ptr(),+ name_count: keys.names.len(),+ states: keys.states.as_ptr(),+ state_count: keys.states.len(),+ }+}+/// Whether the engine defers any element style input, which the host knows without asking where it wrote nothing since/// its last job.#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/css/style/index.rs b/Libraries/LibWeb/Rust/src/css/style/index.rsindex 06e6f01afb0..675aaf52caa 100644--- a/Libraries/LibWeb/Rust/src/css/style/index.rs+++ b/Libraries/LibWeb/Rust/src/css/style/index.rs@@ -1539,7 +1539,7 @@ impl FeatureKey {}}- fn atom(self) -> Option<StyleAtomID> {+ pub(crate) fn atom(self) -> Option<StyleAtomID> {match self {Self::Part(atom)| Self::CustomState(atom)diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rsindex 1c71b6f8ead..6868d36f1de 100644--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs@@ -368,6 +368,7 @@ impl RetainedState {{return reusable;}+ self.note_relational_arrival_keys(&compiled);let program = self.programs.add(compiled);self.selector_programs_need_sweep |= reusable.is_some();self.programs.settle_memory(&mut self.memory);@@ -392,6 +393,66 @@ impl RetainedState {self.attribute_value_text_requirements_version += 1;}+ /// Record what an arrival has to carry to reach the anchor of one of `program`'s `:has()` arguments.+ pub(super) fn note_relational_arrival_keys(&mut self, program: &SelectorProgram) {+ if !program.contains_relational_selector() {+ return;+ }+ for entry in 0..program.entries().len() {+ program.collect_transpose_entry_points(entry, |site| {+ if site.anchor.is_some() && !self.relational_arrival_keys.keys.contains(&site.key) {+ self.unresolved_relational_arrival_keys.insert(site.key);+ }+ });+ }+ }++ /// Starts the keys over from `keys`, as a sweep that reclaimed some of their atoms leaves them.+ pub(super) fn replace_relational_arrival_keys(&mut self, keys: HashSet<RoutingKey>) {+ self.relational_arrival_keys = Arc::default();+ self.unresolved_relational_arrival_keys = keys;+ self.relational_arrival_keys_version += 1;+ }++ /// Resolves the keys rules added since the host last learned them to what it compares an element's names and+ /// states with. The atom table is scanned once for all of them, however many rules added one.+ pub(crate) fn resolve_relational_arrival_keys(&mut self) {+ if self.unresolved_relational_arrival_keys.is_empty() {+ return;+ }+ let mut resolved = (*self.relational_arrival_keys).clone();+ let mut name_atoms = Vec::new();+ for key in std::mem::take(&mut self.unresolved_relational_arrival_keys) {+ if !resolved.keys.insert(key) {+ continue;+ }+ match key {+ RoutingKey::TagName(atom)+ | RoutingKey::Id(atom)+ | RoutingKey::Class(atom)+ | RoutingKey::AttributeName(atom) => name_atoms.push(atom),+ RoutingKey::State(fact) => resolved.states.push(fact as u8),+ _ => resolved.reached_by_any_arrival = true,+ }+ }+ match self.atoms.raw_identities_of(name_atoms) {+ Some(raws) => resolved.names.extend(raws),+ None => resolved.reached_by_any_arrival = true,+ }+ self.relational_arrival_keys = Arc::new(resolved);+ self.relational_arrival_keys_version += 1;+ }++ /// Moves whenever what an arrival has to carry to reach a `:has()` anchor does, once resolved.+ pub(crate) fn relational_arrival_keys_version(&self) -> u64 {+ self.relational_arrival_keys_version+ }++ /// What an arrival has to carry to reach a `:has()` anchor, as last resolved.+ pub(crate) fn relational_arrival_keys(&self) -> &Arc<RelationalArrivalKeys> {+ &self.relational_arrival_keys+ }+/// Moves whenever an attribute name comes to require its value text: a selector's here, or an/// `attr()`'s anywhere in the process.pub fn attribute_value_text_requirements_version(&self) -> u64 {@@ -1976,6 +2037,9 @@ impl StyleEngine {attribute_value_text_names: Arc::default(),tested_attribute_names: Arc::default(),attribute_value_text_requirements_version: 0,+ relational_arrival_keys: Arc::default(),+ unresolved_relational_arrival_keys: HashSet::default(),+ relational_arrival_keys_version: 0,selector_programs_need_sweep: false,routing: Arc::new(RoutingRegistry::new()),selector_truth_changes: SelectorTruthChanges::default(),@@ -3381,6 +3445,9 @@ impl RetainedState {attribute_value_text_names: _,tested_attribute_names: _,attribute_value_text_requirements_version: _,+ relational_arrival_keys: _,+ unresolved_relational_arrival_keys: _,+ relational_arrival_keys_version: _,selector_programs_need_sweep: _,routing: _,// Scratch of one transaction.diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rsindex f0d8608166a..c0cd6c3fa99 100644--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs@@ -162,6 +162,18 @@ use std::sync::Mutex;/// Attribute names a document's selectors read, which its engine shares with its host.pub(crate) type SelectorAttributeNames = Arc<HashSet<StyleAtomID>>;+/// What an element's arrival has to carry to reach the anchor of a `:has()` argument: a name whose raw identity is+/// among `names` as its tag, ID, class or attribute name, or a state among `states`. Where an argument can be reached+/// by anything else, every arrival can reach one. The engine shares it with its host, which leaves the subtrees of+/// elements in a display:none subtree out of the engine's tree for as long as nothing could observe them.+#[derive(Clone, Default)]+pub(crate) struct RelationalArrivalKeys {+ keys: HashSet<RoutingKey>,+ pub(crate) names: Vec<usize>,+ pub(crate) states: Vec<u8>,+ pub(crate) reached_by_any_arrival: bool,+}+use crate::css::cascaded_properties::CascadeOrigin;#[cfg(test)]use crate::css::cascaded_properties::CascadedPropertyStore;@@ -1014,6 +1026,12 @@ pub struct RetainedState {/// The attribute names a selector tests in any way, which the host holds a copy of between jobs.tested_attribute_names: SelectorAttributeNames,attribute_value_text_requirements_version: u64,+ /// What an arrival has to carry to reach a `:has()` anchor, which the host holds a copy of between jobs.+ relational_arrival_keys: Arc<RelationalArrivalKeys>,+ /// The keys rules added since, which the host learns of once they are resolved.+ unresolved_relational_arrival_keys: HashSet<RoutingKey>,+ /// Moves whenever `relational_arrival_keys` does.+ relational_arrival_keys_version: u64,selector_programs_need_sweep: bool,routing: Arc<RoutingRegistry>,/// Exact selector changes and refresh requests emitted by the current transaction.diff --git a/Libraries/LibWeb/Rust/src/css/style/ordering.rs b/Libraries/LibWeb/Rust/src/css/style/ordering.rsindex f215c3a9bb6..be95f5a132c 100644--- a/Libraries/LibWeb/Rust/src/css/style/ordering.rs+++ b/Libraries/LibWeb/Rust/src/css/style/ordering.rs@@ -2253,6 +2253,19 @@ impl StyleEngine {if self.retained.tested_attribute_names.iter().any(is_reclaimed) {Arc::make_mut(&mut self.retained.tested_attribute_names).retain(|atom| !is_reclaimed(atom));}+ let relational_arrival_key_is_reclaimed = |key: &RoutingKey| key.atom().is_some_and(|atom| is_reclaimed(&atom));+ if self+ .retained+ .relational_arrival_keys+ .keys+ .iter()+ .any(relational_arrival_key_is_reclaimed)+ {+ let mut keys = self.retained.relational_arrival_keys.keys.clone();+ keys.extend(self.retained.unresolved_relational_arrival_keys.drain());+ keys.retain(|key| !relational_arrival_key_is_reclaimed(key));+ self.retained.replace_relational_arrival_keys(keys);+ }if self.retained.attribute_value_text_names.iter().any(is_reclaimed) {Arc::make_mut(&mut self.retained.attribute_value_text_names).retain(|atom| !is_reclaimed(atom));self.retained.attribute_value_text_requirements_version += 1;diff --git a/Libraries/LibWeb/Rust/src/css/style/user_agent_selectors.rs b/Libraries/LibWeb/Rust/src/css/style/user_agent_selectors.rsindex 3dc97054649..f8c1f5374a5 100644--- a/Libraries/LibWeb/Rust/src/css/style/user_agent_selectors.rs+++ b/Libraries/LibWeb/Rust/src/css/style/user_agent_selectors.rs@@ -93,6 +93,7 @@ impl StyleEngine {};self.add_style_rule_with(sheet, before, |engine, previous_program| {engine.note_selector_attribute_names(program.program());+ engine.note_relational_arrival_keys(program.program());let id = engine.retained.programs.add_process_program(&program);engine.retained.selector_programs_need_sweep |= previous_program.is_some();engine.retained.programs.settle_memory(&mut engine.retained.memory);diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rsindex 2ee678b1dca..564e37158b3 100644--- a/Libraries/LibWeb/Rust/src/render_state.rs+++ b/Libraries/LibWeb/Rust/src/render_state.rs@@ -155,6 +155,7 @@ impl RenderState {/// host learns of the engine's deferred element style inputs, where they moved, and the facts of the state as the/// job leaves it.fn take_owed(&mut self) -> Owed {+ self.engine_mut().resolve_relational_arrival_keys();let engine = self.engine_ref();let arena = self.arena.arena();let facts = StateFacts {@@ -173,9 +174,11 @@ impl RenderState {},selector_attribute_value_text_requirements_version: engine.selector_attribute_value_text_requirements_version(),+ relational_arrival_keys_version: engine.relational_arrival_keys_version(),};let selector_value_text_names = std::sync::Arc::clone(engine.selector_attribute_value_text_names());let selector_tested_attribute_names = std::sync::Arc::clone(engine.selector_tested_attribute_names());+ let relational_arrival_keys = std::sync::Arc::clone(engine.relational_arrival_keys());Owed {work: std::mem::take(&mut self.owed),deferred_inputs: self.engine_mut().take_moved_deferred_element_style_inputs(),@@ -183,6 +186,7 @@ impl RenderState {facts,selector_value_text_names,selector_tested_attribute_names,+ relational_arrival_keys,}}@@ -277,6 +281,8 @@ pub(crate) struct Owed {selector_value_text_names: crate::css::style::SelectorAttributeNames,/// The attribute names the engine's selectors test in any way, as the job left them.selector_tested_attribute_names: crate::css::style::SelectorAttributeNames,+ /// What an arrival has to carry to reach a `:has()` anchor, as the job left it.+ relational_arrival_keys: std::sync::Arc<crate::css::style::RelationalArrivalKeys>,}/// What a document's render state answers of itself as a job or a frame leaves it, which the host reads in place for as@@ -289,6 +295,8 @@ pub(crate) struct StateFacts {pub(crate) arena: ArenaFacts,/// Where the engine's selectors' requirements of attribute value text are.pub(crate) selector_attribute_value_text_requirements_version: u64,+ /// Where what an arrival has to carry to reach a `:has()` anchor is.+ pub(crate) relational_arrival_keys_version: u64,}/// What the style engine answers of itself as a job or a frame leaves it, which only a write to the engine moves (seediff --git a/Libraries/LibWeb/Rust/src/render_state/document_host.rs b/Libraries/LibWeb/Rust/src/render_state/document_host.rsindex 21b23961298..f1a56bc8e2e 100644--- a/Libraries/LibWeb/Rust/src/render_state/document_host.rs+++ b/Libraries/LibWeb/Rust/src/render_state/document_host.rs@@ -109,6 +109,10 @@ pub struct DocumentHost {selector_value_text_names: RefCell<crate::css::style::SelectorAttributeNames>,/// The attribute names the engine's selectors test in any way, as its last job left them.selector_tested_attribute_names: RefCell<crate::css::style::SelectorAttributeNames>,+ /// What an arrival has to carry to reach a `:has()` anchor, as its last job left it.+ relational_arrival_keys: RefCell<std::sync::Arc<crate::css::style::RelationalArrivalKeys>>,+ /// The keys the host was last told of, kept alive for as long as it reads them.+ lent_relational_arrival_keys: RefCell<std::sync::Arc<crate::css::style::RelationalArrivalKeys>>,/// The ticks the render clock hands the lanes of the document's presented frames.ticks: Arc<ClockTicks>,/// The steps the hover of the lanes decided that the last rendering update took in, which the host runs as the lanes@@ -202,6 +206,8 @@ impl DocumentHost {facts: Cell::new(None),selector_value_text_names: RefCell::default(),selector_tested_attribute_names: RefCell::default(),+ relational_arrival_keys: RefCell::default(),+ lent_relational_arrival_keys: RefCell::default(),ticks: ClockTicks::new(document),lane_transitions: RefCell::default(),frame_held_for_testing: Cell::default(),@@ -363,6 +369,7 @@ impl DocumentHost {facts,selector_value_text_names,selector_tested_attribute_names,+ relational_arrival_keys,}: Owed,) {self.engine_memo@@ -370,6 +377,7 @@ impl DocumentHost {self.facts.set(Some(facts));*self.selector_value_text_names.borrow_mut() = selector_value_text_names;*self.selector_tested_attribute_names.borrow_mut() = selector_tested_attribute_names;+ *self.relational_arrival_keys.borrow_mut() = relational_arrival_keys;self.engine_memo.deferred.borrow_mut()@@ -676,6 +684,26 @@ impl DocumentHost {.map(|facts| facts.selector_attribute_value_text_requirements_version)}+ /// What an arrival has to carry to reach a `:has()` anchor, with where it is, where the host knows: none runs, and it+ /// queued no rule since its last job or frame, which is all that compiles a selector.+ pub(crate) fn known_relational_arrival_keys(+ &self,+ ) -> Option<(u64, std::sync::Arc<crate::css::style::RelationalArrivalKeys>)> {+ let version = self+ .facts_where(|moves| !moves.selectors)?+ .relational_arrival_keys_version;+ Some((version, std::sync::Arc::clone(&self.relational_arrival_keys.borrow())))+ }++ /// Keeps `keys` alive until the host next asks, and answers them.+ pub(crate) fn lend_relational_arrival_keys(+ &self,+ keys: std::sync::Arc<crate::css::style::RelationalArrivalKeys>,+ ) -> std::cell::Ref<'_, crate::css::style::RelationalArrivalKeys> {+ *self.lent_relational_arrival_keys.borrow_mut() = keys;+ std::cell::Ref::map(self.lent_relational_arrival_keys.borrow(), |keys| &**keys)+ }+/// Whether the engine's selectors read the value text of an attribute that answers to any of `keys`, where the host/// knows: as it knows where their requirements are.pub(crate) fn known_selectors_read_value_text_of(diff --git a/Tests/LibWeb/Ref/expected/css/style-engine/children-waiting-in-hidden-subtree-revealed-without-read-ref.html b/Tests/LibWeb/Ref/expected/css/style-engine/children-waiting-in-hidden-subtree-revealed-without-read-ref.htmlnew file mode 100644index 00000000000..a70b63af054--- /dev/null+++ b/Tests/LibWeb/Ref/expected/css/style-engine/children-waiting-in-hidden-subtree-revealed-without-read-ref.html@@ -0,0 +1,10 @@+<!DOCTYPE html>+<style>+ body { margin: 0; }+ .item { width: 100px; height: 20px; background: green; }+</style>+<div>+ <div class="item"></div>+ <div class="item"></div>+ <div class="item"></div>+</div>diff --git a/Tests/LibWeb/Ref/input/css/style-engine/children-waiting-in-hidden-subtree-revealed-without-read.html b/Tests/LibWeb/Ref/input/css/style-engine/children-waiting-in-hidden-subtree-revealed-without-read.htmlnew file mode 100644index 00000000000..7abca0af012--- /dev/null+++ b/Tests/LibWeb/Ref/input/css/style-engine/children-waiting-in-hidden-subtree-revealed-without-read.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<link rel="match" href="../../../expected/css/style-engine/children-waiting-in-hidden-subtree-revealed-without-read-ref.html" />+<style>+ body { margin: 0; }+ .hidden { display: none; }+ .item { width: 100px; height: 20px; background: green; }+</style>+<div id="hidden-parent" class="hidden"></div>+<script>+ const hiddenParent = document.getElementById("hidden-parent");+ document.body.offsetWidth;+ const container = document.createElement("div");+ for (let i = 0; i < 3; i++) {+ const item = document.createElement("div");+ item.className = "item";+ container.appendChild(item);+ }+ hiddenParent.appendChild(container);+ document.body.offsetWidth;+ hiddenParent.className = "";+</script>diff --git a/Tests/LibWeb/Text/expected/css/style-engine/children-waiting-in-hidden-subtree.txt b/Tests/LibWeb/Text/expected/css/style-engine/children-waiting-in-hidden-subtree.txtnew file mode 100644index 00000000000..211c50dc7ff--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/children-waiting-in-hidden-subtree.txt@@ -0,0 +1,20 @@+revealed height: 30+revealed sibling color: rgb(0, 128, 0)+hidden first color: rgb(0, 0, 255)+hidden second color: rgb(0, 128, 0)+anchor color with badge arriving: rgb(255, 0, 0)+anchor color without badge: rgb(0, 0, 0)+anchor color with plain content: rgb(0, 0, 0)+anchor color with badge added later: rgb(255, 0, 0)+anchor background without link: rgba(0, 0, 0, 0)+anchor background with link: rgb(255, 255, 0)+anchor color with rule added later: rgb(255, 0, 255)+empty host display: block+host display with content: none+revealed height after joins: 30+animated reveal height: 20+animated waiting element styled: true+revealed shadow host height: 15+waiting dialog styled as an arrived one is: true+moved height: 30+reinserted height: 30diff --git a/Tests/LibWeb/Text/input/css/style-engine/children-waiting-in-hidden-subtree.html b/Tests/LibWeb/Text/input/css/style-engine/children-waiting-in-hidden-subtree.htmlnew file mode 100644index 00000000000..accb655a6b8--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/children-waiting-in-hidden-subtree.html@@ -0,0 +1,226 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<style>+ .hidden { display: none; }+ .shown { display: block; }+ .item { color: rgb(0, 0, 255); height: 10px; }+ .item + .item { color: rgb(0, 128, 0); }+ .outer { color: rgb(0, 0, 0); }+ .outer:has(.badge) { color: rgb(255, 0, 0); }+ .outer:has(:any-link) { background-color: rgb(255, 255, 0); }+ #empty-host { display: none; }+ #empty-host:empty { display: block; }+</style>+<div id="root"></div>+<script>+function makeContainer(count) {+ const container = document.createElement("div");+ for (let i = 0; i < count; i++) {+ const item = document.createElement("div");+ item.className = "item";+ item.appendChild(document.createElement("span"));+ container.appendChild(item);+ }+ return container;+}++function makeHiddenParent() {+ const parent = document.createElement("div");+ parent.className = "hidden";+ root.appendChild(parent);+ internals.updateStyle();+ return parent;+}++test(() => {+ // Revealing the subtree styles and lays out the children that waited.+ {+ const parent = makeHiddenParent();+ const container = makeContainer(3);+ parent.appendChild(container);+ internals.updateStyle();+ parent.className = "shown";+ println(`revealed height: ${container.offsetHeight}`);+ println(`revealed sibling color: ${getComputedStyle(container.children[1]).color}`);+ parent.remove();+ }++ // A read of a child that waits answers its style, sibling selectors included.+ {+ const parent = makeHiddenParent();+ const container = makeContainer(3);+ parent.appendChild(container);+ internals.updateStyle();+ println(`hidden first color: ${getComputedStyle(container.children[0]).color}`);+ println(`hidden second color: ${getComputedStyle(container.children[1]).color}`);+ parent.remove();+ }++ // A :has() argument reaches its anchor through a hidden child, as it arrives and as it changes later.+ {+ const outer = document.createElement("div");+ outer.className = "outer";+ root.appendChild(outer);+ const parent = document.createElement("div");+ parent.className = "hidden";+ outer.appendChild(parent);+ internals.updateStyle();+ const container = makeContainer(3);+ container.children[2].firstChild.className = "badge";+ parent.appendChild(container);+ println(`anchor color with badge arriving: ${getComputedStyle(outer).color}`);+ container.remove();+ println(`anchor color without badge: ${getComputedStyle(outer).color}`);++ const plain = makeContainer(3);+ parent.appendChild(plain);+ internals.updateStyle();+ println(`anchor color with plain content: ${getComputedStyle(outer).color}`);+ plain.children[1].firstChild.classList.add("badge");+ println(`anchor color with badge added later: ${getComputedStyle(outer).color}`);++ const links = makeContainer(2);+ const link = document.createElement("a");+ links.children[1].appendChild(link);+ parent.appendChild(links);+ internals.updateStyle();+ println(`anchor background without link: ${getComputedStyle(outer).backgroundColor}`);+ link.href = "#target";+ println(`anchor background with link: ${getComputedStyle(outer).backgroundColor}`);+ outer.remove();+ }++ // A rule added later can reach an anchor through children that already wait.+ {+ const outer = document.createElement("div");+ root.appendChild(outer);+ const parent = document.createElement("div");+ parent.className = "hidden";+ outer.appendChild(parent);+ internals.updateStyle();+ const container = makeContainer(3);+ container.children[1].firstChild.className = "late";+ parent.appendChild(container);+ internals.updateStyle();+ const style = document.createElement("style");+ style.textContent = "div:has(.late) { color: rgb(255, 0, 255); }";+ document.head.appendChild(style);+ println(`anchor color with rule added later: ${getComputedStyle(outer).color}`);+ style.remove();+ outer.remove();+ }++ // The parent of a hidden subtree is not empty, though the children of its child wait.+ {+ const host = document.createElement("div");+ host.id = "empty-host";+ root.appendChild(host);+ internals.updateStyle();+ println(`empty host display: ${getComputedStyle(host).display}`);+ host.appendChild(makeContainer(2));+ println(`host display with content: ${getComputedStyle(host).display}`);+ host.remove();+ }++ // Children that join the waiting ones arrive with them as the subtree is revealed.+ {+ const parent = makeHiddenParent();+ const container = makeContainer(2);+ parent.appendChild(container);+ internals.updateStyle();+ container.appendChild(makeContainer(1).firstChild);+ container.children[0].firstChild.appendChild(document.createElement("b"));+ internals.updateStyle();+ parent.className = "shown";+ println(`revealed height after joins: ${container.offsetHeight}`);+ parent.remove();+ }++ // An animation that holds the hidden parent visible reveals the children that waited.+ {+ const parent = makeHiddenParent();+ const container = makeContainer(2);+ parent.appendChild(container);+ internals.updateStyle();+ parent.animate({ display: ["block", "block"] }, { duration: 1000000 });+ println(`animated reveal height: ${container.offsetHeight}`);+ parent.getAnimations().forEach(animation => animation.cancel());+ parent.remove();+ }++ // An element animated after it began to wait keeps its style while hidden, as one animated before does.+ {+ const parent = makeHiddenParent();+ const container = makeContainer(2);+ parent.appendChild(container);+ internals.updateStyle();+ const animated = container.children[1].firstChild;+ animated.animate([{ opacity: 0 }, { opacity: 1 }], 100).finish();+ internals.updateStyle();+ println(`animated waiting element styled: ${internals.styleRecordIdentity(animated) !== 0}`);+ parent.remove();+ }++ // A shadow tree attached to an element whose children wait takes their place, and arrives as it is revealed.+ {+ const parent = makeHiddenParent();+ const container = makeContainer(2);+ parent.appendChild(container);+ internals.updateStyle();+ const shadow = container.attachShadow({ mode: "open" });+ const shadowItem = document.createElement("div");+ shadowItem.style.height = "15px";+ shadow.appendChild(shadowItem);+ internals.updateStyle();+ parent.className = "shown";+ println(`revealed shadow host height: ${container.offsetHeight}`);+ parent.remove();+ }++ // A dialog that waited enters the top layer as one that arrived in full before its parent was hidden does.+ {+ const styled = [];+ for (const waits of [true, false]) {+ const parent = document.createElement("div");+ if (waits)+ parent.className = "hidden";+ root.appendChild(parent);+ internals.updateStyle();+ const container = makeContainer(1);+ const dialog = document.createElement("dialog");+ dialog.textContent = "dialog";+ container.children[0].appendChild(dialog);+ parent.appendChild(container);+ internals.updateStyle();+ if (!waits) {+ parent.className = "hidden";+ internals.updateStyle();+ }+ dialog.showModal();+ internals.updateStyle();+ styled.push(internals.styleRecordIdentity(dialog) !== 0);+ dialog.close();+ parent.remove();+ }+ println(`waiting dialog styled as an arrived one is: ${styled[0] === styled[1]}`);+ }++ // A subtree whose children waited arrives in full where it moves to be seen.+ {+ const parent = makeHiddenParent();+ const container = makeContainer(3);+ parent.appendChild(container);+ internals.updateStyle();+ root.appendChild(container);+ println(`moved height: ${container.offsetHeight}`);+ container.remove();+ parent.appendChild(container);+ internals.updateStyle();+ container.remove();+ root.appendChild(container);+ println(`reinserted height: ${container.offsetHeight}`);+ container.remove();+ parent.remove();+ }+});+</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-consumed-when-visible.html b/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-consumed-when-visible.htmlindex f1066c1b7ca..26d542c3f0c 100644--- a/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-consumed-when-visible.html+++ b/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-consumed-when-visible.html@@ -17,9 +17,11 @@const reaction = document.createElement("span");reaction.id = "reaction";reaction.className = "before";- middle.appendChild(reaction);hidden.appendChild(middle);getComputedStyle(query).color;+ // The span arrives in the hidden subtree itself, where the children of an element arriving with it would wait.+ middle.appendChild(reaction);+ getComputedStyle(query).color;internals.updateStyle();internals.resetStyleInvalidationCounters();