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 7e5a4fe..fb49058 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -49,50 +49,7 @@ export abstract class Node extends EventTarget { // Adds bubbling to the host EventTarget. Capture traversal and resetting the // host's propagation flags after dispatch are not implemented here. override dispatchEvent(event: Event): boolean { - if (event.eventPhase !== Event.NONE) { - throw new DOMException('Cannot redispatch an active event', 'InvalidStateError'); - } - - const path: Node[] = [this]; - for (let current = this.parentNode; current; current = current.parentNode) { - path.push(current); - } - - // Native dispatch retargets on each node. Keep the tree's original target - // and expose its current node and phase while each native dispatch runs. - Object.defineProperty(event, 'target', { configurable: true, value: this }); - const originals = Object.getOwnPropertyDescriptors(event); - - try { - Object.defineProperty(event, 'composedPath', { - value: () => [...path], - configurable: true, - }); - const end = event.bubbles ? path.length : 1; - for (let i = 0; i < end; i++) { - Object.defineProperties(event, { - currentTarget: { value: path[i], configurable: true }, - eventPhase: { - value: i === 0 ? Event.AT_TARGET : Event.BUBBLING_PHASE, - configurable: true, - }, - }); - super.dispatchEvent.call(path[i], event); - if (event.cancelBubble) { - break; - } - } - return !event.defaultPrevented; - } finally { - for (const name of ['currentTarget', 'eventPhase', 'composedPath']) { - const original = originals[name]; - if (original) { - Object.defineProperty(event, name, original); - } else { - Reflect.deleteProperty(event, name); - } - } - } + return dispatchEvent(this, { event, isTrusted: false }); } hasChildNodes(): boolean { @@ -283,6 +240,8 @@ export class DOMImplementation { export class Document extends Node { declare readonly ownerDocument: null; + #activeElement: Element | null = null; + readonly implementation: DOMImplementation; #factory: (...params: ConstructorParameters) => Element; @@ -304,6 +263,56 @@ export class Document extends Node { return '#document'; } + get activeElement(): Element | null { + return ( + this.#activeElement ?? + (this instanceof HTMLDocument ? this.body : null) ?? + this.documentElement + ); + } + + _setActiveElement(element: Element | null): void { + if (element === this.#activeElement) { + return; + } + + const current = this.#activeElement; + this.#activeElement = null; + + if (current !== null) { + dispatchEvent(current, { + event: new FocusEvent('blur', { + relatedTarget: element, + }), + isTrusted: true, + }); + + dispatchEvent(current, { + event: new FocusEvent('focusout', { + relatedTarget: element, + }), + isTrusted: true, + }); + } + + this.#activeElement = element; + + if (element !== null) { + dispatchEvent(element, { + event: new FocusEvent('focus', { + relatedTarget: current, + }), + isTrusted: true, + }); + dispatchEvent(element, { + event: new FocusEvent('focusin', { + relatedTarget: current, + }), + isTrusted: true, + }); + } + } + get doctype(): DocumentType | null { for (const child of this.childNodes) { if (child instanceof DocumentType) { @@ -776,7 +785,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; + } + this.ownerDocument._setActiveElement(this); + } + + blur(): void { + if (!this.isConnected) { + return; + } else if (this === this.ownerDocument.activeElement) { + this.ownerDocument._setActiveElement(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 {} @@ -793,3 +844,74 @@ export class HTMLUnknownElement extends HTMLElement {} /** XML */ export class XMLDocument extends Document {} + +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; + } +} + +function dispatchEvent( + node: Node, + { event, isTrusted }: { event: Event; isTrusted: boolean }, +): boolean { + if (event.eventPhase !== Event.NONE) { + throw new DOMException('Cannot redispatch an active event', 'InvalidStateError'); + } + + const path: Node[] = [node]; + for (let current = node.parentNode; current; current = current.parentNode) { + path.push(current); + } + + // Native dispatch retargets on each node. Keep the tree's original target + // and expose its current node and phase while each native dispatch runs. + Object.defineProperty(event, 'target', { configurable: true, value: node }); + const originals = Object.getOwnPropertyDescriptors(event); + + try { + Object.defineProperty(event, 'composedPath', { + value: () => [...path], + configurable: true, + }); + const end = event.bubbles ? path.length : 1; + for (let i = 0; i < end; i++) { + Object.defineProperties(event, { + currentTarget: { value: path[i], configurable: true }, + eventPhase: { + value: i === 0 ? Event.AT_TARGET : Event.BUBBLING_PHASE, + configurable: true, + }, + isTrusted: { + value: isTrusted, + configurable: true, + }, + }); + EventTarget.prototype.dispatchEvent.call(path[i]!, event); + if (event.cancelBubble) { + break; + } + } + return !event.defaultPrevented; + } finally { + for (const name of ['currentTarget', 'eventPhase', 'composedPath']) { + const original = originals[name]; + if (original) { + Object.defineProperty(event, name, original); + } else { + Reflect.deleteProperty(event, name); + } + } + } +} diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index 90b6c0d..3f63743 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -68,6 +68,9 @@ const config: WPTConfig = { // Native EventTarget reads handleEvent at registration; the getter-timing // case remains excluded until that behavior is implemented. ], + 'html/editing/focus/focus-management/focusing-disconnected-noop.html': true, + 'html/editing/focus/focus-management/focusing-focused-noop.html': true, + 'html/interaction/focus/focus-management/focus-events.html': true, 'dom/nodes/Document-createTextNode.html': true, 'dom/nodes/Document-createElement.html': [/^createElement\(.*\) in HTML document$/], 'dom/nodes/Document-createElementNS.html': [