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.
212 changes: 164 additions & 48 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,61 @@ export class Document {
['div', HTMLDivElement],
]);

#activeElement: Element | null = null;

constructor(notify: () => void) {
this.notify = notify;
this.documentElement = this.createElement('html');
this.body = this.createElement('body');
this.body = this.createElement('body') as HTMLBodyElement;

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.

I wonder if we could type createElement to return the correct type?

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.

Yes, we definitely could. It's going to be really handy when we start making JSX integrations, especially with custom elements.

I'm a bit at a loss as to the best way to do it now however. I mean, there are a couple ways we could go about it, but I do worry that a solution invested in now, might just get in the way of our ultimate solution.

I agree that it's something we should do though. If we can record it somewhere, is a follow-on ok?

this.documentElement.appendChild(this.body);
}

get activeElement(): Element {
return this.#activeElement ?? this.body;

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.

body is the default activeElement? TIL!

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.

who knew?!?

}

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

getElementsByTagName(qualifiedName: string): HTMLCollection {
if (arguments.length === 0) {
throw new TypeError('getElementsByTagName requires a qualified name');
Expand Down Expand Up @@ -172,53 +220,8 @@ export abstract class Node extends EventTarget {
this.ownerDocument = owner;
}

// 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 {
Expand Down Expand Up @@ -461,7 +464,49 @@ export class Element extends Node {
}
}

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

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.

interesting! do you know how the browser handles privileged methods like this?maybe this could be a local function that stores state per document in a WeakMap or something? there's probably a nicer way than that, just the first thing that came to mind.

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.

Yeah, we could do it that way. It would certainly make it so that don't have a "rogue" public method that someone could invoke on their own.

}

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 {}

Expand Down Expand Up @@ -629,3 +674,74 @@ const Event = globalThis.Event as typeof globalThis.Event & {
readonly AT_TARGET: 2;
readonly BUBBLING_PHASE: 3;
};

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);
}
}
}
}
3 changes: 3 additions & 0 deletions packages/ui/test/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ const config: WPTConfig = {
// Four other cases require innerHTML or outerHTML mutation.
],
'html/dom/documents/dom-tree-accessors/Document.body.html': true,
'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-getElementsByTagName.html': [
'Caching is allowed',
"Shouldn't be able to set unsigned properties on a HTMLCollection (non-strict mode)",
Expand Down
Loading