MutableDocument.LiveRanges is the registry that lets a script runtime keep DOM Range and NodeIterator objects correct while the tree changes. It holds the mutation-time half of DOM Standard 5.5 (live ranges) and 6.1 (node iterators): the adjustment of boundary points that the DOM's own mutation algorithms perform. Everything else about ranges and iterators belongs to the caller: the Range and StaticRange objects, setStart, collapse, compareBoundaryPoints, cloneContents, extractContents, surroundContents, toString, TreeWalker, and NodeIterator traversal and filtering. The caller builds those on ordinary MutableNode calls and on the handles below, and reads the adjusted points back.
Spec references: DOM Standard 4.2.3 (insert, remove, replace, replace all), 4.4 (normalize()), 4.10 (replace data), 4.11 (split a Text node), 5.2 (boundary points), 5.5 (live ranges), 6.1 (NodeIterator pre-remove steps).
API
LiveRangeSet set = document.LiveRanges; LiveRange range = set.Register(new BoundaryPoint(startNode, 3), new BoundaryPoint(endNode, 0)); range.Start; range.End; // BoundaryPoint (Node, Offset) range.StartNode; range.StartOffset; range.EndNode; range.EndOffset; range.Set(start, end); range.SetStart(p); range.SetEnd(p); // raw stores of validated points range.Unregister(); LiveNodeIterator it = set.RegisterIterator(root, reference, pointerBeforeReference); it.Reference; it.PointerBeforeReference; it.RootNode; it.Set(reference, pointerBeforeReference); it.SetCandidate(node, pointerBeforeReference); it.ClearCandidate(); // a traversal in progress it.Unregister(); set.RangeCount; set.IteratorCount;
- A boundary point is a node and an offset. For a text node, comment or processing instruction the offset counts UTF-16 code units of its data; for every other node it counts children; a document type has length 0 (DOM 4.4 "length"). Registering or setting a point whose offset is outside
0..lengthisIndexSizeError; a node of another document isWrongDocument; a released node isStaleNode. A failedSetchanges nothing. - The registry only adjusts. It never reorders a range's points and never checks that start is before end or that both share a root. Those are Range algorithms (DOM 5.6) and stay with the caller;
Set,SetStartandSetEndstore what they are given. - Ranges and iterators work in any tree of the document: the main tree, detached trees, document fragments, template contents and shadow trees. A shadow root is not a descendant of its host for these algorithms (DOM 4.2.1 "descendant" follows child links only), so removing a host does not move points inside its shadow root, and edits inside a shadow tree move that tree's points as in any other tree.
- Registered handles are held strongly until
Unregister. A runtime whose Range objects are garbage collected must unregister them (for example from a finalizer or a weak-reference sweep of its own). MutableDocumentOptions.MaxLiveRanges(default 1,048,576) bounds ranges and iterators together; registering past it isLimitExceeded, checked before anything is allocated.- A boundary node (or iterator root or reference) that is released with
MutableDocument.Releasewould otherwise point at a recycled slot. A range with such a point is reset to the document node at offset 0 for that point; an iterator whose root or reference is released is unregistered (IsRegisteredbecomes false); a released candidate reference is cleared. - Not covered: nodes that move between two
MutableDocumentinstances. A registry belongs to one document, so cross-document adopt must call the same remove adjustment when it removes a node from its old parent (the node's range points move to its old parent as for any removal). The runtime holds the registry of the node's old document.
Where points are adjusted
All adjustments run inside the mutation algorithm, at the point the DOM Standard puts them, for every edit path of MutableNode (including innerHTML, textContent, replaceChildren, insertAdjacentHTML, shadow root attachment that empties a root, fragments, and the paths that run with a mutation observer or mutation hooks installed).
| Algorithm | Adjustment |
|---|---|
| remove (DOM 4.2.3; the live range pre-remove steps, 5.5) | Before the node leaves its parent: every point whose node is the removed node or a descendant of it is set to (old parent, old index); then every point in the old parent with offset greater than the index loses one. |
| NodeIterator pre-remove (DOM 6.1), same moment | For every registered iterator, and for its candidate reference when set: if the removed node is an inclusive ancestor of the pointer's node and is not an inclusive ancestor of the iterator's root, then when the pointer is before the reference and a following node inside the root exists outside the removed subtree the pointer moves to it (still before); otherwise it moves to the removed node's parent when it has no previous sibling, or to the last inclusive descendant (tree order) of its previous sibling, with pointer-before false. |
| insert (DOM 4.2.3, step 5) | When there is a reference child: every point in the parent with offset greater than the child's index grows by the number of nodes inserted (a fragment's child count). With no reference child (append) nothing moves. The node is first removed from its old parent, which is a remove as above. |
| replace | The new node is adopted (removed from its old place) first, then the old child is removed, then the new node is inserted before the old child's next sibling. Replacing a child with itself therefore removes and re-inserts it, and points move with it. |
replace all (textContent, innerHTML, replaceChildren) | Every child is removed in order (points inside them end at (parent, 0)), then the new nodes are appended. |
replace data (DOM 4.10: setData, appendData, insertData, deleteData, replaceData, textContent and nodeValue of character data) | For points in the node with offset o, given offset f, count c (clamped to the length) and new data length n: f < o <= f + c becomes f; o > f + c becomes o + n - c. Setting the data is replace data over the whole data (offset 0, count = old length), so every point past 0 collapses to 0, even when the new data equals the old. |
| splitText (DOM 4.11) | The new node is inserted after the old one (an insert, above). Then points on the old node with offset greater than the split offset move to the new node with the offset reduced by the split offset; points in the parent whose offset equals the old node's index + 1 grow by one; then replace data removes the tail from the old node. |
| normalize (DOM 4.4) | For each text node that absorbs following text nodes: the data is appended, then for each absorbed node, points on it move to the surviving node (offset plus the surviving node's length so far), and points in the parent at the absorbed node's index move to (surviving node, that length). The absorbed nodes are then removed (a remove each). Empty text nodes are removed. |
splitText is new public API (MutableNode.SplitText(int offset)); the mutable layer had no splitText. It returns the new text node, which is detached (and the old node keeps its head) when the old node has no parent. An offset past the end is IndexSizeError; a node that is not a text node is HierarchyRequest.
Order of adopt and insert: a deliberate reading of the standard
The DOM Standard's "insert" increases the parent's points before it adopts (removes) the node being moved. When the node already sits in the same parent before the reference child, applying the standard's steps in that order gives a different result from removing first. Web-platform-tests' Range-mutations.js models the opposite order (the node is removed, then inserted), and Chrome 149 gives the same result: moving the last of a b c before a with the range at (parent, 2) gives (parent, 3). OneHtml follows the web-platform-tests model and Chrome: the node leaves its old place first, then points after the reference child grow. Moves of a node to another parent or to a detached position are the same in both orders.
Cost
- With nothing registered, a mutation tests one boolean and does nothing else. Nothing allocates.
- With
Rranges and iterators registered, adjustments allocate nothing (a test measures identical per-edit bytes with 40 ranges and an iterator registered). Time per mutation:- remove: O(R × depth) for the descendant tests, plus O(siblings before the node) for its index;
- insert before a child: O(R) plus O(siblings before the child) for its index; append: O(1);
- replace data and set data: O(R);
- splitText and each normalize merge step: O(R) plus the index;
Releasewith ranges registered: O(nodes released + R), with a hash set of the released slots.
- Replacing all
nchildren costs n removals, each O(R × depth) (the index of a first child is 0, so there is no per-sibling scan). - Nothing recurses on input depth: ancestor tests loop on parent links, and the last-descendant search loops on last-child links.
What is tested
WptRangeMutationTeststranslates, with the pages' own oracle functions, web-platform-tests (commit ffc4686d117de150daf1287809302e3edea82dc6):dom/ranges/Range-mutations-insertBefore,-appendChild,-removeChild,-replaceChild,-insertData,-appendData,-deleteData,-replaceData,-dataChange,-splitTextand-normalize; the DOM-level parts ofRange-adopt-test; anddom/traversal/NodeIterator-removal, with its oracle, its two targeted pointer-before-reference cases and a test-side NodeIterator over the registry.LiveRangeModelTestsruns random edit sequences (append, insertBefore and moves, remove, replaceChild, the data operations, splitText, normalize, textContent, replaceChildren, in attached and detached trees) against registered ranges and iterators, and compares every point after every operation with an independent reference model written from the standard's text. Each sequence runs plain, with a mutation observer installed, with mutation hooks installed, and with both, since those switch the edit paths.LiveRangeTestscovers validation, the limit, shadow trees, fragments, replace all, data changes with equal data, UTF-16 offsets, release, the iterator candidate reference, and the allocation guarantee.
Left out of the translations, with the reason:
- The
foreignDocandxmlDocrows (a second HTML document and an XML document as parent,foreignDoc.doctype,foreignDoc.documentElement) need a second Document node; aMutableDocumentis one document. Theforeign*andxml*text, comment and element nodes of those pages are stood in by nodes of the same kinds in separate trees of the one document, so the algorithms run on the same shapes, but the cross-document adopt part of those rows is not exercised here. The cross-document adopt steps belong with adopt and import. - The second run of every Range-mutations row with the range "selected" in a
Selection: Selection is the runtime's. - CDATA sections (
paras[5]of the page's setup) are plain text nodes here; the layer has no CDATA node kind. They do not take part in the listed rows except as ordinary text nodes. Range-adopt-testcases that move the range's container to another document, andRange-test-iframe, which needs a second browsing context: cross-document adoption and the iframe's window.NodeIterator-removal-during-filtering: it drives a JavaScript filter callback throughnextNode; traversal and filtering are the runtime's. The iterator's candidate reference, which that page exercises, is adjusted by the registry (LiveRangeTests).- Everything else under
dom/ranges/anddom/traversal/: non-mutating Range algorithms, StaticRange, Selection interplay and TreeWalker.