Macros
Macros are build-time functions that the compiler replaces with generated code, to remove the boilerplate that every web component repeats. Each macro is global and needs no import.
Every macro but $defineElement works only inside a component class, which is a class declaration with a static _componentName. The build leaves a call anywhere else as it is, and the call throws at runtime.
$inline
Inlines the contents of an HTML or CSS file as a string at build time.
template.innerHTML = $inline("./my-component.html");The call becomes a string literal with the minified file contents. Keep the HTML and CSS in their own files with full editor tooling and linting, and the output still gets one plain string.
The path is relative to the current module, and only .html and .css files work.
See Writing HTML and CSS as Strings in Limitations for the problem this solves.
$upgrade
Handles own properties that were set on an element before its class upgraded it.
Call it at the start of connectedCallback:
class MyComponent extends HTMLElement { connectedCallback() { $upgrade(); }}Compiles to:
class MyComponent extends HTMLElement { // Added as the first field #__UpgradeProperty = Object.entries(this);
connectedCallback() { for (const [property, value] of this.#__UpgradeProperty) { delete this[property]; this[property] = value; }
this.#__UpgradeProperty = []; }}Deleting each early own property and setting it again runs the prototype setter, as if the value was set after the upgrade.
The generated field comes first in the class to capture the early values before any other field initializer runs. Since the array is empty after the first run, a later connect, like after a remove and re-attach, does nothing.
See Properties Set Before Element Upgrade in Limitations for the problem this solves.
$shadow
Creates and fills a shadow root.
It attaches the shadow root and clones a template into it, with the CSS in a <style> before the HTML. The template is created once, as a static private field, and every instance clones it. Paths are relative to the current module, like in $inline, and a class that extends HTMLElement needs mode.
class MyComponent extends HTMLElement { readonly #shadow = $shadow({ htmlFile: "./my-component.html", cssFile: "./my-component.css", mode: "open", });}Compiles to:
class MyComponent extends HTMLElement { static #__Fragment = (template => { template.innerHTML = "<style>" + $inline("./my-component.css") + "</style>" + $inline("./my-component.html"); return template.content; })(document.createElement("template"));
readonly #shadow = (shadowRoot => { shadowRoot.append(MyComponent.#__Fragment.cloneNode(true)); return shadowRoot; })(this.attachShadow({ mode: "open" }));}In a Component That Extends Another Component
The base already attaches the shadow root, and $shadow adds to that root and returns it. The base's shadow root must be open, and mode cannot change.
- The
cssFilestylesheet is adopted after the base's styles, and its rules win. - The
htmlFilecontents go wherehtmlTargetandhtmlPositionsay. - Any other option goes into an added
attachShadowoverride that merges it into the base's options. The build reports an error if the class already definesattachShadow.
class MyComponent extends BaseComponent { readonly #shadow = $shadow({ htmlFile: "./my-component.html", cssFile: "./my-component.css", htmlTarget: '[part="content"]', htmlPosition: "prepend", delegatesFocus: true, });}Compiles to:
class MyComponent extends BaseComponent { static #__Stylesheet = (() => { const sheet = new CSSStyleSheet(); sheet.replaceSync($inline("./my-component.css")); return sheet; })();
static #__Fragment = (template => { template.innerHTML = $inline("./my-component.html"); return template.content; })(document.createElement("template"));
readonly #shadow = (shadowRoot => { shadowRoot.adoptedStyleSheets.push(MyComponent.#__Stylesheet); shadowRoot.querySelector('[part="content"]').prepend(MyComponent.#__Fragment.cloneNode(true)); return shadowRoot; })(this.shadowRoot);
attachShadow(init) { return super.attachShadow({ ...init, delegatesFocus: true }); }}Options
$shadow accepts all ShadowRootInit options, plus these:
htmlFile
- Type:
string - Description: Path to an HTML file to inline into the shadow root template.
cssFile
- Type:
string - Description: Path to a CSS file to inline into the shadow root.
htmlTarget
- Type:
string - Default: the shadow root
- Description: A selector for the element in the base's shadow root where the
htmlFilecontents go. Select bypartorid, since the build renames classes. It works only in a component that extends another component, together withhtmlFile.
htmlPosition
- Type:
"before" | "prepend" | "append" | "after" - Default:
"append" - Description: Where the
htmlFilecontents go, relative tohtmlTarget.beforeandafteralso needhtmlTarget, because the shadow root has no siblings. It works only in a component that extends another component, together withhtmlFile.
$defineElement
Registers a component class as a custom element.
Call it as a standalone statement at the end of the module, with the component class:
class MyComponent extends HTMLElement { static readonly _componentName = "my-component";}
$defineElement(MyComponent);Compiles to:
if (!customElements.get(MyComponent._componentName)) { customElements.define(MyComponent._componentName, MyComponent);}The tag name comes from the class's static _componentName. A component that is bundled more than once on a page defines its tag once and does not throw a NotSupportedError.
Pass the class by identifier, not as an expression.
$forwardAria
Forwards the host's accessible name and description to an element inside it.
Call it in connectedCallback, with the element that should take them:
class MyComponent extends HTMLElement { connectedCallback() { $forwardAria(this.#input); }}Leave that element without an aria-label of its own, because a field with no label must stay unnamed for accessibility checkers to report it.
Call it once in a class, as a standalone statement. The build fails on a second call, and in an expression position the compiler wraps the generated code in an IIFE.
When It Runs
The forwarding runs on the frame after connect, from attributeChangedCallback, and when focus enters the element from outside. The element has no name until that first frame.
The run on the next frame picks up a <label> that the page adds right after the host in the same task. The run on focus picks up a <label>, or an aria-labelledby or aria-describedby target, that the page adds later. Focus that moves inside the element, like between the controls of a dialog, does not run it again.
Without isExtendable, pass the same element on every connect, because a reconnect keeps the forwarding of the first connect.
Observed Attributes
The build adds aria-label, aria-labelledby, and aria-describedby to observedAttributes. For a form-associated or extendable host, it adds id too, because the id decides which <label for> elements point at the host. When the class has no observedAttributes or attributeChangedCallback, the build creates it.
- The class's own
attributeChangedCallbackcode does not run for an attribute that the build added. - For an attribute that the class already observes, the class's code runs after the forwarding.
- In a class that does not extend another component,
observedAttributesmust be a static field with an array of strings, andattributeChangedCallbackmust be a method with a plain name as its first parameter. The build fails otherwise.
Form-Associated Hosts
Since only a form-associated host can be named by a <label>, the <label> and role parts run only for one. The build keeps them when the class that calls $forwardAria declares static formAssociated = true. An extendable base without that declaration checks formAssociated in the browser, because a subclass may be form-associated, and any other class gets no <label> and role parts.
- The element points at the host's
<label>elements, fromElementInternals.labels. - The host takes the
nonerole while it has noaria-label,aria-labelledby, oraria-describedby, to keep screen readers from reading it as a second named node. - A wrapping
<label>is not supported, because its name includes the host's content, like the buttons of a number field. Use<label for>instead.
These parts need the host's ElementInternals, and the build finds the class field that holds this.attachInternals() on its own. When that field is in a base class, pass it as { internals: this.internals }, since the build fails when it finds neither.
With the Component's Own Naming
Pass { forward: this.#method } when the element's name comes from more than the host, like a popup named after its trigger:
class MyComponent extends HTMLElement { connectedCallback() { $forwardAria(this.#popover, { forward: this.#syncPopoverName }); }
#syncPopoverName() { this.#popover.ariaLabel = this.ariaLabel ?? this.#trigger.ariaLabel; this.#popover.ariaDescribedByElements = this.ariaDescribedByElements; }}The method runs in place of the built-in forwarding, at the same times, and it is the only code that names the element. A takeover by a subclass leaves the name that the method set.
Extending a Component
The last call on a host wins. To let a subclass take over, the base calls $forwardAria with { isExtendable: true }:
class MyComponent extends HTMLElement { connectedCallback() { $forwardAria(this.#popover, { isExtendable: true }); }}The base keeps the observedAttributes and attributeChangedCallback code for both classes. In the subclass, the build adds only the step that clears the base's forwarding and takes over. A takeover forwards at once, and the element keeps its name, also on a reconnect.
In the subclass:
- Call
$forwardAriaaftersuper.connectedCallback()to replace the base's forwarding. - Spread the base's
observedAttributesinto the class's own. - Pass every attribute that the class does not handle to
super.attributeChangedCallback.
class MyExtendedComponent extends MyComponent { static observedAttributes = [...MyComponent.observedAttributes, "placeholder"];
connectedCallback() { super.connectedCallback(); $forwardAria(this.#input); }
attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null) { if (name === "placeholder") { this.#input.placeholder = newValue ?? ""; return; }
super.attributeChangedCallback(name, oldValue, newValue); }}Compiled Output
With { isExtendable: true }, the macro compiles to code like this, with the build's names shortened.
- Without
isExtendable, outside a subclass, the forwarder is a private field that a reconnect keeps, and the clear and takeover steps are left out. - When the class declares
formAssociated,isFormAssociatedistrue, and the build removes the checks. - A host that is not form-associated and not extendable has no
<label>and role steps. Its first forward is a plainrequestAnimationFrame, without the queue. - On the queued frame, every host that connected since the last frame forwards, and the hosts of one root share one scan of its
<label>elements. Every later forward readslabels. - A subclass gets only the
connectedCallbackcode.
// Added once to the modulelet pendingForwarders, labelElementsByControlByRoot;
const queueForwardAria = forwarder => { (pendingForwarders ??= (requestAnimationFrame(() => { labelElementsByControlByRoot = new Map();
for (const pendingForwarder of pendingForwarders) { pendingForwarder(); }
pendingForwarders = labelElementsByControlByRoot = undefined; }), [])).push(forwarder);};
class MyComponent extends HTMLElement { static observedAttributes = ["aria-label", "aria-labelledby", "aria-describedby", "id"];
internals = this.attachInternals(); #input = document.createElement("input");
connectedCallback() { const element = this.#input;
const isFormAssociated = this.constructor.formAssociated;
// Clear earlier call (isExtendable is true) const earlierForwardAria = this[Symbol.for("sv-aria")]; earlierForwardAria?.(0, true);
const forwardAria = (event, isClearing) => { // Undo on takeover (isExtendable is true) if (isClearing) { element.ariaLabelledByElements = element.ariaDescribedByElements = null;
if (isFormAssociated) { this.internals.role = null; }
element.removeEventListener("focusin", forwardAria); return; }
// Skip after a takeover (isExtendable is true), and skip inner focus if (this[Symbol.for("sv-aria")] != forwardAria || element.contains(event?.relatedTarget)) return;
// Name, from the shared scan on the queued frame const rootNode = this.getRootNode();
const labelElements = isFormAssociated && (labelElementsByControlByRoot ? ( labelElementsByControlByRoot.get(rootNode) ?? labelElementsByControlByRoot .set( rootNode, Map.groupBy(rootNode.querySelectorAll("label"), label => label.control) ) .get(rootNode) ).get(this) : this.internals.labels);
element.ariaLabelledByElements = this.ariaLabelledByElements ?? (this.ariaLabel ? [this] : labelElements?.length ? labelElements : null);
// Description element.ariaDescribedByElements = this.ariaDescribedByElements;
// Host role const hostRole = this.ariaLabel || this.ariaLabelledByElements || this.ariaDescribedByElements ? null : "none";
if (isFormAssociated && this.internals.role !== hostRole) { this.internals.role = hostRole; } };
// (isExtendable is true) this[Symbol.for("sv-aria")] = forwardAria;
// Forward now on takeover (isExtendable is true) if (earlierForwardAria) { forwardAria(); }
// Forward next frame queueForwardAria(forwardAria);
// Forward on focus element.addEventListener("focusin", forwardAria); }
attributeChangedCallback(name) { if (["aria-label", "aria-labelledby", "aria-describedby", "id"].includes(name)) { this[Symbol.for("sv-aria")]?.(); return; } }}See Form Components and Accessibility in Limitations for what it cannot cover.
$submitImplicitly
Submits the host's form the way Enter does in a native field. The browser gives this only to native fields, not to form-associated custom elements.
Call it in a keydown listener when the key is Enter, with the event:
class MyComponent extends HTMLElement { #onKeyDown = (event: KeyboardEvent) => { if (event.key === "Enter") { $submitImplicitly(event); } };}In a component that takes text, skip the call while event.isComposing is true, because that Enter ends an IME composition.
Compiles to:
setTimeout(() => { const form = this.form; if (event.defaultPrevented || !form) return;
const defaultButton = [...form.elements].find(control => control.type === "submit"); if (defaultButton) { defaultButton.click(); } else { form.requestSubmit(); }});- It reads the form from
this.form, and a class without aformgetter never submits. - The timeout lets the app's
keydownlisteners on the host run first and cancel the submit withpreventDefault(). - The click on the default button sets
event.submitter, and a disabled default button blocks the submit, as in a native field. - A native field without a submit button submits only when the form has one text-like field, but
$submitImplicitlyalways submits in that case.
See Submitting a Form with Enter in Limitations for the problem this solves.