Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dom-focus.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/ui': minor
---

Add programmatic element focus and blur, document.activeElement tracking, and trusted focus events.
149 changes: 144 additions & 5 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {}

Expand All @@ -954,6 +1035,64 @@ export class HTMLUnknownElement extends HTMLElement {}

export class XMLDocument extends Document {}

/** Focus */

const focii = new WeakMap<Document, Element>();

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 {
Expand Down
10 changes: 10 additions & 0 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ const config: WPTConfig<Document> = {
/ 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': [
Expand Down Expand Up @@ -252,6 +253,15 @@ const config: WPTConfig<Document> = {
'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,
Expand Down
Loading