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-focusability.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/ui': minor
---

Add HTML focusability checks for [HTMLElement.focus()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) and reflected [disabled attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/disabled) on form controls.
129 changes: 117 additions & 12 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -964,9 +964,19 @@ export class HTMLDocument extends Document {
['head', HTMLHeadElement],
['title', HTMLTitleElement],
['body', HTMLBodyElement],
['a', HTMLAnchorElement],
['button', HTMLButtonElement],
['input', HTMLInputElement],
['select', HTMLSelectElement],
['textarea', HTMLTextAreaElement],
['option', HTMLOptionElement],
['optgroup', HTMLOptGroupElement],
['fieldset', HTMLFieldSetElement],
['span', HTMLSpanElement],
['div', HTMLDivElement],
['iframe', HTMLIFrameElement],
['details', HTMLDetailsElement],
['summary', HTMLSummaryElement],
]);
constructor(notify: Node['notify']) {
super(notify, (owner, localName, notifyElement, namespace) => {
Expand Down Expand Up @@ -1024,24 +1034,26 @@ export class HTMLElement extends Element {
}

get tabIndex(): number {
const attr = this.getAttributeNS(null, 'tabindex');
return attr === null ? -1 : Number.parseInt(attr, 10) || 0;
const attr = this.getAttributeNodeNS(null, 'tabindex');
if (!attr) {
return -1;
} else {
const value = Number.parseInt(attr.value, 10);
if (Number.isNaN(value)) {
return -1;
}
return value === 0 ? 0 : value;
}
}

set tabIndex(value: number) {
this.setAttributeNS(null, 'tabindex', String(value));
}

focus(): void {
if (!this.isConnected) {
if (!isFocusable(this)) {
return;
}
// inert nodes don't get focus
for (const node of lineage(this)) {
if (node instanceof HTMLElement && node.inert) {
return;
}
}
transitionActiveElement(this.ownerDocument, this);
}

Expand Down Expand Up @@ -1085,7 +1097,7 @@ export const Focusable = createMixin<Focusable, Constructor<HTMLElement>>(
class extends Base {
override get tabIndex(): number {
const attr = this.getAttributeNS(null, 'tabindex');
return attr ? super.tabIndex : 0;
return attr !== null && !Number.isNaN(Number.parseInt(attr, 10)) ? super.tabIndex : 0;
}

override set tabIndex(value: number) {
Expand All @@ -1094,6 +1106,27 @@ export const Focusable = createMixin<Focusable, Constructor<HTMLElement>>(
},
);

export interface Disablable extends HTMLElement {
disabled: boolean;
}

export const Disablable = createMixin<Disablable, Constructor<HTMLElement>>(
(Base) =>
class extends Base implements Disablable {
get disabled(): boolean {
return this.hasAttributeNS(null, 'disabled');
}

set disabled(value: boolean) {
if (value) {
this.setAttributeNS(null, 'disabled', '');
} else {
this.removeAttributeNS(null, 'disabled');
}
}
},
);

export class HTMLHtmlElement extends HTMLElement {}

export class HTMLHeadElement extends HTMLElement {}
Expand All @@ -1106,7 +1139,27 @@ export class HTMLSpanElement extends HTMLElement {}

export class HTMLDivElement extends HTMLElement {}

export class HTMLButtonElement extends mixin(HTMLElement, [Focusable]) {}
export class HTMLAnchorElement extends mixin(HTMLElement, [Focusable]) {}

export class HTMLButtonElement extends mixin(HTMLElement, [Disablable, Focusable]) {}

export class HTMLInputElement extends mixin(HTMLElement, [Disablable, Focusable]) {}

export class HTMLSelectElement extends mixin(HTMLElement, [Disablable, Focusable]) {}

export class HTMLTextAreaElement extends mixin(HTMLElement, [Disablable, Focusable]) {}

export class HTMLFieldSetElement extends mixin(HTMLElement, [Disablable]) {}

export class HTMLOptionElement extends mixin(HTMLElement, [Disablable]) {}

export class HTMLOptGroupElement extends mixin(HTMLElement, [Disablable]) {}

export class HTMLIFrameElement extends mixin(HTMLElement, [Focusable]) {}

export class HTMLDetailsElement extends HTMLElement {}

export class HTMLSummaryElement extends HTMLElement {}

export class HTMLUnknownElement extends HTMLElement {}

Expand Down Expand Up @@ -1146,12 +1199,18 @@ function transitionActiveElement(document: Document, to: Element | null): void {
isTrusted: true,
});

const detected = getActiveElement(document);

dispatchEvent(current, {
event: new FocusEvent('focusout', {
relatedTarget: to,
relatedTarget: detected ? null : to,
}),
isTrusted: true,
});

if (detected || getActiveElement(document)) {
return;
}
}

setActiveElement(document, to);
Expand All @@ -1163,6 +1222,11 @@ function transitionActiveElement(document: Document, to: Element | null): void {
}),
isTrusted: true,
});

if (getActiveElement(document) !== to) {
return;
}

dispatchEvent(to, {
event: new FocusEvent('focusin', {
relatedTarget: current,
Expand All @@ -1172,6 +1236,47 @@ function transitionActiveElement(document: Document, to: Element | null): void {
}
}

function isFocusable(element: HTMLElement): boolean {
if (!element.isConnected) {
return false;
}

for (const node of lineage(element)) {
if (node instanceof HTMLElement && node.inert) {
return false;
}
if (node instanceof Disablable && node.disabled) {
return false;
}
}

const hasTabIndex = (target: HTMLElement): boolean => {
const attr = target.getAttributeNode('tabindex');
return !!attr && !isNaN(Number(attr.value));
};

switch (element.localName) {
case 'a':
return !!element.getAttributeNodeNS(null, 'href') || hasTabIndex(element);
case 'input':
return element.getAttributeNS(null, 'type') !== 'hidden';
case 'summary':
return (
hasTabIndex(element) ||
(element.parentElement instanceof HTMLDetailsElement &&
element.parentElement.children[0] === element)
);
default: {
const editable = element.getAttribute('contenteditable');
return (
(editable && ['true', '', 'plaintext-only'].includes(editable)) ||
hasTabIndex(element) ||
element.tabIndex === 0
);
}
}
}

/** Connect a host window to the document's event path and listener machinery. */
export function connectWindow(document: Document, window: EventTarget): void {
if (!eventRegistries.has(window)) {
Expand Down
48 changes: 47 additions & 1 deletion packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,12 @@ const config: WPTConfig<Document> = {
'dom/events/Event-defaultPrevented-after-dispatch.html': true,
'dom/events/Event-dispatch-detached-click.html': true,
'dom/events/Event-dispatch-other-document.html': true,
'dom/events/Event-dispatch-on-disabled-elements.html': [
"Can dispatch untrusted 'click' Events at disabled HTML elements.",
'Can dispatch untrusted Events at disabled HTML elements.',
'Can dispatch CustomEvents at disabled HTML elements.',
// Other cases require click(), layout, animation, or pointer input.
],
'dom/events/Event-initEvent.html': true,
'dom/events/Event-propagation.html': true,
'dom/events/Event-returnValue.html': true,
Expand Down Expand Up @@ -286,11 +292,51 @@ const config: WPTConfig<Document> = {
'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,
'focus/focus-sync-when-blur.html': [
'Element.focus() in blur listener when focus has moved away',
],
'focus/focus-double-sync-calls.html': [
'Element.focus() in focus listener when focus has moved away',
],
// inert/inert-node-is-unfocusable.html requires testdriver click setup:
// real layout, hit testing, and an input backend are not available yet.
'inert/nested-inert-unfocusable.html': true,
'html/dom/reflection-misc.html': [/^html\.inert:/, /^html\.tabIndex:/],
'html/dom/reflection-forms.html': [/^button\.tabIndex:/],
'html/dom/reflection-forms.html': [
/^button\.tabIndex:/,
/^(button|input|select|textarea|fieldset|optgroup|option)\.disabled:/,
],
'html/interaction/focus/tabindex-focus-flag.html': [
'a should not be focusable by default.',
'a[href] should be focusable by default.',
'button should be focusable by default.',
'input[type="hidden"] should not be focusable by default.',
'input[type="button"] should be focusable by default.',
'select should be focusable by default.',
'textarea should be focusable by default.',
'#summary-out should not be focusable by default.',
'#summary-first should be focusable by default.',
'#summary-second should not be focusable by default.',
'[contenteditable] should be focusable by default.',
'iframe should be focusable by default.',
'img should not be focusable by default.',
'A with tabindex=0 should be focusable.',
'SUMMARY#summary-out-tabindex0 with tabindex=0 should be focusable.',
'SUMMARY#summary-second-tabindex0 with tabindex=0 should be focusable.',
'IMG with tabindex=0 should be focusable.',
'A with tabindex=-1 should be focusable.',
'SUMMARY#summary-out-tabindex-negative with tabindex=-1 should be focusable.',
'SUMMARY#summary-second-tabindex-negative with tabindex=-1 should be focusable.',
'IMG with tabindex=-1 should be focusable.',
'A with tabindex=invalid should not be focusable.',
'A#with-href with tabindex=invalid should be focusable.',
'DIV with tabindex=invalid should not be focusable.',
'SUMMARY#summary-out-tabindex-invalid with tabindex=invalid should not be focusable.',
'IMG with tabindex=invalid should not be focusable.',
// SVG focus coverage awaits its element interfaces.
],
'html/semantics/forms/the-input-element/number-disabled.html': true,
'html/semantics/disabled-elements/disabledElement.html': true,
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-default-value.html': true,
'dom/nodes/NodeList-Iterable.html': [/^NodeList /],
'dom/nodes/ParentNode-querySelector-All-comma-selector.html': [
Expand Down
Loading