Recursive AI

MutationObserver

All onehtml docs

RecursiveAI.OneHtml.Mutation.MutationObserver is the DOM Standard's MutationObserver over a MutableDocument (the mutable working layer, mutable-document.md). It is a different thing from MutableDocument.Observe(Action<DocumentCommit>), which reports a whole commit's net change set. A mutation observer reports each individual edit, in order, as the DOM Standard defines it, so a script runtime or UI toolkit can bind to it directly.

Spec references: DOM Standard 4.2.3 (mutation algorithms: insert, remove, replace, replace all), 4.3 (interface MutationObserver), 4.3.1 (queue a mutation record, notify mutation observers), 4.3.2 (observe, disconnect, takeRecords), 4.3.3 (MutationRecord), 4.4 (normalize), 4.10 (replace data), 4.9 (attribute changes).

The mutation hooks, exception kinds and tree-version counter that sit at the same call sites are in mutation-hooks.md.

API

C#
var observer = new MutationObserver((records, self) => { ... });
observer.Observe(node, new MutationObserverInit { ChildList = true, Subtree = true });
observer.TakeRecords();   // the queued records, emptied
observer.Disconnect();    // stop watching everything, drop queued records
document.NotifyMutationObservers();   // the host's microtask checkpoint
  • MutationObserverInit has ChildList, Attributes, CharacterData, Subtree, AttributeOldValue, CharacterDataOldValue (all bool?) and AttributeFilter. null means "not given", which the defaults need: AttributeOldValue or AttributeFilter given turns Attributes on, and CharacterDataOldValue given turns CharacterData on (4.3.2 step 1 and 2).
  • The WebIDL TypeErrors of observe are DomException with DomExceptionKind.TypeError: nothing of childList/attributes/characterData is true after the defaults; AttributeOldValue true or AttributeFilter given with Attributes false; CharacterDataOldValue true with CharacterData false. A stale node is StaleNode; a null node is an ArgumentException.
  • MutationRecord has Type (and TypeName, the DOM string), Target, AddedNodes, RemovedNodes, PreviousSibling, NextSibling (the null node when absent), AttributeName, AttributeNamespace (a URI, null for no namespace) and OldValue. Records are immutable; node lists are shared read-only arrays. Nodes are MutableNode handles, so a removed node's handle stays usable until the node is released.
  • MutableNode gained the character-data methods the DOM defines with these records: AppendData, InsertData, DeleteData, ReplaceData (UTF-16 offsets; an offset past the end is DomExceptionKind.IndexSizeError, a count past the end is clamped) and Normalize.

Delivery is host-driven

The library runs no event loop. The host plays the part of the "microtask checkpoint":

  1. MutableDocument.MutationObserverMicrotaskRequested (optional) is called when the DOM Standard would queue the mutation observer microtask: the first queued record, or first transient registration (see below), after the last notification. The host schedules NotifyMutationObservers from it. It runs in the middle of an edit and must only schedule.
  2. MutableDocument.NotifyMutationObservers() is "notify mutation observers" (4.3.1). It clears the "queued" flag; takes the observers that have pending records or transient registrations, in the order the observers were created (not the order they got records); and for each: empties its queue, removes its transient registrations, and calls the callback once with the records when there are any.
  3. Edits a callback makes queue records for a later notification and raise the hook again, so a host loops while (document.HasPendingMutationObservers) document.NotifyMutationObservers();. The library never loops on its own, so a callback that always mutates cannot hang a call.
  4. An exception from a callback does not stop the others. With MutationObserverExceptionReporter set it is passed there ("report the exception"); otherwise it is thrown from NotifyMutationObservers after every observer was notified (several are an AggregateException).

Slot-change seam. 4.3.1 steps 3, 4 and 6 (take the signal slots, empty them, fire slotchange at each after the observers ran) are not implemented yet: the shadow model and events do not exist. The place is marked in NotifyMutationObservers. The set of observers notified in one round is fixed when the round starts (4.3.1 step 2, the pending observers), which matters for that step: a record queued by one callback for an observer that was not pending is delivered in the next round, after the slotchange events.

Where records are queued

Every edit of the mutable layer follows the DOM algorithm, including the order of records:

EditRecords
AppendChild, InsertBefore, PrependChild, InsertAdjacentHtmlThe inserted node first leaves its old parent (a removal record there, with that parent's siblings), then one addition record on the new parent. PreviousSibling is read before the node leaves its old place (4.2.3 insert step 5), so a move within one parent can name the node itself. A fragment gives a removal record on the fragment, then one addition record listing all its children.
ReplaceChildThe new node is adopted (removed from its old parent) first, then the child is removed silently, then one record with both the removed child and the added nodes. Replacing a child with itself gives a removal record and an addition record. (The WPT page expects the adopt-first order; see Decisions.)
RemoveChild, RemoveOne removal record.
SetTextContent (element), SetInnerHtml, ReplaceChildren"Replace all": one record with every old child removed and every new node added, none when both are empty. A single node that is already a child is simply in both lists. Several nodes are first gathered the way replaceChildren does it, which moves each out of its place with a record of its own. SetInnerHtml replaces with the parsed fragment as one node.
SetData, AppendData, InsertData, DeleteData, ReplaceData, SetTextContent (character data)One characterData record per call with the data before the call, even when the data does not change.
SetAttribute, RemoveAttribute, ToggleAttribute, SetStyleProperty, RemoveStyleProperty, class editsOne attributes record per attribute change, queued before the value changes, with the old value (null for a new attribute), even for the same value. Removing an absent attribute queues nothing.
NormalizeA characterData record for each text node that absorbs following ones, a removal record for each node removed.

Records are queued only for observers that match (4.3.1 step 3): the target or, with Subtree, an ancestor registered; the type enabled; AttributeFilter matching a no-namespace attribute by exact local name. An observer registered through several nodes still gets one record; it carries the old value if any of its matching registrations asked for it.

Transient registered observers (4.2.3 remove). When a node leaves a parent, every registration with Subtree on the parent or its ancestors adds a transient registration on the removed node, so the removed subtree stays observed until the next notification (the node's later edits still produce records). A transient made from a transient keeps pointing at the registration it came from. Observe on a node already observed replaces the options and removes the transients that came from the old registration. Disconnect removes all of the observer's transients. NotifyMutationObservers removes them at the start of each observer's turn, whether or not it had records.

Cost, limits and data

  • A document where nothing is registered pays one field test per edit and allocates nothing extra (the zero-allocation test Edits_with_no_observer_allocate_what_they_always_did). Registrations live in a table that exists only after the first Observe; an observer that is disconnected leaves nothing behind. Record lists and handle arrays are built only when an observer matches.
  • Each edit with an observer present walks the target's ancestors once, so its cost is the depth (bounded by MaxDepth).
  • MutableDocumentOptions.MaxQueuedMutationRecords (default 1,048,576) bounds records waiting across the document's observers. It is checked before each edit while any observer is registered: past it, the edit throws DomException (LimitExceeded) and changes nothing. One edit can queue several records per matching observer, so the count may pass the limit by that much.
  • Release removes the registrations on the released nodes, so a reused slot starts with none. Observers are not thread-safe.
  • Template content is its own tree: a registration on a template does not see edits of its content (4.2.3: the content is a separate document fragment, not a child).

Decisions where the spec leaves room

  • Adopt-first in ReplaceChild. The WPT page MutationObserver-childList.html ("internal replacement", "self internal replacement") expects the replacing node to leave its old place, with its own removal record, before the replaced child is removed. The code follows the page.
  • replaceChildren with one node does not adopt first (the same page's comment): the node's removal from its parent is part of the removed list of the single record.
  • Class list no-ops. AddClass of a present token and RemoveClass of an absent token leave the attribute text unchanged but queue the record the DOM's update steps would queue, when the element has a class attribute or the token set is not empty. SetStyleProperty with an unchanged declaration queues nothing (the declaration helpers do not write an unchanged value).
  • Attribute namespaces. The attribute model has four namespaces (none, XLink, XML, XMLNS), so AttributeNamespace is one of those URIs or null.
  • Callback exceptions are reported through MutationObserverExceptionReporter or rethrown after the round, as above.
  • Notification set. Observers with a pending record or transient registration, in creation order. The creation order is a process-wide counter, so it is the same for every document.

Tests and what is not translated

tests/OneHtml.Tests/Mutation/MutationObserverWptTests.cs translates the pages of WPT dom/nodes/ at commit ffc4686d117de150daf1287809302e3edea82dc6 (vendored unmodified in testdata/wpt/mutation-observer, with SHA256SUMS): MutationObserver-attributes, -callback-arguments, -callback-order, -callback-tricky, -characterData, -childList, -cross-realm-callback-report-exception, -disconnect, -inner-outer, -nested-crash, -overlapping-registrations, -sanity, -takeRecords, -textContent, -transient-registered-observers, and the observer part of shadow-dom/slotchange-event.html (the observer rounds; the slot assertions wait for the shadow model). MutationObserverTests.cs adds delivery, limit, zero-cost and random-edit tests: random edits on an observed and an unobserved copy must give the same tree and errors, and replaying the records on a model of the tree must give the final child lists and old attribute values.

Left out, with the reason:

Page, caseWhy
-attributes: n03 (n03.unknown = ...)JavaScript property expando; no attribute involved.
-attributes: n21, n31, n22/n23 with several tokensclassList.add/remove take several tokens as one update; AddClass takes one token, so it queues one record per call. The one-token errors are translated.
-attributes: n80, n90, n91, n92 (setAttributeNS/removeAttributeNS with http://example.org/)The attribute model has only the four built-in namespaces and no namespaced removal. The XML-namespace creation (n81) is translated.
-attributes: n50, n51Attr.value setter; translated as SetAttribute, the same "change an attribute" algorithm.
-childList: n00, n12 first half (nodeValue = "")nodeValue on an element is a JavaScript-visible no-op with no member here.
-childList, -characterData: the Range.* cases (deleteContents, extractContents, insertNode, surroundContents)There is no DOM Range in the library.
-characterData: appendData(null), insertData(2, null), and the processing-instruction case n50JavaScript null coercion; there is no processing-instruction factory in the mutable layer.
-document, -xml-parserThe parser inserts nodes into a live document while it runs; the tree builder that pauses for scripts does not exist yet.
-inner-outer: the outerHTML caseNo outerHTML setter. Its records are those of ReplaceChild with a parsed fragment.
-textContent: the CDATA section caseXML documents.
Node-mutation-adoptNode, namespaced-attribute-mutationsNot MutationObserver pages (adopting between documents; namespaced attribute side effects).