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
17 changes: 16 additions & 1 deletion packages/ui/src/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@

import {
dispatchEvent,
getActiveElement,
getFocusOrder,
incrementFocus,
KeyboardEvent,
nativeKeyCode,
transitionActiveElement,
type Document,
type KeyboardEventInit,
} from './dom.ts';
Expand All @@ -15,7 +19,7 @@ export interface NativeEventDispatch {
export function createNativeDispatch(document: Document): NativeEventDispatch {
return (event: NativeEvent): void => {
if (document.activeElement) {
dispatchEvent(document.activeElement, {
const performDefaultAction = dispatchEvent(document.activeElement, {
event: new KeyboardEvent(event.type, {
...event,
keyCode: nativeKeyCode(event),
Expand All @@ -25,6 +29,17 @@ export function createNativeDispatch(document: Document): NativeEventDispatch {
}),
isTrusted: true,
});

if (performDefaultAction && event.type === 'keydown' && event.key === 'Tab') {
const current = getActiveElement(document);
const next = current
? incrementFocus(current, event.shiftKey ? -1 : 1)
: getFocusOrder(document).at(event.shiftKey ? -1 : 0);

if (next) {
transitionActiveElement(document, next);
}
}
}
};
}
Expand Down
52 changes: 50 additions & 2 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
validateDocumentTypeName,
} from './validation.ts';
import { DOMStringMap } from './dom-string-map.ts';
import { traverse } from './traverse.ts';

const HTML_NS = 'http://www.w3.org/1999/xhtml';

Expand Down Expand Up @@ -1301,11 +1302,58 @@ function setActiveElement(document: Document, element: Element | null): void {
}
}

function getActiveElement(document: Document): Element | null {
export function getActiveElement(document: Document): Element | null {
return focii.get(document) ?? null;
}

function transitionActiveElement(document: Document, to: Element | null): void {
export function incrementFocus(from: Element, direction: 1 | -1): Element | null {
const focusOrder = getFocusOrder(from.ownerDocument);
const start = focusOrder.indexOf(from as HTMLElement);

if (start >= 0) {
const index = (start + direction + focusOrder.length) % focusOrder.length;
return focusOrder[index] ?? null;
}

const backward = direction < 0;
for (const node of traverse(from, { backward })) {
if (node instanceof HTMLElement && focusOrder.indexOf(node) >= 0) {
return node;
}
}

return null;
}

export function getFocusOrder(document: Document): HTMLElement[] {
return document
.querySelectorAll('*')
.filter(
(element): element is HTMLElement => element instanceof HTMLElement && isFocusable(element),
)
.map((element) => {
const value = Number.parseInt(element.getAttribute('tabindex') ?? '', 10);
return {
element,
tabIndex: Number.isNaN(value) ? 0 : value,
};
})
.filter(({ tabIndex }) => tabIndex >= 0)
.toSorted((a, b) => {
if (a.tabIndex === b.tabIndex) {
return 0;
}
if (a.tabIndex === 0) {
return 1;
}
if (b.tabIndex === 0) {
return -1;
}
return a.tabIndex - b.tabIndex;
})
.map(({ element }) => element);
}
export function transitionActiveElement(document: Document, to: Element | null): void {
const current = getActiveElement(document);
if (to === current) {
return;
Expand Down
97 changes: 97 additions & 0 deletions packages/ui/src/traverse.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { describe, expect, it } from 'vitest';
import { createHTMLDocument, type Node } from './dom.ts';
import { traverse } from './traverse.ts';

function expectTraversal(nodes: Iterable<Node>, expected: Node[]): void {
const iterator = nodes[Symbol.iterator]();
const actual = expected.map(() => iterator.next().value);
expect(actual).toEqual(expected);
expect(iterator.next().done).toBe(true);
}

describe('traverse', () => {
it('visits the document and all node types in preorder', () => {
const document = createHTMLDocument(() => {});
const parent = document.body!.appendChild(document.createElement('div'));
const text = parent.appendChild(document.createTextNode('text'));
const comment = parent.appendChild(document.createComment('comment'));
const last = document.body!.appendChild(document.createElement('div'));

expectTraversal(traverse(document), [
document,
document.doctype!,
document.documentElement!,
document.head!,
document.body!,
parent,
text,
comment,
last,
]);
});

it('wraps forward through a fragment and stops before revisiting the nested start', () => {
const document = createHTMLDocument(() => {});
const fragment = document.createDocumentFragment();
const parent = fragment.appendChild(document.createElement('div'));
const start = parent.appendChild(document.createElement('span'));
const text = start.appendChild(document.createTextNode('text'));
const comment = fragment.appendChild(document.createComment('comment'));
const last = fragment.appendChild(document.createElement('div'));
const lastText = last.appendChild(document.createTextNode('last'));

expectTraversal(traverse(start), [start, text, comment, last, lastText, fragment, parent]);
expectTraversal(traverse(lastText), [lastText, fragment, parent, start, text, comment, last]);
});

it('wraps backward through deepest descendants and stops before revisiting the nested start', () => {
const document = createHTMLDocument(() => {});
const fragment = document.createDocumentFragment();
const first = fragment.appendChild(document.createElement('div'));
const nested = first.appendChild(document.createElement('span'));
const text = nested.appendChild(document.createTextNode('text'));
const comment = fragment.appendChild(document.createComment('comment'));
const parent = fragment.appendChild(document.createElement('div'));
const start = parent.appendChild(document.createElement('span'));
const lastText = start.appendChild(document.createTextNode('after the start'));

expectTraversal(traverse(start, { backward: true }), [
start,
parent,
comment,
text,
nested,
first,
fragment,
lastText,
]);
expectTraversal(traverse(fragment, { backward: true }), [
fragment,
lastText,
start,
parent,
comment,
text,
nested,
first,
]);
});

it('stays within a detached element tree in both directions', () => {
const document = createHTMLDocument(() => {});
const root = document.createElement('div');
const text = root.appendChild(document.createTextNode('text'));

expectTraversal(traverse(root, { backward: false }), [root, text]);
expectTraversal(traverse(text), [text, root]);
expectTraversal(traverse(root, { backward: true }), [root, text]);
expectTraversal(traverse(text, { backward: true }), [text, root]);
});

it.each([false, true])('yields a detached single node once with backward=%s', (backward) => {
const document = createHTMLDocument(() => {});
const root = document.createElement('div');

expectTraversal(traverse(root, { backward }), [root]);
});
});
41 changes: 41 additions & 0 deletions packages/ui/src/traverse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/* oxlint-disable bombshell-dev/exported-function-async -- DOM traversal is synchronous. */

import type { Node } from './dom.ts';

/**
* Iterate nodes in either forward or reverse DOM order starting with
* `from` and looping around until `from` is encountered again.
*/
export function* traverse(
from: Node,
{ backward = false }: { backward?: boolean } = {},
): Iterable<Node> {
let root = from;
while (root.parentNode) {
root = root.parentNode;
}

let current = from;
do {
yield current;

if (backward) {
const previous: Node | null = current.previousSibling;
if (!previous && current.parentNode) {
current = current.parentNode;
} else {
current = previous ?? root;
while (current.lastChild) {
current = current.lastChild;
}
}
} else if (current.firstChild) {
current = current.firstChild;
} else {
while (!current.nextSibling && current.parentNode) {
current = current.parentNode;
}
current = current.nextSibling ?? root;
}
} while (current !== from);
}
11 changes: 11 additions & 0 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ const config: WPTConfig<Document> = {
sendKeysWithoutLayout: [
'html/semantics/forms/the-select-element/select-tab-navigation.tentative.html',
'html/semantics/forms/the-select-element/customizable-select/select-tabindex-order.html',
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-negative.html',
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-zero.html',
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-positive.html',
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-order.html',
],
globals: {
AbortController: globalThis.AbortController,
Expand Down Expand Up @@ -323,6 +327,13 @@ 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,
'html/interaction/focus/tab-table-caption.html': true,
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-negative.html': true,
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-zero.html': true,
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-positive.html': true,
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-order.html': true,
'html/semantics/forms/the-select-element/select-tab-navigation.tentative.html': true,
'html/semantics/forms/the-select-element/customizable-select/select-tabindex-order.html': true,
'focus/focus-sync-when-blur.html': [
'Element.focus() in blur listener when focus has moved away',
],
Expand Down
Loading