Truly independent web browser
LibWeb: Assign slottables lazily when shadow host children change
Tim Ledbettereeffc37e7e83
diff --git a/Libraries/LibWeb/Animations/AnimationEffect.cpp b/Libraries/LibWeb/Animations/AnimationEffect.cppindex 8180435d10e..e728bcde210 100644--- a/Libraries/LibWeb/Animations/AnimationEffect.cpp+++ b/Libraries/LibWeb/Animations/AnimationEffect.cpp@@ -963,6 +963,7 @@ void AnimationUpdateContext::publish()|| invalidation.recompute_descendant_styles|| invalidation.needs_layout_tree_rebuild();if (auto* slot = as_if<HTML::HTMLSlotElement>(*target); slot && !descendants_may_observe_non_inherited_properties) {+ slot->assign_slottables_if_needed();// NB: Assigned elements leave explicit inheritance marks on their DOM parent,// including values that substitute to inherit, rather than on the slot. Every// assigned element is a child of the shadow host, so the first one's parentdiff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.cpp b/Libraries/LibWeb/CSS/StyleEngineBridge.cppindex 35ffa22cb59..eed216e393e 100644--- a/Libraries/LibWeb/CSS/StyleEngineBridge.cpp+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.cpp@@ -389,6 +389,8 @@ bool StyleEngine::has_recorded_input() constvoid StyleEngine::submit_recorded_input(){+ if (m_style_computer)+ 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());diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cppindex f30267ee261..fb237b4d477 100644--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp@@ -476,6 +476,7 @@ static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<GC::Redom_order_arrivals.append(*element);++element_count;if (auto* slot = as_if<HTML::HTMLSlotElement>(*element)) {+ slot->assign_slottables_if_needed();for (auto const& slottable : slot->assigned_nodes_internal()) {if (auto const* assigned = slottable.get_pointer<GC::Ref<DOM::Element>>(); assigned && (*assigned)->style_node_id() != no_style_node)slottables_identified_earlier.append(*assigned);@@ -1312,8 +1313,10 @@ void record_top_layer_changed(DOM::Document& document)// republish on arrival: a slottable the list it has just become a member of, and a slot the list it arrived owning.static void republish_assigned_slot_of(DOM::Node& node){- if (auto slot = DOM::assigned_slot_for_node(node))+ if (auto slot = DOM::assigned_slot_for_node(node)) {+ slot->assign_slottables_if_needed();record_slot_assignment_changed(*slot);+ }if (auto* slot = as_if<HTML::HTMLSlotElement>(node))record_slot_assignment_changed(*slot);}@@ -1330,6 +1333,7 @@ static void record_element_disconnecting(DOM::Element& element, TreeScopeID tree// old slot by then. If another slot takes over, the ordinary assignment path publishes the// subsequent arrival.if (auto* slot = as_if<HTML::HTMLSlotElement>(element)) {+ slot->assign_slottables_if_needed();for (auto const& slottable : slot->assigned_nodes_internal()) {auto const* assigned_element = slottable.get_pointer<GC::Ref<DOM::Element>>();if (!assigned_element || (*assigned_element)->style_node_id() == no_style_node)diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 06a835a64ed..2727c58785f 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -6571,6 +6571,22 @@ void Document::unregister_resize_observer(Badge<ResizeObserver::ResizeObserver>,m_resize_observers.remove_all_matching([&](auto const& entry) { return !entry || entry.ptr().ptr() == &observer; });}+void Document::add_shadow_root_needing_slot_assignment(Badge<ShadowRoot>, ShadowRoot& shadow_root)+{+ m_shadow_roots_needing_slot_assignment.append(shadow_root);+}++void Document::remove_shadow_root_needing_slot_assignment(Badge<ShadowRoot>, ShadowRoot& shadow_root)+{+ m_shadow_roots_needing_slot_assignment.remove(shadow_root);+}++void Document::assign_slottables_if_needed()+{+ while (auto* shadow_root = m_shadow_roots_needing_slot_assignment.first())+ shadow_root->assign_slottables_if_needed();+}+// https://www.w3.org/TR/intersection-observer/#queue-an-intersection-observer-taskvoid Document::queue_intersection_observer_task(){diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 5b2bae441f1..e13e48a0b07 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -1088,6 +1088,10 @@ public:bool has_resize_observers() const { return !m_resize_observers.is_empty(); }void unregister_resize_observer(Badge<ResizeObserver::ResizeObserver>, ResizeObserver::ResizeObserver&);+ void add_shadow_root_needing_slot_assignment(Badge<ShadowRoot>, ShadowRoot&);+ void remove_shadow_root_needing_slot_assignment(Badge<ShadowRoot>, ShadowRoot&);+ void assign_slottables_if_needed();+void run_the_update_intersection_observations_steps(HighResolutionTime::DOMHighResTimeStamp time);void start_intersection_observing_a_lazy_loading_element(Element&);@@ -2027,6 +2031,8 @@ private:Vector<GC::Weak<ResizeObserver::ResizeObserver>> m_resize_observers;+ ShadowRoot::DocumentSlotAssignmentList m_shadow_roots_needing_slot_assignment;+// https://html.spec.whatwg.org/multipage/semantics.html#will-declaratively-refresh// A Document object has an associated will declaratively refresh (a boolean). It is initially false.bool m_will_declaratively_refresh { false };diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 7a193ccb84a..f2f34962202 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -6195,6 +6195,10 @@ void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16if (value == Utf16String {} && !old_value.has_value())return;+ // AD-HOC: Assigned nodes are recomputed lazily.+ if (auto assigned_slot = assigned_slot_internal())+ assigned_slot->assign_slottables_if_needed();+// 4. If value is null or the empty string, then set element’s name to the empty string.if (!value.has_value() || value->is_empty())set_slottable_name({});diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cppindex 7d29a0f17a1..38357be8396 100644--- a/Libraries/LibWeb/DOM/Node.cpp+++ b/Libraries/LibWeb/DOM/Node.cpp@@ -989,21 +989,29 @@ void Node::insert_node_into_children(GC::Ref<Node> node, GC::Ptr<Node> child)// 5. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run// signal a slot change for parent.if (auto* this_slot_element = as_if<HTML::HTMLSlotElement>(*this); this_slot_element && root().is_shadow_root()) {+ this_slot_element->assign_slottables_if_needed();if (this_slot_element->assigned_nodes_internal().is_empty())signal_a_slot_change(*this_slot_element);}// AD-HOC: Register any slot elements in the inserted subtree with the shadow root’s slot registry// before running assign_slottables_for_a_tree, so the registry is up-to-date.- if (auto* shadow_root = as_if<ShadowRoot>(node->root())) {+ auto& inserted_root = node->root();+ auto* inserted_shadow_root = as_if<ShadowRoot>(inserted_root);+ bool inserted_subtree_has_slot = false;+ if (inserted_shadow_root) {node->for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](auto& slot) {- shadow_root->register_slot(slot);+ inserted_shadow_root->assign_slottables_if_needed();+ inserted_shadow_root->register_slot(slot);+ inserted_subtree_has_slot = true;return TraversalDecision::Continue;});}// 6. Run assign slottables for a tree with node’s root.- assign_slottables_for_a_tree(node->root());+ // OPTIMIZATION: Inserting into a named shadow tree only changes slot assignments when the subtree holds a slot.+ if (!inserted_shadow_root || inserted_subtree_has_slot || inserted_shadow_root->slot_assignment() == SlotAssignmentMode::Manual)+ assign_slottables_for_a_tree(inserted_root);}// https://dom.spec.whatwg.org/#concept-node-insert@@ -1518,33 +1526,43 @@ void Node::detach_remaining_layout_nodes_for_removal()Layout::RustFFI::render_state_detach_remaining_rows_for_removal(arena->host(), style_nodes.data(), style_nodes.size());}-void Node::assign_slottables_after_removal(Node& parent, Node& parent_root)+Vector<GC::Ref<HTML::HTMLSlotElement>> Node::descendant_slots_before_removal(Node& parent_root){- if (auto assigned_slot = assigned_slot_for_node(*this))- assign_slottables(*assigned_slot);+ // AD-HOC: Assigned nodes are recomputed lazily.+ Vector<GC::Ref<HTML::HTMLSlotElement>> descendant_slots;+ if (auto* shadow_root = as_if<ShadowRoot>(parent_root)) {+ for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](auto& slot) {+ descendant_slots.append(slot);+ return TraversalDecision::Continue;+ });+ if (!descendant_slots.is_empty())+ shadow_root->assign_slottables_if_needed();+ }+ return descendant_slots;+}++void Node::assign_slottables_after_removal(Node& parent, Node& parent_root, ReadonlySpan<GC::Ref<HTML::HTMLSlotElement>> descendant_slots)+{+ // AD-HOC: Assigned nodes are recomputed lazily.+ unassign_a_slot(*this);if (auto* parent_slot_element = as_if<HTML::HTMLSlotElement>(parent); parent_slot_element && parent_root.is_shadow_root()) {+ parent_slot_element->assign_slottables_if_needed();if (parent_slot_element->assigned_nodes_internal().is_empty())signal_a_slot_change(*parent_slot_element);}- if (auto* shadow_root = as_if<ShadowRoot>(parent_root)) {- Vector<GC::Ref<HTML::HTMLSlotElement>> descendant_slots;- for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](auto& slot) {- // AD-HOC: Unregister slot from the shadow root's registry before assign_slottables_for_a_tree.+ if (auto* shadow_root = as_if<ShadowRoot>(parent_root); shadow_root && !descendant_slots.is_empty()) {+ // AD-HOC: Unregister slot from the shadow root's registry before assign_slottables_for_a_tree.+ for (auto const& slot : descendant_slots)shadow_root->unregister_slot(slot);- descendant_slots.append(slot);- return TraversalDecision::Continue;- });- if (!descendant_slots.is_empty()) {- // 1. Run assign slottables for a tree with parent’s root.- assign_slottables_for_a_tree(parent_root);+ // 1. Run assign slottables for a tree with parent’s root.+ assign_slottables_for_a_tree(parent_root);- // 2. Run assign slottables for a tree with node.- for (auto const& slot : descendant_slots)- assign_slottables(slot);- }+ // 2. Run assign slottables for a tree with node.+ for (auto const& slot : descendant_slots)+ assign_slottables(slot);}}@@ -1639,6 +1657,9 @@ void Node::remove(bool suppress_observers)schedule_list_item_renumber_for_removal();+ auto& parent_root = parent->root();+ auto descendant_slots = descendant_slots_before_removal(parent_root);+RemovalStyleRecordPins removal_style_record_pins { document().style_computer() };removal_style_record_pins.pin_style_records_before_removal(*this, was_tracked_by_style_engine);if (was_tracked_by_style_engine) {@@ -1659,8 +1680,7 @@ void Node::remove(bool suppress_observers)// 9. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run// signal a slot change for parent.// 10. If node has an inclusive descendant that is a slot, then:- auto& parent_root = parent->root();- assign_slottables_after_removal(*parent, parent_root);+ assign_slottables_after_removal(*parent, parent_root, descendant_slots);removal_style_record_pins.pin_style_records_after_removal(*this, was_connected);@@ -1969,38 +1989,35 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)}}+ auto& old_parent_root = old_parent->root();+ auto descendant_slots = descendant_slots_before_removal(old_parent_root);+// 13. Remove node from oldParent’s children.old_parent->remove_child_impl(*this);// 14. If node is assigned, then run assign slottables for node’s assigned slot.- if (auto assigned_slot = assigned_slot_for_node(*this))- assign_slottables(*assigned_slot);+ // AD-HOC: Assigned nodes are recomputed lazily.+ unassign_a_slot(*this);// 15. If oldParent’s root is a shadow root, and oldParent is a slot whose assigned nodes is empty, then run signal a slot change for oldParent.- auto& old_parent_root = old_parent->root();if (auto* old_parent_slot_element = as_if<HTML::HTMLSlotElement>(*old_parent); old_parent_slot_element && old_parent_root.is_shadow_root()) {+ old_parent_slot_element->assign_slottables_if_needed();if (old_parent_slot_element->assigned_nodes_internal().is_empty())signal_a_slot_change(*old_parent_slot_element);}// 16. If node has an inclusive descendant that is a slot:- if (auto* shadow_root = as_if<ShadowRoot>(old_parent_root)) {- Vector<GC::Ref<HTML::HTMLSlotElement>> descendant_slots;- for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](auto& slot) {- // AD-HOC: Unregister slot from the shadow root's registry before assign_slottables_for_a_tree.+ if (auto* shadow_root = as_if<ShadowRoot>(old_parent_root); shadow_root && !descendant_slots.is_empty()) {+ // AD-HOC: Unregister slot from the shadow root's registry before assign_slottables_for_a_tree.+ for (auto const& slot : descendant_slots)shadow_root->unregister_slot(slot);- descendant_slots.append(slot);- return TraversalDecision::Continue;- });- if (!descendant_slots.is_empty()) {- // 1. Run assign slottables for a tree with oldParent’s root.- assign_slottables_for_a_tree(old_parent_root);+ // 1. Run assign slottables for a tree with oldParent’s root.+ assign_slottables_for_a_tree(old_parent_root);- // 2. Run assign slottables for a tree with node.- for (auto const& slot : descendant_slots)- assign_slottables(slot);- }+ // 2. Run assign slottables for a tree with node.+ for (auto const& slot : descendant_slots)+ assign_slottables(slot);}// 17. If child is non-null:@@ -2057,34 +2074,39 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)}// 21. If newParent is a shadow host whose shadow root’s slot assignment is "named" and node is a slottable, then assign a slot for node.- if (is<Element>(new_parent) && is<Element>(*this)) {- auto& this_element = static_cast<Element&>(*this);- auto& new_parent_element = static_cast<Element&>(new_parent);-- auto is_named_shadow_host = new_parent_element.is_shadow_host()- && new_parent_element.shadow_root()->slot_assignment() == SlotAssignmentMode::Named;+ if (auto* new_parent_element = as_if<Element>(new_parent)) {+ auto is_named_shadow_host = new_parent_element->is_shadow_host()+ && new_parent_element->shadow_root()->slot_assignment() == SlotAssignmentMode::Named;- if (is_named_shadow_host && this_element.is_slottable())- assign_a_slot(this_element.as_slottable());+ if (is_named_shadow_host && is_slottable())+ assign_a_slot(as_slottable());}// AD-HOC: Register any slot elements in the moved subtree with the shadow root's slot registry so the registry is// up-to-date.- if (auto* new_shadow_root = as_if<ShadowRoot>(root())) {+ auto& new_root = root();+ auto* new_shadow_root = as_if<ShadowRoot>(new_root);+ bool moved_subtree_has_slot = false;+ if (new_shadow_root) {for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>([&](auto& slot) {+ new_shadow_root->assign_slottables_if_needed();new_shadow_root->register_slot(slot);+ moved_subtree_has_slot = true;return TraversalDecision::Continue;});}// 22. If newParent’s root is a shadow root, and newParent is a slot whose assigned nodes is empty, then run signal a slot change for newParent.- if (auto* new_parent_slot_element = as_if<HTML::HTMLSlotElement>(new_parent); new_parent_slot_element && new_parent.root().is_shadow_root()) {+ if (auto* new_parent_slot_element = as_if<HTML::HTMLSlotElement>(new_parent); new_parent_slot_element && new_root.is_shadow_root()) {+ new_parent_slot_element->assign_slottables_if_needed();if (new_parent_slot_element->assigned_nodes_internal().is_empty())signal_a_slot_change(*new_parent_slot_element);}// 23. Run assign slottables for a tree with node’s root.- assign_slottables_for_a_tree(root());+ // OPTIMIZATION: Moving into a named shadow tree only changes slot assignments when the moved subtree holds a slot.+ if (!new_shadow_root || moved_subtree_has_slot || new_shadow_root->slot_assignment() == SlotAssignmentMode::Manual)+ assign_slottables_for_a_tree(new_root);CSS::Invalidation::invalidate_style_after_subtree_place_changed(*this, moved_from_parent);@@ -2954,6 +2976,8 @@ void Node::remove_all_children(bool suppress_observers)if (!list_owner_renumber_scheduled)list_owner_renumber_scheduled = child->schedule_list_item_renumber_for_removal();+ auto descendant_slots = child->descendant_slots_before_removal(parent_root);+RemovalStyleRecordPins removal_style_record_pins { document().style_computer() };removal_style_record_pins.pin_style_records_before_removal(*child, was_tracked_by_style_engine);if (was_tracked_by_style_engine) {@@ -2970,7 +2994,7 @@ void Node::remove_all_children(bool suppress_observers)// 9. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run// signal a slot change for parent.// 10. If node has an inclusive descendant that is a slot, then:- child->assign_slottables_after_removal(*this, parent_root);+ child->assign_slottables_after_removal(*this, parent_root, descendant_slots);removal_style_record_pins.pin_style_records_after_removal(*child, was_connected);diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.hindex d73c03293de..4f954893a1c 100644--- a/Libraries/LibWeb/DOM/Node.h+++ b/Libraries/LibWeb/DOM/Node.h@@ -719,7 +719,8 @@ private:bool schedule_list_item_renumber_for_removal();void report_removal_to_style_engine(Node& parent);void update_layout_tree_for_removal(Layout::BegunRead const& read, Node& parent, LayoutSubtreeRemoval, AncestorsMayHaveFirstLetter);- void assign_slottables_after_removal(Node& parent, Node& parent_root);+ Vector<GC::Ref<HTML::HTMLSlotElement>> descendant_slots_before_removal(Node& parent_root);+ void assign_slottables_after_removal(Node& parent, Node& parent_root, ReadonlySpan<GC::Ref<HTML::HTMLSlotElement>> descendant_slots);void run_removing_steps(Node& parent, Node& parent_root, bool was_tracked_by_style_engine);void add_transient_registered_observers_for_removal(Node& parent);void queue_tree_mutation_record_for_removal(Node& parent, GC::Ptr<Node> old_previous_sibling, GC::Ptr<Node> old_next_sibling);diff --git a/Libraries/LibWeb/DOM/Range.cpp b/Libraries/LibWeb/DOM/Range.cppindex 5e4256bb2ae..45f3b5c0048 100644--- a/Libraries/LibWeb/DOM/Range.cpp+++ b/Libraries/LibWeb/DOM/Range.cpp@@ -264,6 +264,7 @@ static Optional<FlatTreePosition> flat_tree_position(BoundaryPoint point)Optional<RelativeBoundaryPointPosition> position_of_boundary_point_relative_to_other_boundary_point_in_flat_tree(BoundaryPoint a, BoundaryPoint b){+ a.node->document().assign_slottables_if_needed();auto a_position = flat_tree_position(a);auto b_position = flat_tree_position(b);if (!a_position.has_value() || !b_position.has_value() || a_position->root != b_position->root)diff --git a/Libraries/LibWeb/DOM/ShadowRoot.cpp b/Libraries/LibWeb/DOM/ShadowRoot.cppindex 211709b8d30..e41eb1361ad 100644--- a/Libraries/LibWeb/DOM/ShadowRoot.cpp+++ b/Libraries/LibWeb/DOM/ShadowRoot.cpp@@ -51,6 +51,7 @@ void ShadowRoot::finalize(){Base::finalize();document().unregister_shadow_root({}, *this);+ document().remove_shadow_root_needing_slot_assignment({}, *this);}void ShadowRoot::adopted_from(Document& old_document)@@ -61,6 +62,10 @@ void ShadowRoot::adopted_from(Document& old_document)// tree-scoped name lookups), so adoption has to move this shadow root to the new document's list.old_document.unregister_shadow_root({}, *this);document().register_shadow_root({}, *this);+ if (!m_slots_needing_assignment.is_empty()) {+ old_document.remove_shadow_root_needing_slot_assignment({}, *this);+ document().add_shadow_root_needing_slot_assignment({}, *this);+ }// Identities belong to one document's engine, so the root and its scope have to be minted// again in the new one. Its sheets are re-adopted through the CSSOM, which is what attaches@@ -214,6 +219,7 @@ void ShadowRoot::visit_edges(Visitor& visitor)}visitor.visit(m_custom_element_registry);visitor.visit(m_radio_button_group_registry);+ visitor.visit(m_slots_needing_assignment);}HTML::RadioButtonGroupRegistry& ShadowRoot::ensure_radio_button_group_registry()@@ -290,6 +296,23 @@ GC::Ptr<HTML::HTMLSlotElement> ShadowRoot::first_slot_with_name(Utf16View name)return m_slot_registry->first_slot_with_name(name);}+void ShadowRoot::set_needs_slot_assignment(HTML::HTMLSlotElement& slot)+{+ if (m_slots_needing_assignment.contains_slow(GC::Ref { slot }))+ return;+ if (m_slots_needing_assignment.is_empty())+ document().add_shadow_root_needing_slot_assignment({}, *this);+ m_slots_needing_assignment.append(slot);+}++void ShadowRoot::assign_slottables_if_needed()+{+ document().remove_shadow_root_needing_slot_assignment({}, *this);+ auto slots = move(m_slots_needing_assignment);+ for (auto slot : slots)+ assign_slottables(slot, SignalSlotChange::No);+}+// https://drafts.csswg.org/css-shadow-1/#shadow-root-part-element-mapShadowRoot::PartElementMap const& ShadowRoot::part_element_map() const{diff --git a/Libraries/LibWeb/DOM/ShadowRoot.h b/Libraries/LibWeb/DOM/ShadowRoot.hindex 9f34777be11..6bdc32c8bc8 100644--- a/Libraries/LibWeb/DOM/ShadowRoot.h+++ b/Libraries/LibWeb/DOM/ShadowRoot.h@@ -96,6 +96,9 @@ public:GC::Ptr<HTML::HTMLSlotElement> first_slot_with_name(Utf16View name) const;+ void set_needs_slot_assignment(HTML::HTMLSlotElement&);+ void assign_slottables_if_needed();+CSS::StyleScope const& style_scope() const { return m_style_scope; }CSS::StyleScope& style_scope() { return m_style_scope; }@@ -171,11 +174,13 @@ private:AnchorNameMap m_anchor_name_map;OwnPtr<SlotRegistry> m_slot_registry;+ Vector<GC::Ref<HTML::HTMLSlotElement>> m_slots_needing_assignment;GC::Ptr<CSS::StyleSheetList> m_style_sheets;mutable GC::Ptr<WebIDL::ObservableArray> m_adopted_style_sheets;IntrusiveListNode<ShadowRoot> m_list_node;+ IntrusiveListNode<ShadowRoot> m_slot_assignment_list_node;CSS::StyleScope m_style_scope;@@ -192,6 +197,7 @@ private:public:using DocumentShadowRootList = IntrusiveList<&ShadowRoot::m_list_node>;+ using DocumentSlotAssignmentList = IntrusiveList<&ShadowRoot::m_slot_assignment_list_node>;};template<>diff --git a/Libraries/LibWeb/DOM/Slottable.cpp b/Libraries/LibWeb/DOM/Slottable.cppindex 3085df8c180..8ddf2ce646f 100644--- a/Libraries/LibWeb/DOM/Slottable.cpp+++ b/Libraries/LibWeb/DOM/Slottable.cpp@@ -5,6 +5,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/HashTable.h>#include <LibWeb/CSS/Invalidation/LanguageInvalidator.h>#include <LibWeb/CSS/StyleEngineInput.h>#include <LibWeb/DOM/Document.h>@@ -251,15 +252,46 @@ Vector<Slottable> find_flattened_slottables(GC::Ref<HTML::HTMLSlotElement> slot)return result;}+static Node const* slottable_as_node(Slottable const& slottable)+{+ return slottable.visit([](auto const& node) -> Node const* { return node.ptr(); });+}++static void invalidate_after_slot_assignment_change(HTML::HTMLSlotElement& slot)+{+ slot.set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::SlotAssignmentChange);+ CSS::Invalidation::invalidate_style_after_slot_assignment_change(slot);+}++static void change_assigned_slot(Slottable const& slottable, HTML::HTMLSlotElement& changed_slot, GC::Ptr<HTML::HTMLSlotElement> old_slot, GC::Ptr<HTML::HTMLSlotElement> new_slot)+{+ // Other children of the host can join a manual slot when slottable joins or leaves it.+ auto& shadow_root = as<ShadowRoot>(changed_slot.root());+ if (shadow_root.slot_assignment() == SlotAssignmentMode::Manual) {+ assign_slottables(changed_slot);+ return;+ }++ signal_a_slot_change(changed_slot);+ slottable.visit([&](auto const& node) {+ node->set_assigned_slot(new_slot);+ });+ if (auto const* element = slottable.template get_pointer<GC::Ref<Element>>())+ CSS::record_element_assigned_slot_changed(**element, old_slot.ptr());+ shadow_root.set_needs_slot_assignment(changed_slot);+ invalidate_after_slot_assignment_change(changed_slot);+}+// https://dom.spec.whatwg.org/#assign-slotables-void assign_slottables(GC::Ref<HTML::HTMLSlotElement> slot)+void assign_slottables(GC::Ref<HTML::HTMLSlotElement> slot, SignalSlotChange signal_slot_change){// 1. Let slottables be the result of finding slottables for slot.auto slottables = find_slottables(slot);// 2. If slottables and slot’s assigned nodes are not identical, then run signal a slot change for slot.+ // AD-HOC: A lazy recomputation follows a mutation that has already signaled the change.auto assignment_changed = slottables != slot->assigned_nodes_internal();- if (assignment_changed)+ if (assignment_changed && signal_slot_change == SignalSlotChange::Yes)signal_a_slot_change(slot);// AD-HOC: Clear the assigned slot for slottables that are no longer assigned to this slot.@@ -267,16 +299,24 @@ void assign_slottables(GC::Ref<HTML::HTMLSlotElement> slot)// during style computation. A tree-wide assignment can already have moved one of the// old slottables to another slot, which the old slot must not overwrite when it is// processed afterward.- for (auto const& old_slottable : slot->assigned_nodes_internal()) {- if (old_slottable.visit([](auto const& node) { return node->assigned_slot_internal(); }) != slot)- continue;- if (slottables.contains_slow(old_slottable))- continue;- old_slottable.visit([&](auto const& node) {- node->set_assigned_slot(nullptr);- });- if (auto const* element = old_slottable.template get_pointer<GC::Ref<Element>>())- CSS::record_element_assigned_slot_changed(**element, slot.ptr());+ if (assignment_changed && !slot->assigned_nodes_internal().is_empty()) {+ HashTable<Node const*> slottable_nodes;+ slottable_nodes.ensure_capacity(slottables.size());+ for (auto const& slottable : slottables)+ slottable_nodes.set(slottable_as_node(slottable));++ for (auto const& old_slottable : slot->assigned_nodes_internal()) {+ if (old_slottable.visit([](auto const& node) { return node->assigned_slot_internal(); }) != slot)+ continue;+ if (slottable_nodes.contains(slottable_as_node(old_slottable)))+ continue;+ VERIFY(signal_slot_change == SignalSlotChange::Yes);+ old_slottable.visit([&](auto const& node) {+ node->set_assigned_slot(nullptr);+ });+ if (auto const* element = old_slottable.template get_pointer<GC::Ref<Element>>())+ CSS::record_element_assigned_slot_changed(**element, slot.ptr());+ }}// 4. For each slottable in slottables, set slottable’s assigned slot to slot.@@ -284,6 +324,7 @@ void assign_slottables(GC::Ref<HTML::HTMLSlotElement> slot)auto old_slot = slottable.visit([](auto const& node) { return node->assigned_slot_internal(); });if (old_slot == slot)continue;+ VERIFY(signal_slot_change == SignalSlotChange::Yes);slottable.visit([&](auto& node) {node->set_assigned_slot(slot);});@@ -300,10 +341,8 @@ void assign_slottables(GC::Ref<HTML::HTMLSlotElement> slot)// the text nodes among them.CSS::record_slot_assignment_changed(slot);- if (assignment_changed) {- slot->set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::SlotAssignmentChange);- CSS::Invalidation::invalidate_style_after_slot_assignment_change(slot);- }+ if (assignment_changed && signal_slot_change == SignalSlotChange::Yes)+ invalidate_after_slot_assignment_change(slot);}// https://dom.spec.whatwg.org/#assign-slotables-for-a-tree@@ -337,8 +376,21 @@ void assign_a_slot(Slottable const& slottable)auto slot = find_a_slot(slottable);// 2. If slot is non-null, then run assign slottables for slot.- if (slot != nullptr)- assign_slottables(*slot);+ if (slot == nullptr)+ return;++ // AD-HOC: Assigned nodes are recomputed lazily.+ auto old_slot = slottable.visit([](auto const& node) { return node->assigned_slot_internal(); });+ change_assigned_slot(slottable, *slot, old_slot, slot);+}++void unassign_a_slot(Node& node)+{+ auto slot = assigned_slot_for_node(node);+ if (slot == nullptr)+ return;++ change_assigned_slot(node.as_slottable(), *slot, slot, nullptr);}// https://dom.spec.whatwg.org/#signal-a-slot-changediff --git a/Libraries/LibWeb/DOM/Slottable.h b/Libraries/LibWeb/DOM/Slottable.hindex fee1f18b0b6..f78e3946a0f 100644--- a/Libraries/LibWeb/DOM/Slottable.h+++ b/Libraries/LibWeb/DOM/Slottable.h@@ -60,15 +60,21 @@ enum class OpenFlag {Unset,};+enum class SignalSlotChange {+ No,+ Yes,+};+GC::Ptr<HTML::HTMLSlotElement> assigned_slot_for_node(GC::Ref<Node>);bool is_an_assigned_slottable(GC::Ref<Node>);GC::Ptr<HTML::HTMLSlotElement> find_a_slot(Slottable const&, OpenFlag = OpenFlag::Unset);Vector<Slottable> find_slottables(GC::Ref<HTML::HTMLSlotElement>);Vector<Slottable> find_flattened_slottables(GC::Ref<HTML::HTMLSlotElement>);-void assign_slottables(GC::Ref<HTML::HTMLSlotElement>);+void assign_slottables(GC::Ref<HTML::HTMLSlotElement>, SignalSlotChange = SignalSlotChange::Yes);void assign_slottables_for_a_tree(GC::Ref<Node>);void assign_a_slot(Slottable const&);+void unassign_a_slot(Node&);void signal_a_slot_change(GC::Ref<HTML::HTMLSlotElement>);}diff --git a/Libraries/LibWeb/HTML/HTMLSlotElement.cpp b/Libraries/LibWeb/HTML/HTMLSlotElement.cppindex 51c1754c2e5..52b983e0a9b 100644--- a/Libraries/LibWeb/HTML/HTMLSlotElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLSlotElement.cpp@@ -40,6 +40,7 @@ Vector<GC::Root<DOM::Node>> HTMLSlotElement::assigned_nodes(AssignedNodesFlatten{// 1. If options["flatten"] is false, then return this's assigned nodes.if (flatten == AssignedNodesFlatten::No) {+ assign_slottables_if_needed();Vector<GC::Root<DOM::Node>> assigned_nodes;assigned_nodes.ensure_capacity(assigned_nodes_internal().size());@@ -75,6 +76,7 @@ Vector<GC::Root<DOM::Element>> HTMLSlotElement::assigned_elements(AssignedNodesF{// 1. If options["flatten"] is false, then return this's assigned nodes, filtered to contain only Element nodes.if (flatten == AssignedNodesFlatten::No) {+ assign_slottables_if_needed();Vector<GC::Root<DOM::Element>> assigned_nodes;for (auto const& node : assigned_nodes_internal()) {@@ -100,9 +102,18 @@ Vector<GC::Root<DOM::Element>> HTMLSlotElement::assigned_elements(Bindings::Assireturn assigned_elements(assigned_nodes_flatten(options));}+void HTMLSlotElement::assign_slottables_if_needed() const+{+ if (auto* shadow_root = as_if<DOM::ShadowRoot>(const_cast<HTMLSlotElement&>(*this).root()))+ shadow_root->assign_slottables_if_needed();+}+// https://html.spec.whatwg.org/multipage/scripting.html#dom-slot-assignvoid HTMLSlotElement::assign(GC::ConservativeVector<SlottableHandle> nodes){+ // AD-HOC: Assigned nodes are recomputed lazily.+ assign_slottables_if_needed();+// 1. For each node of this's manually assigned nodes, set node's manual slot assignment to null.for (auto& node : m_manually_assigned_nodes) {node.visit([&](auto& node) {@@ -158,6 +169,9 @@ void HTMLSlotElement::attribute_changed(Utf16FlyString const& local_name, Optionif (value == Utf16String {} && !old_value.has_value())return;+ // AD-HOC: Assigned nodes are recomputed lazily.+ assign_slottables_if_needed();+// OPTIMIZATION: Update the slot registry before changing the name.auto* shadow_root = as_if<DOM::ShadowRoot>(root());if (shadow_root)diff --git a/Libraries/LibWeb/HTML/HTMLSlotElement.h b/Libraries/LibWeb/HTML/HTMLSlotElement.hindex 31af22e6367..e3776560d9c 100644--- a/Libraries/LibWeb/HTML/HTMLSlotElement.h+++ b/Libraries/LibWeb/HTML/HTMLSlotElement.h@@ -47,6 +47,8 @@ public:ReadonlySpan<DOM::Slottable> manually_assigned_nodes() const { return m_manually_assigned_nodes; }+ void assign_slottables_if_needed() const;+private:HTMLSlotElement(DOM::Document&, DOM::QualifiedName);diff --git a/Tests/LibWeb/Text/expected/DOM/slot-assignment-after-adoption.txt b/Tests/LibWeb/Text/expected/DOM/slot-assignment-after-adoption.txtnew file mode 100644index 00000000000..f71b9976b19--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/slot-assignment-after-adoption.txt@@ -0,0 +1,4 @@+one adoption: 123 x 17+assigned: true+two adoptions: 123 x 17+assigned: truediff --git a/Tests/LibWeb/Text/expected/DOM/slot-assignment-after-host-child-changes.txt b/Tests/LibWeb/Text/expected/DOM/slot-assignment-after-host-child-changes.txtnew file mode 100644index 00000000000..eaed4e33304--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/slot-assignment-after-host-child-changes.txt@@ -0,0 +1,29 @@+assignedNodes after appending three children: 3+assignedSlot of the last appended child is the slot: true+slotchange events after appending three children: 1+slotchange events after appending one more child: 2+assignedNodes after removing a child: 3+assignedSlot of the removed child: null+slotchange events after removing a child: 3+assignedNodes after renaming the slot: 0+slotchange events after renaming the slot: 2+slotchange events after renaming the slot back: 3+assignedNodes of the removed slot: 0+slotchange events after removing the slot: 2+assignedSlot after changing the slot attribute is slot b: true+assignedNodes of slot a and slot b: 0, 1+slotchange events for slot a and slot b: 2, 1+slotchange events after setting the same slot name: 2, 1+slotchange events after adding fallback content to an empty slot: 1+slotchange events after adding fallback content to a filled slot: 2+offsetWidth of a slotted child: 50+event path passes through the slot: true+assignedSlot after changing the slot attribute of a manually assigned child: true+slotchange events after changing the slot attribute of a manually assigned child: 1+offsetWidth of a child assigned to a newly inserted slot: 50+offsetWidth of a moved child after its previous host was removed: 50+assignedNodes after inserting into a manual shadow tree: 1+assignedNodes after moving within a manual shadow tree: 1+event path of a manually assigned sibling passes through the slot: true+event path of a manually assigned sibling after a removal passes through the slot: true+assignedNodes after moving a text node into a host: 1diff --git a/Tests/LibWeb/Text/input/DOM/slot-assignment-after-adoption.html b/Tests/LibWeb/Text/input/DOM/slot-assignment-after-adoption.htmlnew file mode 100644index 00000000000..306c96fa66d--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/slot-assignment-after-adoption.html@@ -0,0 +1,24 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ for (const adoptTwice of [false, true]) {+ const source = document.implementation.createHTMLDocument();+ const intermediate = document.implementation.createHTMLDocument();+ const host = source.createElement("div");+ const shadow = host.attachShadow({ mode: "open" });+ shadow.innerHTML = "<slot></slot>";+ const slot = shadow.firstChild;+ const child = source.createElement("div");+ child.style.cssText = "width: 123px; height: 17px";+ host.append(child);++ if (adoptTwice)+ intermediate.adoptNode(host);+ document.body.append(host);+ println(`${adoptTwice ? "two adoptions" : "one adoption"}: ${child.offsetWidth} x ${child.offsetHeight}`);+ println(`assigned: ${slot.assignedNodes()[0] === child}`);+ host.remove();+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/DOM/slot-assignment-after-host-child-changes.html b/Tests/LibWeb/Text/input/DOM/slot-assignment-after-host-child-changes.htmlnew file mode 100644index 00000000000..6796d5c6b66--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/slot-assignment-after-host-child-changes.html@@ -0,0 +1,185 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const slotchangeCounts = new Map();+ const observe = slot => {+ slotchangeCounts.set(slot, 0);+ slot.addEventListener("slotchange", () => slotchangeCounts.set(slot, slotchangeCounts.get(slot) + 1));+ };+ const microtask = () => Promise.resolve();+ const createHost = shadowHTML => {+ const host = document.createElement("div");+ host.attachShadow({ mode: "open" }).innerHTML = shadowHTML;+ document.body.appendChild(host);+ return host;+ };+ const createChild = slotName => {+ const child = document.createElement("div");+ if (slotName)+ child.slot = slotName;+ return child;+ };++ const host1 = createHost("<slot></slot>");+ const slot1 = host1.shadowRoot.firstChild;+ observe(slot1);+ const children = [createChild(), createChild(), createChild()];+ for (const child of children)+ host1.appendChild(child);+ println(`assignedNodes after appending three children: ${slot1.assignedNodes().length}`);+ println(`assignedSlot of the last appended child is the slot: ${children[2].assignedSlot === slot1}`);+ await microtask();+ println(`slotchange events after appending three children: ${slotchangeCounts.get(slot1)}`);+ host1.appendChild(createChild());+ await microtask();+ println(`slotchange events after appending one more child: ${slotchangeCounts.get(slot1)}`);+ children[0].remove();+ println(`assignedNodes after removing a child: ${slot1.assignedNodes().length}`);+ println(`assignedSlot of the removed child: ${children[0].assignedSlot}`);+ await microtask();+ println(`slotchange events after removing a child: ${slotchangeCounts.get(slot1)}`);++ const host2 = createHost('<slot name="a"></slot>');+ const slot2 = host2.shadowRoot.firstChild;+ observe(slot2);+ host2.appendChild(createChild("a"));+ await microtask();+ slot2.name = "b";+ println(`assignedNodes after renaming the slot: ${slot2.assignedNodes().length}`);+ await microtask();+ println(`slotchange events after renaming the slot: ${slotchangeCounts.get(slot2)}`);+ slot2.name = "a";+ await microtask();+ println(`slotchange events after renaming the slot back: ${slotchangeCounts.get(slot2)}`);++ const host3 = createHost("<slot></slot>");+ const slot3 = host3.shadowRoot.firstChild;+ observe(slot3);+ host3.appendChild(createChild());+ await microtask();+ slot3.remove();+ println(`assignedNodes of the removed slot: ${slot3.assignedNodes().length}`);+ await microtask();+ println(`slotchange events after removing the slot: ${slotchangeCounts.get(slot3)}`);++ const host4 = createHost('<slot name="a"></slot><slot name="b"></slot>');+ const [slot4a, slot4b] = host4.shadowRoot.children;+ observe(slot4a);+ observe(slot4b);+ const child4 = createChild("a");+ host4.appendChild(child4);+ await microtask();+ child4.slot = "b";+ println(`assignedSlot after changing the slot attribute is slot b: ${child4.assignedSlot === slot4b}`);+ println(`assignedNodes of slot a and slot b: ${slot4a.assignedNodes().length}, ${slot4b.assignedNodes().length}`);+ await microtask();+ println(`slotchange events for slot a and slot b: ${slotchangeCounts.get(slot4a)}, ${slotchangeCounts.get(slot4b)}`);+ child4.setAttribute("slot", "b");+ await microtask();+ println(`slotchange events after setting the same slot name: ${slotchangeCounts.get(slot4a)}, ${slotchangeCounts.get(slot4b)}`);++ const host5 = createHost("<slot></slot>");+ const slot5 = host5.shadowRoot.firstChild;+ observe(slot5);+ slot5.appendChild(createChild());+ await microtask();+ println(`slotchange events after adding fallback content to an empty slot: ${slotchangeCounts.get(slot5)}`);+ host5.appendChild(createChild());+ await microtask();+ slot5.appendChild(createChild());+ await microtask();+ println(`slotchange events after adding fallback content to a filled slot: ${slotchangeCounts.get(slot5)}`);++ const host6 = createHost("<style>::slotted(div) { width: 50px; height: 10px; }</style><slot></slot>");+ const slot6 = host6.shadowRoot.lastChild;+ const child6 = createChild();+ host6.appendChild(child6);+ println(`offsetWidth of a slotted child: ${child6.offsetWidth}`);+ let composedPath = [];+ child6.addEventListener("test", event => composedPath = event.composedPath());+ child6.dispatchEvent(new Event("test", { composed: true, bubbles: true }));+ println(`event path passes through the slot: ${composedPath.includes(slot6)}`);++ const host7 = document.createElement("div");+ host7.attachShadow({ mode: "open", slotAssignment: "manual" }).innerHTML = "<slot></slot>";+ document.body.appendChild(host7);+ const slot7 = host7.shadowRoot.firstChild;+ observe(slot7);+ const child7 = createChild();+ host7.appendChild(child7);+ slot7.assign(child7);+ await microtask();+ child7.slot = "a";+ println(`assignedSlot after changing the slot attribute of a manually assigned child: ${child7.assignedSlot === slot7}`);+ await microtask();+ println(`slotchange events after changing the slot attribute of a manually assigned child: ${slotchangeCounts.get(slot7)}`);++ const host8 = createHost('<slot name="b"></slot>');+ const child8 = createChild("b");+ host8.appendChild(child8);+ child8.offsetWidth;+ host8.shadowRoot.innerHTML = '<style>::slotted(div) { width: 50px; }</style><slot name="a"></slot>';+ child8.slot = "a";+ println(`offsetWidth of a child assigned to a newly inserted slot: ${child8.offsetWidth}`);++ const host9 = createHost("<slot></slot>");+ const host10 = createHost('<style>::slotted(div) { width: 50px; }</style><slot></slot>');+ const child9 = createChild();+ host9.appendChild(child9);+ child9.offsetWidth;+ host10.moveBefore(child9, null);+ host9.remove();+ println(`offsetWidth of a moved child after its previous host was removed: ${child9.offsetWidth}`);++ const createManualHost = () => {+ const host = document.createElement("div");+ host.attachShadow({ mode: "open", slotAssignment: "manual" }).innerHTML = "<slot></slot><div></div><div></div>";+ document.body.appendChild(host);+ const slot = host.shadowRoot.firstChild;+ const child = createChild();+ slot.assign(child);+ host.appendChild(child);+ return host;+ };+ const host11 = createManualHost();+ host11.shadowRoot.appendChild(document.createElement("div"));+ println(`assignedNodes after inserting into a manual shadow tree: ${host11.shadowRoot.firstChild.assignedNodes().length}`);+ const host12 = createManualHost();+ host12.shadowRoot.moveBefore(host12.shadowRoot.lastChild, host12.shadowRoot.children[1]);+ println(`assignedNodes after moving within a manual shadow tree: ${host12.shadowRoot.firstChild.assignedNodes().length}`);++ const host13 = document.createElement("div");+ host13.attachShadow({ mode: "open", slotAssignment: "manual" }).innerHTML = "<slot></slot>";+ document.body.appendChild(host13);+ const slot13 = host13.shadowRoot.firstChild;+ const child13 = createChild();+ const sibling13 = createChild();+ slot13.assign(child13, sibling13);+ host13.append(child13, sibling13);+ child13.slot = "a";+ sibling13.addEventListener("test", event => composedPath = event.composedPath());+ sibling13.dispatchEvent(new Event("test", { composed: true, bubbles: true }));+ println(`event path of a manually assigned sibling passes through the slot: ${composedPath.includes(slot13)}`);++ const host14 = document.createElement("div");+ host14.attachShadow({ mode: "open", slotAssignment: "manual" }).innerHTML = "<slot></slot>";+ document.body.appendChild(host14);+ const slot14 = host14.shadowRoot.firstChild;+ const child14 = createChild();+ const sibling14 = createChild();+ host14.appendChild(child14);+ slot14.assign(child14, sibling14);+ host14.appendChild(sibling14);+ child14.remove();+ sibling14.addEventListener("test", event => composedPath = event.composedPath());+ sibling14.dispatchEvent(new Event("test", { composed: true, bubbles: true }));+ println(`event path of a manually assigned sibling after a removal passes through the slot: ${composedPath.includes(slot14)}`);++ const host15 = createHost("<slot></slot>");+ const text15 = document.createTextNode("text");+ document.body.appendChild(text15);+ host15.moveBefore(text15, null);+ println(`assignedNodes after moving a text node into a host: ${host15.shadowRoot.firstChild.assignedNodes().length}`);+ });+</script>