Skip to content

Truly independent web browser

LibWeb: Correct transient registered observer bookkeeping and order

Shannon Boothc0c1778503b3
diff --git a/Libraries/LibWeb/DOM/MutationObserver.cpp b/Libraries/LibWeb/DOM/MutationObserver.cpp
index 6f205a91e72..7ec85c0a8ba 100644
--- a/Libraries/LibWeb/DOM/MutationObserver.cpp
+++ b/Libraries/LibWeb/DOM/MutationObserver.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/QuickSort.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/Array.h>
#include <LibWeb/Bindings/MutationRecord.h>
@@ -28,16 +29,22 @@ GC_DEFINE_ALLOCATOR(MutationObserver);
GC_DEFINE_ALLOCATOR(RegisteredObserver);
GC_DEFINE_ALLOCATOR(TransientRegisteredObserver);
-WebIDL::ExceptionOr<GC::Ref<MutationObserver>> MutationObserver::create(GC::Ptr<WebIDL::CallbackType> callback)
+GC::Ref<MutationObserver> MutationObserver::create_for_constructor(JS::Object& relevant_global_object, GC::Ptr<WebIDL::CallbackType> callback)
{
- return GC::Heap::the().allocate<MutationObserver>(callback);
+ return GC::Heap::the().allocate<MutationObserver>(callback, HTML::relevant_similar_origin_window_agent(relevant_global_object));
}
// https://dom.spec.whatwg.org/#dom-mutationobserver-mutationobserver
-MutationObserver::MutationObserver(GC::Ptr<WebIDL::CallbackType> callback)
- : m_callback(move(callback))
+MutationObserver::MutationObserver(GC::Ptr<WebIDL::CallbackType> callback, HTML::SimilarOriginWindowAgent& relevant_agent)
{
- // The new MutationObserver(callback) constructor steps are to set this’s callback to callback.
+ // 1. Set this’s callback to callback.
+ m_callback = move(callback);
+
+ // 2. Set this’s creation index to this’s relevant agent’s mutation observer counter.
+ m_creation_index = relevant_agent.mutation_observer_counter;
+
+ // 3. Increase this’s relevant agent’s mutation observer counter by 1.
+ ++relevant_agent.mutation_observer_counter;
}
MutationObserver::~MutationObserver() = default;
@@ -109,27 +116,40 @@ WebIDL::ExceptionOr<void> MutationObserver::observe(Node& target, MutationObserv
if (options.character_data_old_value.has_value() && options.character_data_old_value.value() && !options.character_data.value())
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "characterData must be true if characterDataOldValue is true."_utf16 };
- // 7. For each registered of target’s registered observer list, if registered’s observer is this:
- bool updated_existing_observer = false;
- if (target.registered_observer_list()) {
- for (auto& registered_observer : *target.registered_observer_list()) {
- if (registered_observer->observer().ptr() != this)
- continue;
-
- updated_existing_observer = true;
+ // 7. Let registered be the registered observer in target’s registered observer list that is not a transient
+ // registered observer and whose observer is this, if any; otherwise null.
+ GC::Ptr<RegisteredObserver> registered;
+ if (auto* registered_observer_list = target.registered_observer_list()) {
+ for (auto& registered_observer : *registered_observer_list) {
+ if (!is<TransientRegisteredObserver>(*registered_observer) && registered_observer->observer().ptr() == this) {
+ registered = registered_observer;
+ break;
+ }
+ }
+ }
- // 1. For each node of this’s node list, remove all transient registered observers whose source is registered from node’s registered observer list.
- remove_transient_registered_observers(registered_observer.ptr());
+ // 8. If registered is non-null:
+ if (registered) {
+ // 1. For each node of this’s transient node set: remove all transient registered observers whose source is
+ // registered from node’s registered observer list.
+ for (auto& node : m_transient_node_set) {
+ if (!node)
+ continue;
- // 2. Set registered’s options to options.
- registered_observer->set_options(move(options));
- target.document().add_mutation_observer_types(registered_observer->options());
- break;
+ if (auto* registered_observer_list = node->registered_observer_list()) {
+ registered_observer_list->remove_all_matching([&registered](RegisteredObserver& registered_observer) {
+ auto* transient = as_if<TransientRegisteredObserver>(registered_observer);
+ return transient && transient->source().ptr() == registered.ptr();
+ });
+ }
}
- }
- // 8. Otherwise:
- if (!updated_existing_observer) {
+ // 2. Set registered’s options to options.
+ registered->set_options(move(options));
+ target.document().add_mutation_observer_types(registered->options());
+ }
+ // 9. Otherwise:
+ else {
// 1. Append a new registered observer whose observer is this and options is options to target’s registered observer list.
auto new_registered_observer = RegisteredObserver::create(*this, options);
target.add_registered_observer(new_registered_observer);
@@ -162,9 +182,13 @@ void MutationObserver::disconnect()
}
}
+ // 2. Remove transient registered observers for this.
remove_transient_registered_observers();
- // 2. Empty this’s record queue.
+ // 3. Empty this’s node list.
+ m_node_list.clear();
+
+ // 4. Empty this’s record queue.
m_record_queue.clear();
}
@@ -183,47 +207,33 @@ Vector<GC::Root<MutationRecord>> MutationObserver::take_records()
return records;
}
-void MutationObserver::add_transient_registered_node(Badge<Node>, Node& node)
+void MutationObserver::append_to_transient_node_set(Badge<Node>, Node& node)
{
- for (auto& transient_registered_node : m_transient_registered_node_list) {
- if (transient_registered_node.ptr().ptr() == &node)
+ for (auto& transient_node : m_transient_node_set) {
+ if (transient_node.ptr().ptr() == &node)
return;
}
- m_transient_registered_node_list.append(node);
+ m_transient_node_set.append(node);
}
-void MutationObserver::remove_transient_registered_observers(RegisteredObserver const* source)
+// https://dom.spec.whatwg.org/#remove-transient-registered-observers
+void MutationObserver::remove_transient_registered_observers()
{
- for (auto& node : m_transient_registered_node_list) {
+ // 1. For each node of observer’s transient node set: remove all transient registered observers whose observer is
+ // observer from node’s registered observer list.
+ for (auto& node : m_transient_node_set) {
if (!node)
continue;
if (auto* registered_observer_list = node->registered_observer_list()) {
- registered_observer_list->remove_all_matching([this, source](RegisteredObserver& registered_observer) {
- auto* transient = as_if<TransientRegisteredObserver>(registered_observer);
- return transient && transient->observer().ptr() == this && (!source || transient->source().ptr() == source);
+ registered_observer_list->remove_all_matching([this](RegisteredObserver& registered_observer) {
+ return is<TransientRegisteredObserver>(registered_observer) && registered_observer.observer().ptr() == this;
});
}
}
- if (!source) {
- m_transient_registered_node_list.clear();
- return;
- }
-
- m_transient_registered_node_list.remove_all_matching([this](GC::Weak<Node> const& node) {
- if (!node)
- return true;
- auto const* registered_observer_list = node->registered_observer_list();
- if (!registered_observer_list)
- return true;
- for (auto const& registered_observer : *registered_observer_list) {
- auto const* transient = as_if<TransientRegisteredObserver>(*registered_observer);
- if (transient && transient->observer().ptr() == this)
- return false;
- }
- return true;
- });
+ // 2. Empty observer’s transient node set.
+ m_transient_node_set.clear();
}
// https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask
@@ -242,22 +252,25 @@ void queue_mutation_observer_microtask(HTML::SimilarOriginWindowAgent& surroundi
// 1. Set the surrounding agent’s mutation observer microtask queued to false.
surrounding_agent.mutation_observer_microtask_queued = false;
- // 2. Let notifySet be a clone of the surrounding agent’s pending mutation observers.
+ // 2. Let notifyList be the result of sorting the surrounding agent’s pending mutation observers in ascending
+ // order, with a being less than b if a’s creation index is less than b’s creation index.
// 3. Empty the surrounding agent’s pending mutation observers.
- auto notify_set = move(surrounding_agent.pending_mutation_observers);
+ auto notify_list = move(surrounding_agent.pending_mutation_observers);
+ quick_sort(notify_list, [](auto const& a, auto const& b) {
+ return a->creation_index() < b->creation_index();
+ });
// 4. Let signalSet be a clone of the surrounding agent’s signal slots.
// 5. Empty the surrounding agent’s signal slots.
auto signal_set = move(surrounding_agent.signal_slots);
- // 6. For each mo of notifySet:
- for (auto& mutation_observer : notify_set) {
+ // 6. For each mo of notifyList:
+ for (auto& mutation_observer : notify_list) {
// 1. Let records be a clone of mo’s record queue.
// 2. Empty mo’s record queue.
auto records = mutation_observer->take_records();
- // 3. For each node of mo’s node list, remove all transient registered observers whose observer is mo from
- // node’s registered observer list.
+ // 3. Remove transient registered observers for mo.
mutation_observer->remove_transient_registered_observers();
// 4. If records is not empty, then invoke mo’s callback with « records, mo » and "report", and with
diff --git a/Libraries/LibWeb/DOM/MutationObserver.h b/Libraries/LibWeb/DOM/MutationObserver.h
index ba9f99c5ece..1975324bc7e 100644
--- a/Libraries/LibWeb/DOM/MutationObserver.h
+++ b/Libraries/LibWeb/DOM/MutationObserver.h
@@ -44,7 +44,7 @@ class MutationObserver final : public Bindings::GCAllocatedWrappable {
GC_DECLARE_ALLOCATOR(MutationObserver);
public:
- static WebIDL::ExceptionOr<GC::Ref<MutationObserver>> create(GC::Ptr<WebIDL::CallbackType>);
+ static GC::Ref<MutationObserver> create_for_constructor(JS::Object& relevant_global_object, GC::Ptr<WebIDL::CallbackType>);
virtual ~MutationObserver() override;
WebIDL::ExceptionOr<void> observe(Node& target, MutationObserverOptions options);
@@ -55,30 +55,35 @@ public:
Vector<GC::Weak<Node>>& node_list() { return m_node_list; }
Vector<GC::Weak<Node>> const& node_list() const { return m_node_list; }
- void add_transient_registered_node(Badge<Node>, Node&);
- void remove_transient_registered_observers(RegisteredObserver const* source = nullptr);
+ void append_to_transient_node_set(Badge<Node>, Node&);
+ void remove_transient_registered_observers();
WebIDL::CallbackType& callback() { return *m_callback; }
+ u64 creation_index() const { return m_creation_index; }
+
void enqueue_record(Badge<Node>, GC::Ref<MutationRecord> mutation_record)
{
m_record_queue.append(*mutation_record);
}
private:
- explicit MutationObserver(GC::Ptr<WebIDL::CallbackType>);
+ MutationObserver(GC::Ptr<WebIDL::CallbackType>, HTML::SimilarOriginWindowAgent& relevant_agent);
virtual void visit_edges(GC::Cell::Visitor&) override;
// https://dom.spec.whatwg.org/#concept-mo-callback
GC::Ptr<WebIDL::CallbackType> m_callback;
+ // https://dom.spec.whatwg.org/#mutationobserver-creation-index
+ u64 m_creation_index { 0 };
+
// https://dom.spec.whatwg.org/#mutationobserver-node-list
// Registered observers in a node’s registered observer list have a weak reference to the node.
Vector<GC::Weak<Node>> m_node_list;
- // Nodes that currently have transient registered observers for this observer.
- Vector<GC::Weak<Node>> m_transient_registered_node_list;
+ // https://dom.spec.whatwg.org/#mutationobserver-transient-node-set
+ Vector<GC::Weak<Node>> m_transient_node_set;
// https://dom.spec.whatwg.org/#concept-mo-queue
Vector<GC::Ref<MutationRecord>> m_record_queue;
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index 08bb280a61e..0f52e270134 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -8,6 +8,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/AnyOf.h>
#include <AK/HashTable.h>
#include <AK/JsonObjectSerializer.h>
#include <AK/NeverDestroyed.h>
@@ -1628,18 +1629,54 @@ void Node::run_removing_steps(Node& parent, Node& parent_root, bool was_tracked_
});
}
-void Node::add_transient_registered_observers_for_removal(Node& parent)
+// https://dom.spec.whatwg.org/#add-transient-registered-observers
+void Node::add_transient_registered_observers(Node& parent)
{
+ // 1. For each inclusive ancestor inclusiveAncestor of parent, and then for each registered of inclusiveAncestor’s
+ // registered observer list:
for (auto* inclusive_ancestor = &parent; inclusive_ancestor; inclusive_ancestor = inclusive_ancestor->parent()) {
auto* registered_observer_list = inclusive_ancestor->registered_observer_list();
if (!registered_observer_list)
continue;
for (auto& registered : *registered_observer_list) {
- if (registered->options().subtree) {
- auto transient_observer = TransientRegisteredObserver::create(registered->observer(), registered->options(), registered);
- add_registered_observer(move(transient_observer));
- registered->observer()->add_transient_registered_node({}, *this);
+ // 1. If registered’s options["subtree"] is false, then continue.
+ if (!registered->options().subtree)
+ continue;
+
+ // 2. Let observer be registered’s observer.
+ auto observer = registered->observer();
+
+ // 3. Let source be registered’s source if registered is a transient registered observer; otherwise
+ // registered.
+ GC::Ref<RegisteredObserver> source = registered;
+ if (auto* transient = as_if<TransientRegisteredObserver>(*registered))
+ source = transient->source();
+
+ // 4. If node’s registered observer list contains a transient registered observer whose source is source,
+ // then continue.
+ if (auto const* node_registered_observer_list = this->registered_observer_list()) {
+ auto contains_transient_with_source = any_of(*node_registered_observer_list, [&source](auto const& node_registered) {
+ auto const* transient = as_if<TransientRegisteredObserver>(*node_registered);
+ return transient && transient->source() == source;
+ });
+ if (contains_transient_with_source)
+ continue;
}
+
+ // 5. Append a new transient registered observer whose observer is observer, options is source’s options,
+ // and source is source to node’s registered observer list.
+ add_registered_observer(TransientRegisteredObserver::create(observer, source->options(), source));
+
+ // 6. Append a weak reference to node to observer’s transient node set.
+ observer->append_to_transient_node_set({}, *this);
+
+ // 7. Append observer to the surrounding agent’s pending mutation observers.
+ auto& surrounding_agent = HTML::relevant_similar_origin_window_agent(*this);
+ if (!surrounding_agent.pending_mutation_observers.contains_slow(observer))
+ surrounding_agent.pending_mutation_observers.append(observer);
+
+ // 8. Queue a mutation observer microtask.
+ queue_mutation_observer_microtask(surrounding_agent);
}
}
}
@@ -1724,11 +1761,8 @@ void Node::remove(bool suppress_observers)
// chain it hung off. Nothing about any element in that chain moved, so it has to be told.
CSS::Invalidation::invalidate_style_after_subtree_place_changed(*this, parent);
- // 15. For each inclusive ancestor inclusiveAncestor of parent, and then for each registered of inclusiveAncestor’s
- // registered observer list, if registered’s options["subtree"] is true, then append a new transient registered
- // observer whose observer is registered’s observer, options is registered’s options, and source is registered
- // to node’s registered observer list.
- add_transient_registered_observers_for_removal(*parent);
+ // 15. Add transient registered observers given node and parent.
+ add_transient_registered_observers(*parent);
// 16. If suppressObservers is false, then queue a tree mutation record for parent with « », « node »,
// oldPreviousSibling, and oldNextSibling.
@@ -2047,7 +2081,10 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)
assign_slottables(slot);
}
- // 17. If child is non-null:
+ // 17. Add transient registered observers given node and oldParent.
+ add_transient_registered_observers(*old_parent);
+
+ // 18. If child is non-null:
if (child) {
// 1. For each live range whose start node is newParent and start offset is greater than child’s index:
// increase its start offset by 1.
@@ -2063,14 +2100,14 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)
}
}
- // 18. Let newPreviousSibling be child’s previous sibling if child is non-null, and newParent’s last child otherwise.
+ // 19. Let newPreviousSibling be child’s previous sibling if child is non-null, and newParent’s last child otherwise.
auto* new_previous_sibling = child ? child->previous_sibling() : new_parent.last_child();
- // 19. If child is null, then append node to newParent’s children.
+ // 20. If child is null, then append node to newParent’s children.
if (!child) {
new_parent.append_child_impl(*this);
}
- // 20. Otherwise, insert node into newParent’s children before child’s index.
+ // 21. Otherwise, insert node into newParent’s children before child’s index.
else {
new_parent.insert_before_impl(*this, child);
}
@@ -2100,7 +2137,7 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)
new_parent.set_child_needs_layout_tree_update(true);
}
- // 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.
+ // 22. 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 (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;
@@ -2123,21 +2160,21 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)
});
}
- // 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.
+ // 23. 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_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.
+ // 24. Run assign slottables for a tree with node’s 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);
- // 24. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
+ // 25. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
for_each_shadow_including_inclusive_descendant([this, &new_parent, old_parent](Node& inclusive_descendant) {
// 1. Let isSubtreeRoot be true if inclusiveDescendant is node; otherwise false.
auto is_subtree_root = (&inclusive_descendant == this) ? IsSubtreeRoot::Yes : IsSubtreeRoot::No;
@@ -2160,11 +2197,11 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)
for (auto const& state : previous_read_write_states)
CSS::Invalidation::invalidate_style_after_read_write_state_change(*state.element, state.value);
- // 25. Queue a tree mutation record for oldParent with « », « node », oldPreviousSibling, and oldNextSibling.
+ // 26. Queue a tree mutation record for oldParent with « », « node », oldPreviousSibling, and oldNextSibling.
GC::Ref<Node> moved_node = *this;
old_parent->queue_tree_mutation_record({}, { &moved_node, 1 }, old_previous_sibling, old_next_sibling);
- // 26. Queue a tree mutation record for newParent with « node », « », newPreviousSibling, and child.
+ // 27. Queue a tree mutation record for newParent with « node », « », newPreviousSibling, and child.
new_parent.queue_tree_mutation_record({ &moved_node, 1 }, {}, new_previous_sibling, child);
old_parent->invalidate_html_collection_caches_in_ancestors(affects_elements);
@@ -3049,11 +3086,8 @@ void Node::remove_all_children(bool suppress_observers)
if (a_child_holds_a_propagating_state_source)
CSS::Invalidation::invalidate_style_after_subtree_place_changed(*child, this);
- // 15. For each inclusive ancestor inclusiveAncestor of parent, and then for each registered of
- // inclusiveAncestor’s registered observer list, if registered’s options["subtree"] is true, then append a
- // new transient registered observer whose observer is registered’s observer, options is registered’s
- // options, and source is registered to node’s registered observer list.
- child->add_transient_registered_observers_for_removal(*this);
+ // 15. Add transient registered observers given node and parent.
+ child->add_transient_registered_observers(*this);
// 16. If suppressObservers is false, then queue a tree mutation record for parent with « », « node »,
// oldPreviousSibling, and oldNextSibling.
@@ -4027,14 +4061,14 @@ void Node::queue_mutation_record(Utf16FlyString const& type, Optional<Utf16FlySt
}
}
- // OPTIMIZATION: If there are no interested observers, bail without doing any more work.
+ // 4. If interestedObservers is empty, then return.
if (interested_observers.is_empty() && !page.listen_for_dom_mutations())
return;
auto added_nodes_list = StaticNodeList::create(added_nodes);
auto removed_nodes_list = StaticNodeList::create(removed_nodes);
- // 4. For each observer → mappedOldValue of interestedObservers:
+ // 5. For each observer → mappedOldValue of interestedObservers:
for (auto& [observer, mapped_old_value] : interested_observers) {
// 1. Let record be a new MutationRecord object with its type set to type, target set to target, attributeName set to name, attributeNamespace set to namespace, oldValue set to mappedOldValue,
// addedNodes set to addedNodes, removedNodes set to removedNodes, previousSibling set to previousSibling, and nextSibling set to nextSibling.
@@ -4044,10 +4078,12 @@ void Node::queue_mutation_record(Utf16FlyString const& type, Optional<Utf16FlySt
observer->enqueue_record({}, move(record));
// 3. Append observer to the surrounding agent’s pending mutation observers.
- HTML::relevant_similar_origin_window_agent(*this).pending_mutation_observers.append(*observer);
+ auto& pending_mutation_observers = HTML::relevant_similar_origin_window_agent(*this).pending_mutation_observers;
+ if (!pending_mutation_observers.contains_slow(GC::Ref { *observer }))
+ pending_mutation_observers.append(*observer);
}
- // 5. Queue a mutation observer microtask.
+ // 6. Queue a mutation observer microtask.
queue_mutation_observer_microtask(HTML::relevant_similar_origin_window_agent(*this));
// AD-HOC: Notify the UI if it is interested in DOM mutations (i.e. for DevTools).
diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.h
index 51d4958c2f8..4db7c0079d4 100644
--- a/Libraries/LibWeb/DOM/Node.h
+++ b/Libraries/LibWeb/DOM/Node.h
@@ -731,7 +731,7 @@ private:
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 add_transient_registered_observers(Node& parent);
void queue_tree_mutation_record_for_removal(Node& parent, GC::Ptr<Node> old_previous_sibling, GC::Ptr<Node> old_next_sibling);
void queue_tree_mutation_record(ReadonlySpan<GC::Ref<Node>> added_nodes, ReadonlySpan<GC::Ref<Node>> removed_nodes, Node* previous_sibling, Node* next_sibling);
diff --git a/Libraries/LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h b/Libraries/LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h
index 2350c37c1b0..34e5a973e7c 100644
--- a/Libraries/LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h
+++ b/Libraries/LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h
@@ -32,6 +32,10 @@ struct SimilarOriginWindowAgent : public Agent {
// Each similar-origin window agent also has pending mutation observers (a set of zero or more MutationObserver objects), which is initially empty.
GC::RootVector<GC::Ref<DOM::MutationObserver>> pending_mutation_observers;
+ // https://dom.spec.whatwg.org/#mutation-observer-counter
+ // Each similar-origin window agent also has a mutation observer counter (a number), which is initially 0.
+ u64 mutation_observer_counter { 0 };
+
// https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-reactions-stack
// Each similar-origin window agent has a custom element reactions stack, which is initially empty.
CustomElementReactionsStack custom_element_reactions_stack {};
diff --git a/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/MutationObserver-callback-order.window.txt b/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/MutationObserver-callback-order.window.txt
new file mode 100644
index 00000000000..dfc7cb44d30
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/MutationObserver-callback-order.window.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Pass
+Pass Mutation observers are notified in the order they were created
+Pass Mutation observers are notified in the order they were created, also when one observes a removed subtree
+Pass The mutation observer microtask is only queued once a record is queued for an observer
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.txt b/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.txt
new file mode 100644
index 00000000000..1c371d492a9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.txt
@@ -0,0 +1,20 @@
+Harness status: OK
+
+Found 15 tests
+
+15 Pass
+Pass Mutations in a removed subtree are observed until mutation observers are notified
+Pass Attribute mutations in a removed subtree are observed until mutation observers are notified
+Pass Mutations in a subtree removed by replaceChildren() are observed until mutation observers are notified
+Pass takeRecords() does not stop observing a removed subtree
+Pass A removed subtree is no longer observed after mutation observers are notified
+Pass A removed subtree is no longer observed after mutation observers are notified, even if no record was queued
+Pass A removed subtree is no longer observed after mutation observers are notified, even if the callback was not invoked
+Pass A subtree removed from a removed subtree is no longer observed after mutation observers are notified
+Pass Removing a node from an observed subtree queues the mutation observer microtask
+Pass disconnect() stops observing a removed subtree
+Pass disconnect() stops observing a subtree removed from a removed subtree
+Pass disconnect() does not affect another observer observing a removed subtree
+Pass observe() stops observing a removed subtree through the target, but not through other targets
+Pass observe() stops observing subtrees removed from a removed subtree
+Pass observe() on a node in a removed subtree keeps observing it after mutation observers are notified
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.txt b/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.txt
new file mode 100644
index 00000000000..6e23f80cf3d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass A subtree moved out of an observed subtree by moveBefore() is observed until mutation observers are notified
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-callback-order.window.html b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-callback-order.window.html
new file mode 100644
index 00000000000..d1cf5a88627
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-callback-order.window.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>MutationObserver: callback order</title>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../../dom/nodes/MutationObserver-callback-order.window.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-callback-order.window.js b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-callback-order.window.js
new file mode 100644
index 00000000000..b223e46a004
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-callback-order.window.js
@@ -0,0 +1,60 @@
+// META: title=MutationObserver: callback order
+"use strict";
+
+// Mutation observers are notified in the order they were created, not in the order in which they
+// got records.
+
+// Mutation observers are notified in a microtask, so they have been notified once a new task runs.
+function nextTask(t) {
+ return new Promise(resolve => t.step_timeout(resolve, 0));
+}
+
+promise_test(async t => {
+ const firstTarget = document.createElement("div");
+ const secondTarget = document.createElement("div");
+ const order = [];
+ const first = new MutationObserver(() => order.push("first"));
+ const second = new MutationObserver(() => order.push("second"));
+ first.observe(firstTarget, { attributes: true });
+ second.observe(secondTarget, { attributes: true });
+
+ secondTarget.setAttribute("data-test", "");
+ firstTarget.setAttribute("data-test", "");
+ await nextTask(t);
+
+ assert_array_equals(order, ["first", "second"]);
+}, "Mutation observers are notified in the order they were created");
+
+promise_test(async t => {
+ const parent = document.createElement("div");
+ const child = parent.appendChild(document.createElement("div"));
+ const order = [];
+ const first = new MutationObserver(() => order.push("first"));
+ const second = new MutationObserver(() => order.push("second"));
+ first.observe(parent, { childList: true });
+ second.observe(parent, { attributes: true, subtree: true });
+
+ // This queues a record for first, while second keeps observing child.
+ child.remove();
+ child.setAttribute("data-test", "");
+ await nextTask(t);
+
+ assert_array_equals(order, ["first", "second"]);
+}, "Mutation observers are notified in the order they were created, also when one observes a removed subtree");
+
+promise_test(async t => {
+ const target = document.createElement("div");
+ const order = [];
+ const observer = new MutationObserver(() => order.push("observer"));
+ observer.observe(target, { attributes: true });
+
+ // No observer gets a record for this mutation, so it does not queue the mutation observer
+ // microtask.
+ document.createElement("div").append("text");
+ Promise.resolve().then(() => order.push("promise"));
+ // This queues a record and therefore the mutation observer microtask, after the promise job.
+ target.setAttribute("data-test", "");
+ await nextTask(t);
+
+ assert_array_equals(order, ["promise", "observer"]);
+}, "The mutation observer microtask is only queued once a record is queued for an observer");
diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.html b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.html
new file mode 100644
index 00000000000..1f48830feed
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>MutationObserver: transient registered observers</title>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../../dom/nodes/MutationObserver-transient-registered-observers.window.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.js b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.js
new file mode 100644
index 00000000000..6d742849399
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/MutationObserver-transient-registered-observers.window.js
@@ -0,0 +1,265 @@
+// META: title=MutationObserver: transient registered observers
+"use strict";
+
+// When a node is removed from a subtree that is observed with subtree set to true, the node and its
+// descendants remain observed until mutation observers are notified.
+
+function createTree() {
+ const parent = document.createElement("div");
+ parent.id = "parent";
+ const child = parent.appendChild(document.createElement("div"));
+ child.id = "child";
+ const grandchild = child.appendChild(document.createElement("div"));
+ grandchild.id = "grandchild";
+ return { parent, child, grandchild };
+}
+
+function createElement(id) {
+ const element = document.createElement("span");
+ element.id = id;
+ return element;
+}
+
+function summarize(records) {
+ return records.map(({ type, target, addedNodes, removedNodes, attributeName }) => {
+ let summary = `${type} ${target.id}`;
+ for (const node of addedNodes) {
+ summary += ` +${node.id}`;
+ }
+ for (const node of removedNodes) {
+ summary += ` -${node.id}`;
+ }
+ if (attributeName !== null) {
+ summary += ` ${attributeName}`;
+ }
+ return summary;
+ });
+}
+
+// Mutation observers are notified in a microtask, so they have been notified once a new task runs.
+function nextTask(t) {
+ return new Promise(resolve => t.step_timeout(resolve, 0));
+}
+
+test(() => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ child.append(createElement("added"));
+
+ assert_array_equals(summarize(observer.takeRecords()), [
+ "childList parent -child",
+ "childList child +added"
+ ]);
+}, "Mutations in a removed subtree are observed until mutation observers are notified");
+
+test(() => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { attributes: true, subtree: true });
+
+ child.remove();
+ child.setAttribute("data-test", "");
+
+ assert_array_equals(summarize(observer.takeRecords()), ["attributes child data-test"]);
+}, "Attribute mutations in a removed subtree are observed until mutation observers are notified");
+
+test(() => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+
+ parent.replaceChildren();
+ child.append(createElement("added"));
+
+ assert_array_equals(summarize(observer.takeRecords()), [
+ "childList parent -child",
+ "childList child +added"
+ ]);
+}, "Mutations in a subtree removed by replaceChildren() are observed until mutation observers are notified");
+
+test(() => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ assert_array_equals(summarize(observer.takeRecords()), ["childList parent -child"]);
+
+ child.append(createElement("added"));
+ assert_array_equals(summarize(observer.takeRecords()), ["childList child +added"]);
+}, "takeRecords() does not stop observing a removed subtree");
+
+promise_test(async t => {
+ const { parent, child } = createTree();
+ const delivered = [];
+ const observer = new MutationObserver(records => delivered.push(...summarize(records)));
+ observer.observe(parent, { childList: true, subtree: true });
+
+ // This microtask is queued before the mutation observer microtask and therefore runs first.
+ Promise.resolve().then(() => child.append(createElement("before")));
+ child.remove();
+ await nextTask(t);
+ assert_array_equals(delivered, ["childList parent -child", "childList child +before"]);
+
+ child.append(createElement("after"));
+ assert_array_equals(summarize(observer.takeRecords()), []);
+}, "A removed subtree is no longer observed after mutation observers are notified");
+
+promise_test(async t => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(t.unreached_func("callback invoked"));
+ observer.observe(parent, { attributes: true, subtree: true });
+
+ // This does not queue a record as observer does not observe childList mutations.
+ child.remove();
+ await nextTask(t);
+
+ child.setAttribute("data-test", "");
+ assert_array_equals(summarize(observer.takeRecords()), []);
+}, "A removed subtree is no longer observed after mutation observers are notified, even if no record was queued");
+
+promise_test(async t => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(t.unreached_func("callback invoked"));
+ observer.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ assert_array_equals(summarize(observer.takeRecords()), ["childList parent -child"]);
+ await nextTask(t);
+
+ child.append(createElement("added"));
+ assert_array_equals(summarize(observer.takeRecords()), []);
+}, "A removed subtree is no longer observed after mutation observers are notified, even if the callback was not invoked");
+
+promise_test(async t => {
+ const { parent, child, grandchild } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ // grandchild is removed from a subtree that is itself only observed because it was removed.
+ grandchild.remove();
+ grandchild.append(createElement("before"));
+ assert_array_equals(summarize(observer.takeRecords()), [
+ "childList parent -child",
+ "childList child -grandchild",
+ "childList grandchild +before"
+ ]);
+ await nextTask(t);
+
+ grandchild.append(createElement("after"));
+ assert_array_equals(summarize(observer.takeRecords()), []);
+}, "A subtree removed from a removed subtree is no longer observed after mutation observers are notified");
+
+promise_test(async t => {
+ const { parent, child } = createTree();
+ const order = [];
+ const observer = new MutationObserver(() => order.push("observer"));
+ observer.observe(parent, { attributes: true, subtree: true });
+
+ // This queues no record, as observer does not observe childList mutations.
+ child.remove();
+ Promise.resolve().then(() => order.push("promise"));
+ child.setAttribute("data-test", "");
+ await nextTask(t);
+
+ assert_array_equals(order, ["observer", "promise"]);
+}, "Removing a node from an observed subtree queues the mutation observer microtask");
+
+test(() => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ observer.disconnect();
+ child.append(createElement("added"));
+
+ assert_array_equals(summarize(observer.takeRecords()), []);
+}, "disconnect() stops observing a removed subtree");
+
+test(() => {
+ const { parent, child, grandchild } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ grandchild.remove();
+ observer.disconnect();
+ child.append(createElement("added-to-child"));
+ grandchild.append(createElement("added-to-grandchild"));
+
+ assert_array_equals(summarize(observer.takeRecords()), []);
+}, "disconnect() stops observing a subtree removed from a removed subtree");
+
+test(() => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(() => {});
+ const otherObserver = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+ otherObserver.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ observer.disconnect();
+ child.append(createElement("added"));
+
+ assert_array_equals(summarize(observer.takeRecords()), []);
+ assert_array_equals(summarize(otherObserver.takeRecords()), [
+ "childList parent -child",
+ "childList child +added"
+ ]);
+}, "disconnect() does not affect another observer observing a removed subtree");
+
+test(() => {
+ const { parent, child, grandchild } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+ observer.observe(child, { attributes: true, subtree: true });
+
+ // grandchild remains observed through both parent and child.
+ grandchild.remove();
+ // This stops observing grandchild through child, but not through parent.
+ observer.observe(child, { attributes: true, subtree: true });
+ grandchild.append(createElement("added"));
+ grandchild.setAttribute("data-test", "");
+
+ assert_array_equals(summarize(observer.takeRecords()), [
+ "childList child -grandchild",
+ "childList grandchild +added"
+ ]);
+}, "observe() stops observing a removed subtree through the target, but not through other targets");
+
+test(() => {
+ const { parent, child, grandchild } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ // grandchild is removed from a subtree that is itself only observed because it was removed.
+ grandchild.remove();
+ observer.observe(parent, { childList: true, subtree: true });
+ child.append(createElement("added-to-child"));
+ grandchild.append(createElement("added-to-grandchild"));
+
+ assert_array_equals(summarize(observer.takeRecords()), [
+ "childList parent -child",
+ "childList child -grandchild"
+ ]);
+}, "observe() stops observing subtrees removed from a removed subtree");
+
+promise_test(async t => {
+ const { parent, child } = createTree();
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, { childList: true, subtree: true });
+
+ child.remove();
+ observer.observe(child, { attributes: true });
+ await nextTask(t);
+
+ child.append(createElement("added"));
+ child.setAttribute("data-test", "");
+ assert_array_equals(summarize(observer.takeRecords()), ["attributes child data-test"]);
+}, "observe() on a node in a removed subtree keeps observing it after mutation observers are notified");
diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.html b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.html
new file mode 100644
index 00000000000..ad836e6d2b6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>moveBefore() and MutationObserver: a moved subtree remains observed until notification</title>
+<script src="../../../resources/testharness.js"></script>
+<script src="../../../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../../../dom/nodes/moveBefore/mutation-observer-moved-subtree.window.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.js b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.js
new file mode 100644
index 00000000000..e00fd5bc7a4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/dom/nodes/moveBefore/mutation-observer-moved-subtree.window.js
@@ -0,0 +1,26 @@
+// META: title=moveBefore() and MutationObserver: a moved subtree remains observed until notification
+"use strict";
+
+promise_test(async t => {
+ const root = document.createElement("div");
+ const oldParent = root.appendChild(document.createElement("div"));
+ const newParent = root.appendChild(document.createElement("div"));
+ const target = oldParent.appendChild(document.createElement("div"));
+ const observer = new MutationObserver(() => {});
+ observer.observe(oldParent, { childList: true, subtree: true });
+
+ newParent.moveBefore(target, null);
+ const before = target.appendChild(document.createElement("span"));
+ const records = observer.takeRecords();
+ assert_equals(records.length, 2, "number of records");
+ assert_equals(records[0].target, oldParent, "removal record target");
+ assert_array_equals([...records[0].removedNodes], [target], "removal record removedNodes");
+ assert_equals(records[1].target, target, "second record target");
+ assert_array_equals([...records[1].addedNodes], [before], "second record addedNodes");
+
+ // Mutation observers are notified in a microtask, so they have been notified once a new task runs.
+ await new Promise(resolve => t.step_timeout(resolve, 0));
+
+ target.append(document.createElement("span"));
+ assert_array_equals(observer.takeRecords(), [], "records after mutation observers are notified");
+}, "A subtree moved out of an observed subtree by moveBefore() is observed until mutation observers are notified");