Recursive AI

The node model: namespaces, attribute nodes, node types and documents

All onehtml docs

This is the behaviour of RecursiveAI.OneHtml.Mutation beyond the tree-editing calls in mutable-document.md: what a script runtime needs to give a page the DOM Standard's node model. Everything here follows the DOM Standard (sections named in comments); where it does not, section 9 says so. A port reproduces the behaviour from this text.

1. Documents

A MutableDocument has a kind and a content type:

Made byKindContent typeMode
Parse, Create(Document)HTMLtext/htmlfrom the parse
CreateHtmlDocument(title)HTMLtext/htmlno quirks; doctype html, html, head (with title only when a title is given), body
ImplementationCreateDocument(ns, qualifiedName, doctype)XMLapplication/xhtml+xml for the HTML namespace, image/svg+xml for SVG, application/xml otherwiseno quirks
CreateEmpty() (new Document())XMLapplication/xmlno quirks
ParseFromString(html, "text/html", declarativeShadowRoots)HTMLtext/htmlfrom the parse; scripting off
CloneDocument(deep) / node.CloneNode() on a documentsame as the sourcesamesame
  • IsXmlDocument, ContentType and CompatMode (BackCompat in quirks mode) read them. Every document has version 0 committed.
  • An XML document is case sensitive. CreateElementDom (createElement) keeps the name; the element is in the HTML namespace when the content type is application/xhtml+xml and in no namespace otherwise. In an HTML document it lower-cases the name (ASCII) and makes an HTML element. Attribute names are lower-cased only for an HTML-namespace element of an HTML document. TagName is upper case only for an HTML-namespace element of an HTML document.
  • ImplementationCreateDocument follows DOM 4.5: the element is made first (its errors propagate), then the doctype is appended (a doctype of another document is adopted, so it leaves its old document), then the element. A null or empty qualified name makes no element.
  • ParseFromString accepts text/html only; the XML types throw NotSupportedError (the library has no XML parser). Use Parse(html, ParseOptions, MutableDocumentOptions) for finer control of scripting and declarative shadow roots.
  • XML documents serialize with the HTML fragment algorithm (HTML 13.3), which is what SerializeNode and snapshots use for every document. The XML serializer of DOM Parsing is not implemented.

2. Namespaces and prefixes

  • Representation. The node columns keep the parser's three namespaces in one byte (ElementNamespace.Html, MathMl, Svg). An element in any other namespace, or in none, has ElementNamespace.Other there and an index into a per-document URI table (index 0 is "no namespace"). The prefix is a name atom in a second column. Both columns exist only once a document makes such an element or prefix, so a document that never does pays nothing. A URI in the HTML, SVG or MathML namespaces always maps to the enum, whatever the prefix; the prefix stays in its column.
  • Attributes. An attribute row has (in the attribute flags column, as in the arena) AttributeNamespace None, XLink, Xml, Xmlns (the parser's, with their standard prefixes xlink, xml, xmlns and, for the xmlns attribute itself, no prefix) or Other. Any other combination of namespace URI and prefix, including a standard URI with a different prefix, is Other with the URI and prefix in an extension entry. MutableAttr.NamespaceUri and .Prefix give both for every attribute.
  • Snapshots. Node.Namespace can be Other; Node.NamespaceURI, Prefix and QualifiedName read it. Attr.Namespace can be Other; Attr.NamespaceUri, Prefix and QualifiedName read it. Selectors treat a namespaced attribute as not being a no-namespace attribute. The URI table of a snapshot is a copy. MutableDocument.Create(snapshot) reads these columns back.
  • HTML 13.3 serialization. An element in the HTML, SVG or MathML namespace is written with its local name (whatever its prefix); any other element with its qualified name. An attribute in no namespace is written with its local name, an XML-namespace attribute as xml: + local name, an XMLNS one as xmlns or xmlns: + local name, an XLink one as xlink: + local name and any other as its qualified name.
  • Validate and extract (DOM 1.4, the current loose rules). CreateElementNS, CreateAttributeNS, SetAttributeNS and ImplementationCreateDocument run it with a context. A namespace of null or "" is none. A qualified name with a colon is split at the first colon; the prefix must be a valid namespace prefix (not empty, no ASCII whitespace, U+0000, / or >), the local name a valid element local name (context element) or valid attribute local name (not empty, no ASCII whitespace, U+0000, /, = or >). Failures are InvalidCharacterError. Then: a prefix with no namespace, prefix xml with a namespace other than the XML namespace, xmlns as qualified name or prefix with a namespace other than XMLNS, and the XMLNS namespace without xmlns as qualified name or prefix are NamespaceError. The vendored Document-createElementNS.js table (182 rows, every one of them in an HTML, an XML and an XHTML document) and the DOMImplementation-createDocument rows run as tests.
  • Attribute lookup. GetAttribute, HasAttribute, SetAttribute, RemoveAttribute, ToggleAttribute and GetAttributeNode find "the first attribute whose qualified name is the argument" (the name is first lower-cased for an HTML element of an HTML document). An unprefixed attribute's qualified name is its local name, so getAttribute("pre:fix") finds an attribute made by setAttribute("pre:fix") (local name pre:fix, no namespace) and one made by setAttributeNS(uri, "pre:fix") (prefix pre, local name fix), whichever came first. The *NS calls match the namespace URI and local name exactly (case sensitive). Setting an existing attribute keeps its position and prefix.
  • Lookups. LookupNamespaceUri(prefix), LookupPrefix(uri) and IsDefaultNamespace(uri) implement DOM 4.4 "locate a namespace" and "locate a namespace prefix", including the fixed xml and xmlns prefixes, xmlns declarations on ancestors, the document element for a document, nothing for doctypes and fragments, and the owner element for an attribute node.

3. Attribute nodes

MutableAttrNode (DOM Attr) is a handle (document, entry, generation). A row of an element's attribute list gets an entry only when a handle is asked for it (GetAttributeNode, GetAttributeNodeNS, AttributeNodeAt), so elements whose attributes are never taken as nodes pay nothing. The entry is stored in the row, so the node follows its attribute through every change of value, compaction and reordering of the rows; asking again gives the same handle.

  • Value reads and writes through the owner element (same records, hooks, limits and counters as SetAttribute); on a detached attribute it is held by the entry.
  • OwnerElement, LocalName, Name (qualified), NamespaceUri, Prefix.
  • Removal detaches. RemoveAttribute, RemoveAttributeNode, replacing it with another attribute node, or releasing its element detach a node somebody holds a handle to: it keeps its name, namespace, prefix and value, and OwnerElement is the null node. An entry nobody held is freed at once.
  • CreateAttribute(localName) (lower-cased in an HTML document; valid attribute local name) and CreateAttributeNS make detached nodes with an empty value. ReleaseAttribute frees a detached one (a node left alone costs an entry until then, and counts against MaxTotalAttributes; its value counts against MaxValueStoreChars).
  • SetAttributeNode (and SetAttributeNodeNS, the same operation) follows DOM 4.9 "set an attribute": a node in another element is InUseAttributeError; a node already in this element changes nothing; an attribute with the same namespace and local name is replaced in place (it keeps its position; the old node detaches with its value and is returned), otherwise the node is appended. A detached node of another document is adopted first (its copy is attached; hooks get AttributeAdopted); one that is in an element there is InUseAttributeError.
  • RemoveAttributeNode of a node that is not in the element is NotFoundError.
  • CloneNode() and MutableDocument.ImportNode(attr) make a detached copy with the same name, namespace, prefix and value.
  • CompareDocumentPosition, IsEqualNode (namespace, local name and value; not the prefix), LookupNamespaceUri, LookupPrefix and IsDefaultNamespace exist on attribute nodes as DOM 4.4 defines them.

Hooks and records: MutationHooks.AttributeChangeSteps keeps its shape (the enum for the namespace, which is Other for any namespace beyond the three); AttributeChangeStepsNs(element, localName, namespaceUri, old, value) follows it with the URI. A MutationRecord.AttributeNamespace is the URI. AttributeDelta.NamespaceUri is set when the namespace is Other; the net effect tells two attributes with the same local name in different namespaces apart.

4. Node types

TypeMade byNotes
Doctype (10)CreateDocumentType(name, publicId, systemId)name must be a valid doctype name (no ASCII whitespace, U+0000 or >; the empty string is valid). The identifiers are stored per node and written by snapshots (Node.PublicId, SystemId; a snapshot has one document doctype, the first child). MutableDocument.Doctype is the document's. Insertion rules: only into a document, one, before the element.
Processing instruction (7)CreateProcessingInstruction(target, data)target must match the XML Name production, data must not contain ?>; both InvalidCharacterError. LocalName is the target.
CDATA section (4)CreateCDataSection(data)XML documents only (NotSupportedError otherwise); data must not contain ]]>. It is a NodeKind.Text node with IsCDataSection true, so it can go wherever text can, snapshots and serialization treat it as text, NodeType is 4, NodeName #cdata-section, IsEqualNode tells it from text, CloneNode and adoption keep it, and Normalize leaves it alone and does not merge text across it.
Text (3), comment (8)CreateTextNode, CreateCommentany characters (also U+0000, lone surrogates), up to MaxValueLength.

NodeType, NodeName, NodeValue (get and set), TagName, QualifiedName, NamespaceUri, Prefix, DomTextContent (null for a document and a doctype) give the DOM's reads per node type; a shadow root is 11, #document-fragment.

IsEqualNode (DOM 4.4): same node type; doctypes by name and identifiers; elements by namespace, prefix, local name and attribute set (by namespace, local name and value, in any order; linear in the attribute count above eight); processing instructions by target and data; text, CDATA and comments by data; then equal children in order. Iterative. Shadow roots and template contents are not compared. The nodes may belong to different documents.

CompareDocumentPosition (DOM 4.4): nodes of different documents or trees are Disconnected | ImplementationSpecific plus Preceding or Following, consistent and anticommutative: trees are ordered by document (creation order), then by the slot of the tree's root. Attributes follow the DOM's attribute rules (two attributes of one element are ordered by their place in its list, ImplementationSpecific; an attribute is contained by its element). Within one tree the order is tree order. Contains(other) is true for the node itself and its descendants.

5. Token lists

MutableNode.ClassList and MutableNode.Part are MutableTokenList views (DOMTokenList, DOM 7.1) over the class and part attributes: Count, Item, Contains, Add(params), Remove(params), Toggle, Replace, Value (get/set), Supports (always TypeError: neither attribute defines supported tokens). An empty token is SyntaxError, one with ASCII whitespace InvalidCharacterError, all checked before anything changes. The update steps do not create the attribute when the set stays empty and it is absent. The view holds no state; the scoped cascade reads the part attribute as before. AddClass and the other class calls keep their behaviour.

6. Adopt, import and clone

Every document has its own arena, so a node cannot change documents in place. Adopting copies the subtree into the target as a detached subtree and frees the original. The copy gets new handles; the old ones are stale. A runtime that keeps an object per node replaces its key from MutationHooks.NodeAdopted(oldNode, newNode).

  • AdoptNode(node) (DOM 4.5): a document is NotSupportedError, a shadow root HierarchyRequestError. The node leaves its parent first (removing steps, records, and a custom element's disconnectedCallback, which runs at once with the old handle), then its subtree is copied with shadow roots (all of them, with their properties), template contents, attributes, namespaces, prefixes, doctype identifiers and CDATA flags, the original is released, and for each node in shadow-including tree order the target's hooks get NodeAdopted(old, new) then AdoptingSteps(new, oldDocument); custom elements keep their state and definition and get adoptedCallback. A node of the document itself is only removed from its parent and returned unchanged.
  • Inserting a node of another document (AppendChild, PrependChild, InsertBefore, ReplaceChild, ReplaceChildren) stages a copy in the target, runs ensure pre-insertion validity on it, and only then adopts (removes the original, releases it, runs the adopting steps) and inserts. A refused insertion leaves the node in its document and leaves no slot behind. The call returns the node's new handle; for a fragment (and a shadow root used as one) the children are adopted one by one and the original fragment, now empty, is returned. ReplaceChildren checks every node before adopting any.
  • ImportNode(node, deep = false, registry = null) (DOM 4.5 clone; deep is false by default as in importNode; custom element registries as in docs/custom-elements.md): for a node of another document copies it into the target; the original is untouched. Clonable shadow roots come along (a shadow root itself is NotSupportedError), elements are looked up in the target's custom element registry as parsed elements are, and the cloning steps run. ImportNode(attribute) copies an attribute node. For a node of the same document it is CloneNode.
  • CloneNode of a document makes a new MutableDocument (CloneDocument(deep)), with the same kind, content type and mode; deep copies the children (doctype included).
  • slot.assign() with a node of another document is accepted and stored as a token entry, as if the node had been adopted away after being listed: it turns into a plain entry when the node is adopted into the slot's document. Assigning again drops the old entries, tokens included.
  • Manual slot assignments are carried. A slot's manually assigned nodes (slot.assign(), DOM 4.2.2.2 "manual slot assignment") belong to the slot and the nodes, not to the arena they sit in, so adopting either one keeps the link. A node that some slot lists and that moves to another document leaves a token behind in the list; the token follows the node (NodeAdopted moves it) and turns back into a plain entry, at its old position in the list, when the node, or the slot, returns to the document that holds the list. While they are in different documents the node is not slotted (its parent is not the slot's host), as DOM "find slottables" requires. Nodes adopted into a document that never gets the slot back keep one small token in the source document's list, freed with the list.
  • What is not carried: observers registered on the old nodes (they are dropped with the nodes; the old document's observers see the removal), event listeners (the host re-registers from NodeAdopted) and adopted style sheets of a moved shadow root.
  • Custom elements. The target gets a registry when it takes in a custom element, so reactions have somewhere to be queued; with no reaction scope open there, the adoptedCallback waits on the backup queue for the host's ProcessBackupElementQueue.
  • Limits. The copy is made before anything changes and counts against the target's MaxNodes, MaxAttributesPerElement, MaxTotalAttributes, MaxValueStoreChars and MaxNames; a failure releases the partial copy and leaves the source alone. MaxDepth is checked on the insertion with exact heights (the copy's heights are recomputed bottom-up). Copying uses explicit stacks: a 20,000-deep tree moves without recursion.
  • Template contents owner document. A template's content nodes stay in the arena of the template's own document, so their handles name that document. TemplateContentsOwnerDocument is the inert HTML document of HTML 4.12.3 (made on first use, its own owner), and NodeDocumentOf(node) is the document the DOM would report as ownerDocument: the inert one for a node inside template content, the node's document otherwise. A node made by the inert document and inserted into a content fragment is adopted into the content's arena like any foreign node.

7. Limits and cost

  • Live structures. Adoption removes the node from its old parent through the ordinary removal path, so the old document's live ranges and node iterators get their pre-remove adjustment (DOM 5.5), its id table drops the subtree, and its live collections see the change; the copy enters the target through the ordinary insertion path, so its id table, ranges and collections see an insertion. A range boundary inside a detached subtree that is adopted goes to the start of the old document (the subtree is released). An attribute set or removed through an attribute node bumps the attribute version counters and the id table like SetAttribute.

  • A document that uses none of this pays nothing: the node columns for namespace URIs and prefixes, the attribute columns for namespace URIs, prefixes and attribute-node identity (_aUri, _aPfx, _aExt) and the URI table are allocated on first use, and the attribute rows stay four columns. The live view the queries use (MutableDocument.Live.cs) reads the same columns, so a namespaced element or attribute is seen by selectors, closest and the live collections as it is by snapshots.

  • Attribute entries are bounded by MaxTotalAttributes, the URI table and names by MaxNames, detached values by MaxValueStoreChars.

  • GetAttributeNode and the attribute node reads scan the owner's attributes (at most MaxAttributesPerElement). IsEqualNode and CompareDocumentPosition are linear in the nodes and depth.

  • The read path (parse, query, cascade) gained one flag test per attribute in the selector matcher and serializer.

8. Not translated from the WPT pages

Pinned at ffc4686d117de150daf1287809302e3edea82dc6; the pages are vendored under testdata/wpt/dom-nodes.

PageWhat runsWhat does not, and why
Document-createElementNSEvery row of the table, in an HTML, an XML and an XHTML documentThe iframes (dummy.xml): the documents are made with ImplementationCreateDocument.
DOMImplementation-createDocumentEvery row of the table with its element, doctype, content type and compatMode checks; doctype adoption; reuse of a doctype of another documentArgument coercion (TypeError for false, no arguments), characterSet, charset, inputEncoding, URL, documentURI, location and Object.getPrototypeOf: script and host properties.
DOMImplementation-createHTMLDocumentThe tree, with and without a title; metadata that has a node-model meaningURL, documentURI, characterSet, location, anchor href parsing, the no-browsing-context and saved-implementation pages: host properties and script realms.
DOMImplementation-createDocumentTypeEvery rowNone.
attributes.htmlEvery test that is about attributes: toggle, set, setNS, lookups, node functions, Attr ownershipThe getOwnPropertyNames, enumerable-property and NamedNodeMap index tests (script objects), el.style = ..., and the iframe.src load test.
Attr-prefix, Element-removeAttributeNS, Element-setAttributeNodeNS, Document-createAttributeAllAttr-prefix-xhtml and the other .xhtml/.xml variants need an XML parser.
Node-lookupNamespaceURIAllNone.
Node-isEqualNode, Node-compareDocumentPositionAll the page's checks; the comparison runs over the node set dom/common.js builds (documents, detached trees, a foreign HTML document, an XML document with a doctype, a processing instruction, CDATA sections) for every ordered pairThe XML iframe pages of isEqualNode (XML parser). The ranges in common.js are not part of this layer.
Document-adoptNode, Document-importNodeAll, plus attribute nodes and what a runtime needs (handles, hooks, reactions, observers, limits)None.
Node-cloneNode, -XMLDocument, -document-with-doctypeNode properties for each node type, attributes and attribute nodes, documents (deep and shallow), doctype identifiersinstanceof HTML*Element and prototype checks (the runtime's interfaces), Document.title, charset, URL (host), the external-stylesheet, base-URL, srcdoc and inactive-document pages (browsing contexts, networking).
Document-createProcessingInstruction, -createCDATASection, DocumentType-*, Node-normalize, -nodeName, -nodeValue, -textContent, -isSameNode, -containsAll DOM-level assertionsThe .xhtml variants (XML parser); Node-normalize-2 (live ranges, which this layer does not have yet); interface checks (instanceof).
css/css-shadow/part/part-name-idlAll four testsThe two invalidation-change-part-name-idl-* pages are style invalidation (covered by the scoped cascade tests).

9. Deviations and defaults

  • A node that moves documents has a new handle. The DOM keeps the object; a handle names an arena slot, so the runtime remaps its objects from NodeAdopted.
  • Template contents keep their arena (section 6).
  • No XML serializer and no XML parser. XML documents serialize with HTML 13.3.
  • Listeners, observers and manual slot assignments do not move with an adopted node.
  • ParseFromString supports text/html only.
  • Names. createElement and friends use the current DOM's loosened name rules, not the XML Name production, except for a processing instruction's target (the DOM still requires Name there).
  • Prefixes on the three parser namespaces. The prefix is kept in its own column; an attribute in the XLink, XML or XMLNS namespace with a prefix other than the standard one is AttributeNamespace.Other.