The custom element machinery of the HTML Standard (4.13) as C# DOM features of the mutable layer (RecursiveAI.OneHtml.Mutation, see mutable-document.md). The library holds the registry, the element states, the upgrade and reaction machinery, the form-associated bookkeeping and ElementInternals. The host (a script runtime, or C# code) supplies what the library cannot know: the constructors, the lifecycle callbacks, promises (whenDefined), events and form submission.
Spec references: HTML Standard 4.13 "Custom elements" (4.13.3 "Core concepts", 4.13.4 "The CustomElementRegistry interface", 4.13.5 "Upgrades", 4.13.6 "Custom element reactions", 4.13.7 "Element internals"), 3.2.8.1 "HTML element constructors", 13.2.6.1 "Creating and inserting nodes"; DOM Standard 4.5 "Interface Document" (create an element), 4.2.3 "Mutation algorithms" (insert, remove, adopt, clone), 4.9 attachShadow.
1. The pieces
| Type | What it is |
|---|---|
MutableDocument.CustomElements | The document's CustomElementRegistry, created on first read. |
CustomElementRegistry | Define, Get, GetName, Upgrade, element states, the reactions stack, ConstructHtmlElement, CreateElementForToken, AttachInternals, form hooks. |
CustomElementDefinition | Abstract. The host derives one per class: name, extends, observed attributes, the callbacks it has, disabledFeatures, formAssociated, the constructor identity, Construct, and one virtual method per lifecycle callback. |
CustomElementState | Undefined, Failed, Uncustomized, Precustomized, Custom (4.13.3). |
ElementInternals, CustomStateSet, ValidationProblems | 4.13.7. |
MutableDocument.CreateElement(name, ns, isValue) | DOM "create an element" with the synchronous custom elements flag set. |
The document's registry is MutableDocument.CustomElements, the global registry. Scoped registries (section 11) are made with MutableDocument.CreateScopedCustomElementRegistry(). Every lookup goes through one function that takes the element's registry (CeRegOf).
2. Define (4.13.4)
registry.Define(definition) runs the specification's checks in its order and throws DomException:
- the name is not a valid custom element name:
SyntaxError. The production isPotentialCustomElementNameof 4.13.3 minus the eight reserved names;a-is valid; - the definition is already defined, the name is taken, or the constructor identity (
CustomElementDefinition.ConstructorIdentity, the definition itself by default) is taken:NotSupportedError; extendsis a valid custom element name, or not the name of an HTML element that has an interface of its own (a fixed list of the HTML Standard's element names, including the obsolete ones that have interfaces):NotSupportedError;registry.DefinitionRunningis set:NotSupportedError. The host sets it while it reads the class's properties for the definition (the "element definition is running" flag);Definesets it while it reads the definition's own data.
The definition's data (ObservedAttributes, Callbacks, DisableInternals, DisableShadow, FormAssociated, ConstructorIdentity) is read once, at the end of step 4. Then an upgrade reaction is queued for every element of the document, in shadow-including tree order, whose namespace is HTML and local name is the definition's local name (for a customized built-in, whose is value is also the definition's name). registry.Defined is called last: the host resolves its whenDefined promise there. Get(name) and GetName(constructorIdentity) are plain lookups. Upgrade(root) queues an upgrade reaction for every element in the shadow-including inclusive subtree of root that has a definition (detached trees included).
3. Element states and :defined
An element's state is stored only when it differs from its default, so a document with no custom elements stores nothing:
- default:
Undefinedfor an HTML element with a valid custom element name,Uncustomizedfor every other element; - an element created with an
isvalue, or parsed with anisattribute, isUndefinedwhatever its name; theisvalue is stored when the element is created and is not the attribute (DOM "is value"). Elements that already existed when the registry was first read take it from theirisattribute; registry.GetState,GetDefinition,GetIsValue,IsDefined(:defined:UncustomizedorCustom; every non-HTML element is defined).
Snapshots carry the states: a snapshot taken from a mutable document whose registry holds any custom element data answers :defined and :state(name) from them. A parsed Document has no registry: :defined is false for an element with a valid custom element name or an is attribute, and :state() never matches. A change of state (an upgrade finishing, a state added to or removed from a CustomStateSet, an ARIA default changing) marks the document changed and is listed in the commit: DocumentChanges.CustomElementsChanged names the elements, ToChangeSet reports them as attribute changes, and a restyle treats each as an element whose attributes may have changed. A selector with :defined or :state() carries the dependency SelectorDependencies.CustomState, which makes its rules re-match for those elements, so Restyle and Rebase after such a commit equal a fresh computation (checked in CustomElementRestyleTests, including :has() and sibling-combinator rules). A change is listed once per commit, and ChangesSince unions the lists.
registry.HasCustomState(node, name) and registry.IsDefined(node) are the reads for a matcher that runs on the live tree.
4. Creating elements
MutableDocument.CreateElement(name, ns) and CreateElement(name, ns, isValue) are DOM "create an element" with the synchronous custom elements flag set (createElement):
| Lookup result | What happens |
|---|---|
| no definition | a plain element; Undefined when it has a valid custom name or an isValue |
a customized built-in definition (name and is match, local name matches) | the element is made Undefined with its is value, and an upgrade reaction is queued |
| an autonomous definition | definition.Construct(document) runs now. The result is checked: it must be an element of this document, an HTML element with the right local name, with no attributes, no children and no parent: NotSupportedError/TypeError otherwise. A constructor exception or a failed check makes the result a new element in state Failed, reports the exception (registry.ExceptionReporter, or rethrows when none is set) and goes on |
Fragment parsing (SetInnerHtml, InsertAdjacentHtml, ParseFragment), Import and CloneNode create elements with the flag unset: the element is Undefined, and an upgrade reaction is queued if a definition applies. Elements parsed for a template element's content or inside template content are never upgraded (the content belongs to an inert document with no registry).
The HTML element constructor
The host's class constructor reaches registry.ConstructHtmlElement(definition) (HTML 3.2.8.1) in place of the base HTMLElement constructor:
- construction stack empty (a direct
new C()): a new element in stateCustomfor the definition. For a customized built-in (a definition withextends) its is value is the definition name, so cloning it (the clone replays the is value) finds the definition again and the copy is the same customized element (custom-elements/builtin-coverage.html); - construction stack non-empty (an upgrade is running): the element being upgraded, and the stack entry becomes the already constructed marker;
- the marker is the last entry:
DomExceptionwith kindTypeError; - a definition that belongs to another registry:
TypeError.
Prototype setting is the host's. An upgrade then checks that Construct returned that same element (otherwise TypeError).
The parser
registry.CreateElementForToken(localName, ns, attributes, forFragment) is "create an element for a token" (13.2.6.1) for a parser that builds nodes in this document. With a definition and forFragment false ("will execute script"): it raises registry.ThrowOnDynamicMarkupInsertionCounter, calls registry.PerformMicrotaskCheckpoint (the host does the checkpoint only when its script stack is empty), pushes an element queue, creates the element with the synchronous flag, appends the token's attributes after construction (so the constructor sees none; observed attributes queue attributeChanged), then pops and invokes the queue and lowers the counter. The is value is the token's is attribute. It returns the detached element; the parser inserts it with the ordinary mutation methods, which queue the connected reaction. For the incremental parser the call is:
MutableNode CustomElementRegistry.CreateElementForToken(string localName, ElementNamespace ns, IReadOnlyList<MutableAttr> attributes, bool forFragment = false)
The parser must push an element queue around its insertion of each element when it is not a fragment parse, as 13.2.6.1 "insert an element at the adjusted insertion location" says (PushElementQueue, insert, PopElementQueueAndInvokeReactions), and it must not hold the registry's stack across ScriptReady.
5. Upgrades (4.13.5)
An upgrade reaction runs "upgrade an element": nothing happens unless the state is Undefined or Uncustomized. Otherwise the element gets the definition and state Failed; every attribute is queued as attributeChanged (observed names only), a connected element queues connected; the element goes on the definition's construction stack; a definition that disables shadow roots fails the upgrade if the element already has one (NotSupportedError); the state becomes Precustomized; Construct runs; its result must be the element. Any exception sets the state to Failed, clears the definition and the element's reaction queue, pops the stack and is reported. On success a form-associated element resets its form owner (queueing formAssociated for a non-null owner) and queues formDisabled(true) when disabled, and the state becomes Custom.
6. Reactions (4.13.6)
- Element queues.
PushElementQueue()andPopElementQueueAndInvokeReactions()(orusing (registry.EnterReactionsScope())) are the host's[CEReactions]bracket: push before the operation, pop and invoke after. Reactions run in queue order; an exception from a constructor or callback goes toExceptionReporter, or, when none is set, is rethrown after every reaction ran (several as anAggregateException). Reactions queued while reactions run go to the enclosing queue. - Automatic scopes. A public mutating method (
AppendChild,InsertBefore,ReplaceChild,RemoveChild,Remove,ReplaceChildren,SetTextContent,SetInnerHtml,InsertAdjacentHtml,SetAttribute,RemoveAttribute,ToggleAttribute,AddClass,RemoveClass,ToggleClass,SetStyleProperty,RemoveStyleProperty,Normalize,CloneNode,Import,CreateElement,Define,Upgrade) called with no queue pushed pushes its own and runs the reactions before it returns, so C# code needs no bracket. A host that pushes its own queue is not affected: a method called inside a pushed queue never opens another.registry.AutomaticReactionScopes = falsegives the specification's behaviour for calls made with no queue: the element goes on the backup queue. A document with no definitions never opens one. - Backup element queue. The first element put on it calls
registry.BackupQueueMicrotaskRequested; the host callsregistry.ProcessBackupElementQueue()from a microtask (the call also lowers the "processing" flag, so a later enqueue asks again).HasPendingBackupQueuesays whether elements wait. - Where reactions come from. The mutation hooks (
mutation-hooks.md), in the order of the DOM insert, remove and clone algorithms: insertion steps queueconnectedfor a connected custom element and an upgrade attempt for any other element; removing steps queuedisconnectedfor each custom element of a subtree whose parent was connected, in shadow-including tree order (the shadow root's tree comes before the host's children); attribute change steps queueattributeChangedfor a custom element's observed attributes (added, changed even to the same value, removed; the namespace is passed as a URI string toCustomElementDefinition.AttributeChangedNs, whose default maps it to theAttributeNamespaceenum and callsAttributeChanged, so a host that overrides only the older method keeps working and anysetAttributeNSnamespace survives); cloning steps replayisand look up a definition for the copy. The hooks are registered on the firstDefine; before that nothing is hooked. - Adopted. The adopting step queues
adopted(oldDocument, newDocument)for custom elements. The library cannot adopt between documents yet (MutationHooks.AdoptingStepsis reserved), soadoptedCallbackis never called today. - connectedMoveCallback.
moveBeforedoes not exist in the library, so there is noconnectedMoveCallback. When it is added, a move queuesconnectedMovewhere the definition has it anddisconnectedfollowed byconnectedwhere it does not. - Limit.
MutableDocumentOptions.MaxCustomElementNesting(default 256) bounds the element queue stack and the nesting of constructors (a constructor that creates its own element); exceeding it throwsDomExceptionwith kindLimitExceededbefore the work.
7. Form-associated custom elements
A definition with FormAssociated makes its elements form-associated once they are Custom. The library tracks, for each such element, the form owner (4.10.18.3: the form attribute names a form element with that id in the same tree, else the nearest form ancestor) and the disabled state (its disabled attribute, or a disabled fieldset ancestor unless the element is inside that fieldset's first legend). It re-reads both after structural edits that touch a form-related element (a form-associated element, form, fieldset, legend, datalist) and after changes to the disabled, form, readonly and id attributes, and queues formAssociated(form or null) when the owner changed and formDisabled(bool) when disabled changed. The first call after an upgrade queues formAssociated only for a non-null owner.
For the host's own form code: EnqueueFormAssociated, EnqueueFormReset, ResetForm(form) (queues formReset for every form-associated element owned by the form, in tree order), EnqueueFormStateRestore(element, state, mode) and RefreshFormAssociations(). All but the last throw NotSupportedError for an element that is not a form-associated custom element.
8. ElementInternals (4.13.7)
registry.AttachInternals(element): NotSupportedError when the element has an is value, is not Precustomized or Custom, its definition disables internals, or internals were attached before. ElementInternals holds:
States(CustomStateSet, a set of strings in insertion order;:state(name)matches it, in snapshots and throughHasCustomState);FormValue/FormStateandSetFormValue(value, state, stateGiven)(opaque to the library);Validity(ValidationProblemsflags),ValidationMessage,ValidationAnchor,IsValid,SetValidity(flags, message, anchor): a flag with an empty message isTypeError; an anchor that is not an HTML element isTypeError, one outside the element's shadow-including subtree isNotFoundError; line breaks of the message are normalized to U+000A; no flags clears all three;WillValidate(a form-associated element that is not disabled, has noreadonlyattribute and has nodatalistancestor) andForm;AriaDefaults(SetAriaDefault): theroleandaria-*defaults the class sets. Snapshots carry them (Document.GetElementInternalsAriaDefault(element, name),HasElementInternalsAria), and the accessibility tree reads them as defaults: an attribute of the page wins. They give the role (an element with noroleattribute takes theroledefault, and the origin is reported as explicit), the states and properties ofStateBuilder(everyaria-*it reads) andaria-labelfor the accessible name. Other name and relation sources (aria-labelledby,aria-describedby,aria-ownsand the other reference attributes) read attributes only. A change of a default is a change of the element in the commit, soAccessibilityTree.UpdateequalsBuild;- everything not form-associated throws
NotSupportedErrorfrom the form members.
The host owns checkValidity/reportValidity events, labels, focusing of anchors, and submission.
9. Shadow roots
MutableNode.AttachShadow and the declarative path refuse a host whose definition disables shadow roots: CustomElementDisablesShadow of the document (a function of the local name) is still honoured for hosts the registry does not know, and the registry's own check (CheckAttachShadow, called by AttachShadow) looks the element up by local name and is value, so customized built-ins are covered too. The check applies when the element's name is a valid custom element name or it has an is value; a refused host with a root or without one both throw NotSupportedError. An upgrade of an element that already has a root fails if the definition disables shadow roots.
10. ElementInternals.shadowRoot
ElementInternals.ShadowRoot returns the host's shadow root, open or closed, when the root is available to element internals (HTML 4.13.7, DOM 4.9): the host was Precustomized or Custom when the root was attached (AttachShadow called from its constructor or later), or the parser made the root from a declarative template. A root attached before the upgrade is not available. The root of a cloned host takes the flag of the original's root (the WPT tests read a cloned declarative root through the internals of the upgraded copy). MutableNode.ShadowRoot keeps returning closed roots too, since the library is the user agent.
11. Scoped registries
HTML 4.13.4 and 4.13.6, DOM 4.5 and 4.9, as Chrome 156 ships them. Every element and every shadow root has a custom element registry: the document's global one, a scoped one, or null; one with no entry of its own has the document's registry (stored as nothing). MutableNode.CustomElementRegistry and MutableDocument.GetCustomElementRegistry read it; the document node's is the document's own registry (first row below); text, comments and fragments have none.
| Piece | Behaviour |
|---|---|
| The document's registry | A document has a custom element registry (DOM 4.5 Document): null for a document made without a browsing context (CreateHtmlDocument, ImplementationCreateDocument, CreateEmpty (new Document()), ParseFromString, CloneDocument), the global registry for a window's document (MutableDocument.Parse, Create, the incremental parser: the default) or a scoped registry once registry.Initialize(document) ran on a null-registry document. MutableNode.CustomElementRegistry of the document root reports it; the document's registry is set once and cannot change again. Everything created in the document without a registry of its own has it (creation, CreateElement with no registry argument, parsing, fragment parsing, shadow roots that name none), and a document with a null registry makes null-registry elements that no definition reaches. CustomElements is still the document's global registry object (where a host defines for a window), but in a document whose registry is not it, it is used for nothing: a global registry given to CreateElement, ImportNode or AttachShadow is NotSupportedError there (DOM 4.5 "flatten element creation options"), and Initialize with it throws as for a document. |
MutableDocument.CreateScopedCustomElementRegistry() | The host's new CustomElementRegistry(). IsScoped is true. A scoped registry belongs to the document that made it (the library has no second document to share it with) and takes autonomous definitions only: extends is NotSupportedError. The same constructor identity may be defined in several registries, once in each. |
| Host settings | ExceptionReporter, AutomaticReactionScopes, BackupQueueMicrotaskRequested, PerformMicrotaskCheckpoint and ThrowOnDynamicMarkupInsertionCounter are the document's: a scoped registry reads and writes the global registry's. Defined and DefinitionRunning are per registry (whenDefined of a scoped registry does not resolve for the global one's names). |
Define | Upgrades the candidates of this registry: HTML elements of the document that have the registry, the name and (customized built-ins) the is value, in shadow-including tree order. An element with another registry, or none, is not touched. |
Upgrade(root), Initialize(root) | Upgrade tries the inclusive shadow-including descendants whose registry is this one. Initialize gives this registry to the root (a null-registry shadow root) and to every inclusive descendant in tree order that has a null registry (it does not enter shadow roots), permanently, clears their "keep null" flag, then tries to upgrade the elements that have this registry. A global registry refuses the document and template content with NotSupportedError, as does any registry for a node of another document. |
| Creating | CreateElement(name, ns, isValue, registry) is createElement with the customElementRegistry option (a null registry is a null registry; isValue must be null). The registry the element gets decides the definition looked up, and ResolveConstructor. Fragment parsing (innerHTML, insertAdjacentHTML, setHTMLUnsafe, ParseFragment) gives the new elements the registry of the node the markup goes into: an element's or a shadow root's own, null in template content. insertAdjacentHTML with BeforeBegin or AfterEnd uses the registry of the parent, not the element's. |
| The parser | An HTML element with a customelementregistry attribute gets a null registry and keeps it null (keep custom element registry null); its descendants inherit a null registry. A template with shadowrootcustomelementregistry makes a root with a null registry that keeps it. Setting the attribute later changes nothing. CreateElementForToken(..., registryParent, forFragment) does this for the incremental parser. |
AttachShadow | ShadowRootInit.CustomElementRegistry with CustomElementRegistryIsSet: the registry of the new root, null for a null registry; the default is the document's global registry, not the host's. A registry of another document is NotSupportedError. |
| Cloning | CloneNode and ImportNode(node, deep, registry) follow DOM 4.5 "clone a node": a copy has its original's registry; an original with a null registry that does not keep it null takes the fallback registry (CloneNode: none; ImportNode: the argument, else the global registry); an element that keeps a null registry stops the fallback for its descendants; the shadow root of a clonable host is cloned with its registry and its children never get the fallback; the content of a template is cloned with no fallback. ImportNode defaults to a shallow copy, as importNode does. |
| Adoption and import between documents | AdoptNode, inserting a node of another MutableDocument, and ImportNode (DOM 4.5 "adopt" and "clone a node") move or copy the subtree with its registries: a scoped registry stays the node's, also when it belongs to the other document; a null registry that is kept null stays null; a global registry becomes the new document's effective global registry (itself when the document's registry is global, else null); a null registry that is not kept follows its new parent, as the effective global registry of the parent's registry (null under a scoped, kept-null or null parent), or the document's for a root or a fragment child (parents are handled first); for a clone with a fallback registry (ImportNode) such an element takes the fallback (the document's registry unless one is given). A shadow root follows the same rule. A scoped registry of another document is only reported: it is not consulted for definitions, so such an element is not upgraded or constructed in the new document. |
| Template content | The content of a template belongs to the template contents owner document, which has no registry. Elements made there have a null registry; a node taken out of template content and inserted into the document tree (or into a shadow root of the document) is adopted: a null registry that is not kept becomes the registry of its new parent, if that is the global one, else null (an element with no parent, a shadow root, or a child of a fragment takes the document's); elements that were global stay global. Nothing is upgraded in template content. A detached copy of template content stays in the owner document until it is inserted. |
| Constructors | The HTML element constructor finds its definition with registry.ResolveConstructor(identity): the registry the constructor is being run for during createElement or an upgrade, else the global registry, else null (the host throws TypeError). The new element of a direct call gets that registry. |
| Serialization | GetHtml and snapshot serialization (HTML 13.3) write is="..." for an element created with an is value and no is attribute, customelementregistry="" for an HTML element without that attribute whose registry differs from the one it inherits from its parent (or the document) and is null or scoped, and shadowrootcustomelementregistry="" for a root unless the root and its document both use the global registry or both null. |
Deviations and what is not done:
initialize(document)and nodes outside the tree.Initialize(document)gives the registry to the document and to every element of its tree that has a null registry (descendants of the document, in tree order). Nodes of the document that are not descendants of it (detached elements and fragments) keep the null registry, as the standard says. To keep that exact, the document first gives every live element and shadow root that has the null registry an entry of its own, which costs one pass over the document's nodes, once.- Registries of other documents. A scoped registry belongs to one
MutableDocument. After adoption or import it still names the node's registry, but it is not consulted for definitions in the new document (one set of reaction queues per document), andCloneDocumentgives the copy a null registry (the spec copies a scoped registry of the original document; here that registry would belong to another document). - Not in the library:
adoptedCallbackfor a scoped registry of another document, theouterHTMLsetter andcreateContextualFragment, browsing contexts (initial-about-blank,per-document, iframes). Scoped registries and:defined: a candidate whose registry has no definition is not defined (:definedfollows the element's state, not its registry).
12. Test coverage
The ledger of the vendored web-platform-tests custom-elements/ suite (commit ffc4686d117de150daf1287809302e3edea82dc6, 213 files) is wpt-custom-elements.md: every file, its number of test calls, whether C# tests cover it, which tests, and why not otherwise. tests/OneHtml.Tests/Mutation/CustomElementTests.cs and CustomElementRestyleTests.cs and ScopedRegistryTests.cs (the scoped registries of registries/) hold the translations; a test checks that the ledger names only files and tests that exist.
The thirty rows of the Shadow DOM inventory tagged custom-elements (28 css/css-shadow/part/ pages that use customElements.define to make a host, shadow-dom/Element-interface-attachShadow-custom-element.html and shadow-dom/slotchange-customelements.html) are translated page by page in tests/OneHtml.Tests/Shadow/Wpt/WptShadowPartPageTests.cs, which loads each page, defines its elements as the page's helper does and checks what its test() calls check. shadow-dom/reference-target/tentative/gethtml-serialization.html waits for the reference-target work (the tentative shadowrootreferencetarget attribute).
The cross-document halves of adopted-callback.html and reactions/* need an iframe or createHTMLDocument page whose script runs the callback; their DOM-level part is tested in WptDomAdoptTests (adoptedCallback after disconnectedCallback and before connectedCallback; a document that takes in a custom element gets a registry).