Recursive AI

Custom elements

All onehtml docs

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

TypeWhat it is
MutableDocument.CustomElementsThe document's CustomElementRegistry, created on first read.
CustomElementRegistryDefine, Get, GetName, Upgrade, element states, the reactions stack, ConstructHtmlElement, CreateElementForToken, AttachInternals, form hooks.
CustomElementDefinitionAbstract. 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.
CustomElementStateUndefined, Failed, Uncustomized, Precustomized, Custom (4.13.3).
ElementInternals, CustomStateSet, ValidationProblems4.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:

  1. the name is not a valid custom element name: SyntaxError. The production is PotentialCustomElementName of 4.13.3 minus the eight reserved names; a- is valid;
  2. the definition is already defined, the name is taken, or the constructor identity (CustomElementDefinition.ConstructorIdentity, the definition itself by default) is taken: NotSupportedError;
  3. extends is 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;
  4. registry.DefinitionRunning is set: NotSupportedError. The host sets it while it reads the class's properties for the definition (the "element definition is running" flag); Define sets 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: Undefined for an HTML element with a valid custom element name, Uncustomized for every other element;
  • an element created with an is value, or parsed with an is attribute, is Undefined whatever its name; the is value 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 their is attribute;
  • registry.GetState, GetDefinition, GetIsValue, IsDefined (:defined: Uncustomized or Custom; 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 resultWhat happens
no definitiona 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 definitiondefinition.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 state Custom for the definition. For a customized built-in (a definition with extends) 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: DomException with kind TypeError;
  • 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:

C#
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() and PopElementQueueAndInvokeReactions() (or using (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 to ExceptionReporter, or, when none is set, is rethrown after every reaction ran (several as an AggregateException). 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 = false gives 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 calls registry.ProcessBackupElementQueue() from a microtask (the call also lowers the "processing" flag, so a later enqueue asks again). HasPendingBackupQueue says 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 queue connected for a connected custom element and an upgrade attempt for any other element; removing steps queue disconnected for 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 queue attributeChanged for a custom element's observed attributes (added, changed even to the same value, removed; the namespace is passed as a URI string to CustomElementDefinition.AttributeChangedNs, whose default maps it to the AttributeNamespace enum and calls AttributeChanged, so a host that overrides only the older method keeps working and any setAttributeNS namespace survives); cloning steps replay is and look up a definition for the copy. The hooks are registered on the first Define; before that nothing is hooked.
  • Adopted. The adopting step queues adopted(oldDocument, newDocument) for custom elements. The library cannot adopt between documents yet (MutationHooks.AdoptingSteps is reserved), so adoptedCallback is never called today.
  • connectedMoveCallback. moveBefore does not exist in the library, so there is no connectedMoveCallback. When it is added, a move queues connectedMove where the definition has it and disconnected followed by connected where 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 throws DomException with kind LimitExceeded before 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 through HasCustomState);
  • FormValue/FormState and SetFormValue(value, state, stateGiven) (opaque to the library);
  • Validity (ValidationProblems flags), ValidationMessage, ValidationAnchor, IsValid, SetValidity(flags, message, anchor): a flag with an empty message is TypeError; an anchor that is not an HTML element is TypeError, one outside the element's shadow-including subtree is NotFoundError; 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 no readonly attribute and has no datalist ancestor) and Form;
  • AriaDefaults (SetAriaDefault): the role and aria-* 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 no role attribute takes the role default, and the origin is reported as explicit), the states and properties of StateBuilder (every aria-* it reads) and aria-label for the accessible name. Other name and relation sources (aria-labelledby, aria-describedby, aria-owns and the other reference attributes) read attributes only. A change of a default is a change of the element in the commit, so AccessibilityTree.Update equals Build;
  • everything not form-associated throws NotSupportedError from 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.

PieceBehaviour
The document's registryA 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 settingsExceptionReporter, 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).
DefineUpgrades 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.
CreatingCreateElement(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 parserAn 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.
AttachShadowShadowRootInit.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.
CloningCloneNode 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 documentsAdoptNode, 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 contentThe 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.
ConstructorsThe 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.
SerializationGetHtml 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), and CloneDocument gives 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: adoptedCallback for a scoped registry of another document, the outerHTML setter and createContextualFragment, browsing contexts (initial-about-blank, per-document, iframes). Scoped registries and :defined: a candidate whose registry has no definition is not defined (:defined follows 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).