diff --git a/.changeset/dom-focus.md b/.changeset/dom-focus.md new file mode 100644 index 0000000..aeda487 --- /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 512f198..0b43fda 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -353,6 +353,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) { @@ -537,10 +545,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; @@ -623,6 +627,18 @@ export class Element extends Node { return exposeAttributes(this.#attributes); } + override removeChild(node: Node): Node { + const result = super.removeChild(node); + + // Removing the focused subtree clears focus without dispatching focus events. + const activeElement = this.ownerDocument.activeElement; + if (activeElement && findElement([node], (element) => element === activeElement)) { + setActiveElement(this.ownerDocument, null); + } + + return result; + } + getAttribute(name: string): string | null { return this.#attributes.getNamedItem(name)?.value ?? null; } @@ -862,12 +878,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; + } +} + /* HTML */ export function createHTMLDocument(notify: Node['notify'], title?: string): HTMLDocument { @@ -934,7 +973,49 @@ export class HTMLDocument extends Document { } } -export class HTMLElement extends Element {} +export class HTMLElement extends Element { + #onfocus: EventListener | undefined = undefined; + #onblur: EventListener | undefined = undefined; + + 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 class HTMLHtmlElement extends HTMLElement {} @@ -954,6 +1035,64 @@ export class HTMLUnknownElement extends HTMLElement {} export class XMLDocument extends Document {} +/** Focus */ + +const focii = new WeakMap(); + +function setActiveElement(document: Document, element: Element | null): void { + if (element === null) { + focii.delete(document); + } else { + focii.set(document, element); + } +} + +function getActiveElement(document: Document): Element | null { + return focii.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 0133db1..22a310b 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -176,6 +176,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': [ @@ -252,6 +253,15 @@ const config: WPTConfig = { 'getElementsByTagName() should be a live collection', // Preserve the existing selection; interface and named own-property coverage remains deferred. ], + '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,