Skip to content

Commit b523ee5

Browse files
committed
Add sequential keyboard focus navigation
1 parent cec0ba3 commit b523ee5

6 files changed

Lines changed: 276 additions & 3 deletions

File tree

‎packages/ui/src/dispatch.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,12 @@
22

33
import {
44
dispatchEvent,
5+
getActiveElement,
6+
getFocusOrder,
7+
incrementFocus,
58
KeyboardEvent,
69
nativeKeyCode,
10+
transitionActiveElement,
711
type Document,
812
type KeyboardEventInit,
913
} from './dom.ts';
@@ -15,7 +19,7 @@ export interface NativeEventDispatch {
1519
export function createNativeDispatch(document: Document): NativeEventDispatch {
1620
return (event: NativeEvent): void => {
1721
if (document.activeElement) {
18-
dispatchEvent(document.activeElement, {
22+
const performDefaultAction = dispatchEvent(document.activeElement, {
1923
event: new KeyboardEvent(event.type, {
2024
...event,
2125
keyCode: nativeKeyCode(event),
@@ -25,6 +29,17 @@ export function createNativeDispatch(document: Document): NativeEventDispatch {
2529
}),
2630
isTrusted: true,
2731
});
32+
33+
if (performDefaultAction && event.type === 'keydown' && event.key === 'Tab') {
34+
const current = getActiveElement(document);
35+
const next = current
36+
? incrementFocus(current, event.shiftKey ? -1 : 1)
37+
: getFocusOrder(document).at(event.shiftKey ? -1 : 0);
38+
39+
if (next) {
40+
transitionActiveElement(document, next);
41+
}
42+
}
2843
}
2944
};
3045
}

‎packages/ui/src/dom.ts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
validateDocumentTypeName,
1717
} from './validation.ts';
1818
import { DOMStringMap } from './dom-string-map.ts';
19+
import { traverse } from './traverse.ts';
1920

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

@@ -1286,11 +1287,58 @@ function setActiveElement(document: Document, element: Element | null): void {
12861287
}
12871288
}
12881289

1289-
function getActiveElement(document: Document): Element | null {
1290+
export function getActiveElement(document: Document): Element | null {
12901291
return focii.get(document) ?? null;
12911292
}
12921293

1293-
function transitionActiveElement(document: Document, to: Element | null): void {
1294+
export function incrementFocus(from: Element, direction: 1 | -1): Element | null {
1295+
const focusOrder = getFocusOrder(from.ownerDocument);
1296+
const start = focusOrder.indexOf(from as HTMLElement);
1297+
1298+
if (start >= 0) {
1299+
const index = (start + direction + focusOrder.length) % focusOrder.length;
1300+
return focusOrder[index] ?? null;
1301+
}
1302+
1303+
const backward = direction < 0;
1304+
for (const node of traverse(from, { backward })) {
1305+
if (node instanceof HTMLElement && focusOrder.indexOf(node) >= 0) {
1306+
return node;
1307+
}
1308+
}
1309+
1310+
return null;
1311+
}
1312+
1313+
export function getFocusOrder(document: Document): HTMLElement[] {
1314+
return document
1315+
.querySelectorAll('*')
1316+
.filter(
1317+
(element): element is HTMLElement => element instanceof HTMLElement && isFocusable(element),
1318+
)
1319+
.map((element) => {
1320+
const value = Number.parseInt(element.getAttribute('tabindex') ?? '', 10);
1321+
return {
1322+
element,
1323+
tabIndex: Number.isNaN(value) ? 0 : value,
1324+
};
1325+
})
1326+
.filter(({ tabIndex }) => tabIndex >= 0)
1327+
.toSorted((a, b) => {
1328+
if (a.tabIndex === b.tabIndex) {
1329+
return 0;
1330+
}
1331+
if (a.tabIndex === 0) {
1332+
return 1;
1333+
}
1334+
if (b.tabIndex === 0) {
1335+
return -1;
1336+
}
1337+
return a.tabIndex - b.tabIndex;
1338+
})
1339+
.map(({ element }) => element);
1340+
}
1341+
export function transitionActiveElement(document: Document, to: Element | null): void {
12941342
const current = getActiveElement(document);
12951343
if (to === current) {
12961344
return;

‎packages/ui/src/testdriver.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,23 @@ function fixture(beforeDispatch?: NativeEventDispatch): TestDriverFixture {
5858
}
5959

6060
describe('testdriver keyboard backend integration', () => {
61+
it('focuses the target once and follows focus changes between Tab key events', async () => {
62+
const { document, first, third, events, driver } = fixture();
63+
let focusCount = 0;
64+
first.addEventListener('focus', () => focusCount++);
65+
66+
await driver.send_keys(first, '\uE004\uE004');
67+
68+
expect(focusCount).toBe(1);
69+
expect(document.activeElement).toBe(third);
70+
expect(events).toEqual([
71+
['keydown', 'Tab', 'first', false],
72+
['keyup', 'Tab', 'second', false],
73+
['keydown', 'Tab', 'second', false],
74+
['keyup', 'Tab', 'third', false],
75+
]);
76+
});
77+
6178
it('dispatches to the active element when a focus handler redirects the target', async () => {
6279
const { document, first, second, events, driver } = fixture();
6380
first.addEventListener('focus', () => second.focus());
@@ -71,6 +88,19 @@ describe('testdriver keyboard backend integration', () => {
7188
]);
7289
});
7390

91+
it('continues from the focused control when the target is the body', async () => {
92+
const { document, second, third, events, driver } = fixture();
93+
second.focus();
94+
95+
await driver.send_keys(document.body, '\uE004');
96+
97+
expect(document.activeElement).toBe(third);
98+
expect(events).toEqual([
99+
['keydown', 'Tab', 'second', false],
100+
['keyup', 'Tab', 'third', false],
101+
]);
102+
});
103+
74104
it('holds automatic Shift across uppercase and punctuation, then releases it for lowercase', async () => {
75105
const { first, events, driver } = fixture();
76106

@@ -88,6 +118,28 @@ describe('testdriver keyboard backend integration', () => {
88118
]);
89119
});
90120

121+
it('handles Shift+Tab and releases modifiers at NULL and completion', async () => {
122+
const { document, second, third, events, driver } = fixture();
123+
124+
await driver.send_keys(second, '\uE008\uE004\uE000\uE004\uE008');
125+
expect(document.activeElement).toBe(second);
126+
await driver.send_keys(second, '\uE004');
127+
128+
expect(document.activeElement).toBe(third);
129+
expect(events).toEqual([
130+
['keydown', 'Shift', 'second', true],
131+
['keydown', 'Tab', 'second', true],
132+
['keyup', 'Tab', 'first', true],
133+
['keyup', 'Shift', 'first', false],
134+
['keydown', 'Tab', 'first', false],
135+
['keyup', 'Tab', 'second', false],
136+
['keydown', 'Shift', 'second', true],
137+
['keyup', 'Shift', 'second', false],
138+
['keydown', 'Tab', 'second', false],
139+
['keyup', 'Tab', 'third', false],
140+
]);
141+
});
142+
91143
it('releases Shift before Control at NULL even when Control was pressed first', async () => {
92144
const { first, events, driver } = fixture();
93145

@@ -101,6 +153,19 @@ describe('testdriver keyboard backend integration', () => {
101153
]);
102154
});
103155

156+
it('honors cancellation of Tab navigation', async () => {
157+
const { document, first, events, driver } = fixture();
158+
first.addEventListener('keydown', (event) => event.preventDefault());
159+
160+
await driver.send_keys(first, '\uE004');
161+
162+
expect(document.activeElement).toBe(first);
163+
expect(events).toEqual([
164+
['keydown', 'Tab', 'first', false],
165+
['keyup', 'Tab', 'first', false],
166+
]);
167+
});
168+
104169
it('queues send_keys after concurrent Actions including their pauses', async () => {
105170
const { first, second, events, driver } = fixture();
106171
first.focus();

‎packages/ui/src/traverse.test.ts‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { createHTMLDocument, type Node } from './dom.ts';
3+
import { traverse } from './traverse.ts';
4+
5+
function expectTraversal(nodes: Iterable<Node>, expected: Node[]): void {
6+
const iterator = nodes[Symbol.iterator]();
7+
const actual = expected.map(() => iterator.next().value);
8+
expect(actual).toEqual(expected);
9+
expect(iterator.next().done).toBe(true);
10+
}
11+
12+
describe('traverse', () => {
13+
it('visits the document and all node types in preorder', () => {
14+
const document = createHTMLDocument(() => {});
15+
const parent = document.body!.appendChild(document.createElement('div'));
16+
const text = parent.appendChild(document.createTextNode('text'));
17+
const comment = parent.appendChild(document.createComment('comment'));
18+
const last = document.body!.appendChild(document.createElement('div'));
19+
20+
expectTraversal(traverse(document), [
21+
document,
22+
document.doctype!,
23+
document.documentElement!,
24+
document.head!,
25+
document.body!,
26+
parent,
27+
text,
28+
comment,
29+
last,
30+
]);
31+
});
32+
33+
it('wraps forward through a fragment and stops before revisiting the nested start', () => {
34+
const document = createHTMLDocument(() => {});
35+
const fragment = document.createDocumentFragment();
36+
const parent = fragment.appendChild(document.createElement('div'));
37+
const start = parent.appendChild(document.createElement('span'));
38+
const text = start.appendChild(document.createTextNode('text'));
39+
const comment = fragment.appendChild(document.createComment('comment'));
40+
const last = fragment.appendChild(document.createElement('div'));
41+
const lastText = last.appendChild(document.createTextNode('last'));
42+
43+
expectTraversal(traverse(start), [start, text, comment, last, lastText, fragment, parent]);
44+
expectTraversal(traverse(lastText), [lastText, fragment, parent, start, text, comment, last]);
45+
});
46+
47+
it('wraps backward through deepest descendants and stops before revisiting the nested start', () => {
48+
const document = createHTMLDocument(() => {});
49+
const fragment = document.createDocumentFragment();
50+
const first = fragment.appendChild(document.createElement('div'));
51+
const nested = first.appendChild(document.createElement('span'));
52+
const text = nested.appendChild(document.createTextNode('text'));
53+
const comment = fragment.appendChild(document.createComment('comment'));
54+
const parent = fragment.appendChild(document.createElement('div'));
55+
const start = parent.appendChild(document.createElement('span'));
56+
const lastText = start.appendChild(document.createTextNode('after the start'));
57+
58+
expectTraversal(traverse(start, { backward: true }), [
59+
start,
60+
parent,
61+
comment,
62+
text,
63+
nested,
64+
first,
65+
fragment,
66+
lastText,
67+
]);
68+
expectTraversal(traverse(fragment, { backward: true }), [
69+
fragment,
70+
lastText,
71+
start,
72+
parent,
73+
comment,
74+
text,
75+
nested,
76+
first,
77+
]);
78+
});
79+
80+
it('stays within a detached element tree in both directions', () => {
81+
const document = createHTMLDocument(() => {});
82+
const root = document.createElement('div');
83+
const text = root.appendChild(document.createTextNode('text'));
84+
85+
expectTraversal(traverse(root, { backward: false }), [root, text]);
86+
expectTraversal(traverse(text), [text, root]);
87+
expectTraversal(traverse(root, { backward: true }), [root, text]);
88+
expectTraversal(traverse(text, { backward: true }), [text, root]);
89+
});
90+
91+
it.each([false, true])('yields a detached single node once with backward=%s', (backward) => {
92+
const document = createHTMLDocument(() => {});
93+
const root = document.createElement('div');
94+
95+
expectTraversal(traverse(root, { backward }), [root]);
96+
});
97+
});

‎packages/ui/src/traverse.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/* oxlint-disable bombshell-dev/exported-function-async -- DOM traversal is synchronous. */
2+
3+
import type { Node } from './dom.ts';
4+
5+
export function* traverse(
6+
from: Node,
7+
{ backward = false }: { backward?: boolean } = {},
8+
): Iterable<Node> {
9+
let root = from;
10+
while (root.parentNode) {
11+
root = root.parentNode;
12+
}
13+
14+
let current = from;
15+
do {
16+
yield current;
17+
18+
if (backward) {
19+
const previous: Node | null = current.previousSibling;
20+
if (!previous && current.parentNode) {
21+
current = current.parentNode;
22+
} else {
23+
current = previous ?? root;
24+
while (current.lastChild) {
25+
current = current.lastChild;
26+
}
27+
}
28+
} else if (current.firstChild) {
29+
current = current.firstChild;
30+
} else {
31+
while (!current.nextSibling && current.parentNode) {
32+
current = current.parentNode;
33+
}
34+
current = current.nextSibling ?? root;
35+
}
36+
} while (current !== from);
37+
}

‎packages/ui/wpt.config.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ const config: WPTConfig<Document> = {
3939
sendKeysWithoutLayout: [
4040
'html/semantics/forms/the-select-element/select-tab-navigation.tentative.html',
4141
'html/semantics/forms/the-select-element/customizable-select/select-tabindex-order.html',
42+
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-negative.html',
43+
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-zero.html',
44+
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-positive.html',
45+
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-order.html',
4246
],
4347
globals: {
4448
AbortController: globalThis.AbortController,
@@ -306,6 +310,13 @@ const config: WPTConfig<Document> = {
306310
'html/editing/focus/focus-management/focusing-disconnected-noop.html': true,
307311
// focusing-focused-noop.html requires the innerHTML setter for setup and cleanup.
308312
'html/interaction/focus/focus-management/focus-events.html': true,
313+
'html/interaction/focus/tab-table-caption.html': true,
314+
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-negative.html': true,
315+
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-zero.html': true,
316+
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-positive.html': true,
317+
'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-order.html': true,
318+
'html/semantics/forms/the-select-element/select-tab-navigation.tentative.html': true,
319+
'html/semantics/forms/the-select-element/customizable-select/select-tabindex-order.html': true,
309320
'focus/focus-sync-when-blur.html': [
310321
'Element.focus() in blur listener when focus has moved away',
311322
],

0 commit comments

Comments
 (0)