Skip to content
Merged
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.
141 changes: 137 additions & 4 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand All @@ -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 {}
Expand Down Expand Up @@ -1030,6 +1105,64 @@ export class HTMLUnknownElement extends HTMLElement {}

export class XMLDocument extends Document {}

/** Focus */

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

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,
});
}
}

Comment on lines +1112 to +1165

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be nice to wrap this up in a FocusManager state machine? could give us a good extension point for implementing tab behavior

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@natemoo-re How about we do that with this one #127

Then we'll have all the pieces and we can put them together in a separate module.

/** 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 @@ -214,6 +214,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 @@ -345,6 +346,15 @@ const config: WPTConfig<Document> = {
'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,
Expand Down
Loading