diff --git a/.changeset/dom-inert.md b/.changeset/dom-inert.md new file mode 100644 index 0000000..c986096 --- /dev/null +++ b/.changeset/dom-inert.md @@ -0,0 +1,5 @@ +--- +'@clack/ui': minor +--- + +Reflect the inert attribute on HTML elements and prevent programmatic focus inside inert subtrees. diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index ada5c88..571900d 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -1030,10 +1030,29 @@ export class HTMLElement extends Element { this.setAttributeNS(null, 'tabindex', String(value | 0)); } + get inert(): boolean { + return this.hasAttributeNS(null, 'inert'); + } + + set inert(value: boolean) { + if (value) { + this.setAttributeNS(null, 'inert', ''); + } else { + this.removeAttributeNS(null, 'inert'); + } + } + focus(): void { if (!this.isConnected) { return; } + // inert nodes don't get focus + // oxlint-disable-next-line typescript/no-this-alias -- This cursor walks the node's ancestry. + for (let node: Node | null = this; node; node = node.parentNode) { + if (node instanceof HTMLElement && node.inert) { + return; + } + } transitionActiveElement(this.ownerDocument, this); } diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index e3e4ba6..8dfac40 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -343,7 +343,7 @@ const config: WPTConfig = { 'dom/nodes/querySelector-id-nth-child.html': [ 'querySelectorAll matching #id + constant nth-child()', ], - 'html/dom/reflection-misc.html': [/\.tabIndex:/], + 'html/dom/reflection-misc.html': [/\.tabIndex:/, /^html\.inert:/], 'html/dom/reflection-forms.html': [/\.tabIndex:/], 'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-default-value.html': true, 'html/editing/focus/focus-management/active-element.html': [ @@ -355,6 +355,9 @@ const config: WPTConfig = { 'html/editing/focus/focus-management/focusing-disconnected-noop.html': true, // focusing-focused-noop.html requires the innerHTML setter for setup and cleanup. 'html/interaction/focus/focus-management/focus-events.html': true, + // inert/inert-node-is-unfocusable.html requires testdriver click setup: + // real layout, hit testing, and an input backend are not available yet. + 'inert/nested-inert-unfocusable.html': true, 'dom/nodes/Document-createEvent.https.html': [ /^(?:Event|Events|HTMLEvents|SVGEvents) should be an alias for Event\.$/i, /^createEvent\('(?:Event|Events|HTMLEvents|SVGEvents)'\) should be initialized correctly\.$/i,