From 1f0081af9e9147cbb22363dd96ece73df86d25c5 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Tue, 17 Nov 2026 11:56:01 -0600 Subject: [PATCH] Add programmatic focus with native WPT coverage --- .changeset/dom-focus.md | 5 ++ packages/ui/src/dom.ts | 141 ++++++++++++++++++++++++++++++++++++-- packages/ui/wpt.config.ts | 10 +++ 3 files changed, 152 insertions(+), 4 deletions(-) create mode 100644 .changeset/dom-focus.md diff --git a/.changeset/dom-focus.md b/.changeset/dom-focus.md new file mode 100644 index 00000000..aeda4878 --- /dev/null +++ b/.changeset/dom-focus.md @@ -0,0 +1,5 @@ +--- +'@clack/ui': minor +--- + +Add programmatic element focus and blur, document.activeElement tracking, and trusted focus events. diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index dc38f209..ada5c889 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -213,6 +213,13 @@ export abstract class Node implements EventTarget { this.#childNodes.splice(currentIndex, 1); node.#parentNode = null; + // Removing the focused subtree clears focus without dispatching focus events. + const document = this instanceof Document ? this : this.ownerDocument; + const activeElement = document ? getActiveElement(document) : null; + if (document && activeElement && node.contains(activeElement)) { + setActiveElement(document, null); + } + this.notify([this]); return node; } @@ -364,6 +371,14 @@ export class Document extends Node { return '#document'; } + get activeElement(): Element | null { + return ( + getActiveElement(this) ?? + (this instanceof HTMLDocument ? this.body : null) ?? + this.documentElement + ); + } + get doctype(): DocumentType | null { for (const child of this.childNodes) { if (child instanceof DocumentType) { @@ -566,10 +581,6 @@ export class DocumentType extends Node { } } -export interface EventListener { - (this: EventTarget, event: Event): void; -} - /** Mirrors the DOM spec's attribute change steps: https://dom.spec.whatwg.org/#concept-element-attributes-change-ext */ function attributeChanged(attr: Attr, value: string | null): void { const element = attr.ownerElement; @@ -906,12 +917,35 @@ interface ElementNamespace { prefix: string | null; } +/** Events */ + +export interface EventListener { + (this: EventTarget, event: Event): void; +} + export interface EventOptions { bubbles?: boolean; cancelable?: boolean; composed?: boolean; } +export class FocusEvent extends Event { + override readonly type: 'focus' | 'focusin' | 'focusout' | 'blur'; + readonly relatedTarget: Element | null; + + constructor( + type: 'focus' | 'focusin' | 'focusout' | 'blur', + options: { relatedTarget?: Element | null } = {}, + ) { + super(type, { + bubbles: type === 'focusin' || type === 'focusout', + cancelable: false, + }); + this.type = type; + this.relatedTarget = options.relatedTarget ?? null; + } +} + /* HTML */ export function createHTMLDocument(notify: Node['notify'], title?: string): HTMLDocument { @@ -981,6 +1015,8 @@ export class HTMLDocument extends Document { export class HTMLElement extends Element { #dataset = new DOMStringMap(this); + #onfocus: EventListener | undefined = undefined; + #onblur: EventListener | undefined = undefined; get dataset(): DOMStringMap { return this.#dataset; @@ -993,6 +1029,45 @@ export class HTMLElement extends Element { set tabIndex(value: number) { this.setAttributeNS(null, 'tabindex', String(value | 0)); } + + focus(): void { + if (!this.isConnected) { + return; + } + transitionActiveElement(this.ownerDocument, this); + } + + blur(): void { + if (!this.isConnected) { + return; + } else if (this === this.ownerDocument.activeElement) { + transitionActiveElement(this.ownerDocument, null); + } + } + + get onfocus(): EventListener | undefined { + return this.#onfocus; + } + + set onfocus(listener: EventListener) { + if (this.#onfocus) { + this.removeEventListener('focus', this.#onfocus); + } + this.#onfocus = listener; + this.addEventListener('focus', listener); + } + + get onblur(): EventListener | undefined { + return this.#onblur; + } + + set onblur(listener: EventListener) { + if (this.#onblur) { + this.removeEventListener('blur', this.#onblur); + } + this.#onblur = listener; + this.addEventListener('blur', listener); + } } export interface Focusable extends HTMLElement {} @@ -1030,6 +1105,64 @@ export class HTMLUnknownElement extends HTMLElement {} export class XMLDocument extends Document {} +/** Focus */ + +const activeElements = new WeakMap(); + +function setActiveElement(document: Document, element: Element | null): void { + if (element === null) { + activeElements.delete(document); + } else { + activeElements.set(document, element); + } +} + +function getActiveElement(document: Document): Element | null { + return activeElements.get(document) ?? null; +} + +function transitionActiveElement(document: Document, to: Element | null): void { + const current = getActiveElement(document); + if (to === current) { + return; + } + + setActiveElement(document, null); + + if (current !== null) { + dispatch(current, { + event: new FocusEvent('blur', { + relatedTarget: to, + }), + isTrusted: true, + }); + + dispatch(current, { + event: new FocusEvent('focusout', { + relatedTarget: to, + }), + isTrusted: true, + }); + } + + setActiveElement(document, to); + + if (to !== null) { + dispatch(to, { + event: new FocusEvent('focus', { + relatedTarget: current, + }), + isTrusted: true, + }); + dispatch(to, { + event: new FocusEvent('focusin', { + relatedTarget: current, + }), + isTrusted: true, + }); + } +} + /** internal helpers **/ function getTextContent(node: Element | DocumentFragment): string { diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index 0cd6a015..e3e4ba65 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -214,6 +214,7 @@ const config: WPTConfig = { / with interface Event is not cancelable$/, // WheelEvent and TouchEvent constructors remain unsupported. ], + 'uievents/focusevents/blur-relatedTarget.html': true, 'dom/events/Event-constructors.any.js': true, 'dom/events/Event-dispatch-order-at-target.html': true, 'dom/events/Event-init-while-dispatching.html': [ @@ -345,6 +346,15 @@ const config: WPTConfig = { 'html/dom/reflection-misc.html': [/\.tabIndex:/], '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': [ + 'activeElement initially starts as the document body', + 're-adding the formerly active element to the document does not make it active again', + // The focused-descendant removal case requires innerHTML mutation. + ], + 'dom/nodes/insertion-removing-steps/blur-event.window.js': true, + '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, '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,