Skip to content

Commit 3fe9ed8

Browse files
committed
Add focus pseudo-class selectors and Element.matches
1 parent b523ee5 commit 3fe9ed8

5 files changed

Lines changed: 183 additions & 4 deletions

File tree

‎.changeset/dom-focus-selectors.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@clack/ui': minor
3+
---
4+
5+
Add Element.matches() and :focus, :focus-within, and :focus-visible matching.
6+
Focus is always indicated for the current keyboard-only input dispatcher.

‎packages/ui/src/css-select.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Options } from 'css-select';
22
import { compile as compileSelector, selectAll, selectOne } from 'css-select';
3-
import { Element, Node } from './dom.ts';
3+
import { Element, getActiveElement, Node } from './dom.ts';
44

55
type Adapter = NonNullable<Options<Node, Element>['adapter']>;
66

@@ -61,9 +61,23 @@ const adapter: Adapter = {
6161
},
6262
};
6363

64-
export function compile(selector: string): (node: Node) => boolean {
64+
export function compile(selector: string, context?: Element): (node: Node) => boolean {
65+
if (selector.trim() === '') {
66+
throw new DOMException('A selector must not be empty', 'SyntaxError');
67+
}
6568
try {
66-
return compileSelector(selector, { adapter });
69+
return compileSelector(selector, {
70+
adapter,
71+
context,
72+
relativeSelector: false,
73+
cacheResults: false,
74+
pseudos: {
75+
focus: (element) => getActiveElement(element.ownerDocument) === element,
76+
// Native input is keyboard-only, so focused elements always indicate focus.
77+
'focus-visible': ':focus',
78+
'focus-within': (element) => element.contains(getActiveElement(element.ownerDocument)),
79+
},
80+
});
6781
} catch (error) {
6882
throw new DOMException(
6983
error instanceof Error ? error.message : 'Invalid selector',
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { compile } from './css-select.ts';
3+
import { createNativeDispatch } from './dispatch.ts';
4+
import { createHTMLDocument, type HTMLElement } from './dom.ts';
5+
6+
describe('focus selectors', () => {
7+
it('distinguishes document focus from explicitly focusing the body', () => {
8+
const document = createHTMLDocument(() => {});
9+
const body = document.body!;
10+
11+
expect(document.activeElement).toBe(body);
12+
expect(document.querySelector(':focus')).toBeNull();
13+
expect(document.querySelector(':focus-visible')).toBeNull();
14+
expect(document.querySelector(':focus-within')).toBeNull();
15+
16+
body.tabIndex = -1;
17+
body.focus();
18+
expect(document.querySelectorAll(':focus')).toEqual([body]);
19+
expect(document.querySelectorAll(':focus-visible')).toEqual([body]);
20+
expect(document.querySelectorAll(':focus-within')).toEqual([document.documentElement, body]);
21+
22+
body.blur();
23+
expect(document.activeElement).toBe(body);
24+
expect(body.matches(':focus, :focus-visible, :focus-within')).toBe(false);
25+
});
26+
27+
it('updates reused compound selectors when keyboard navigation moves focus', () => {
28+
const document = createHTMLDocument(() => {});
29+
const container = document.createElement('section');
30+
const inside = document.createElement('button') as HTMLElement;
31+
const outside = document.createElement('button') as HTMLElement;
32+
document.body!.appendChild(container);
33+
container.appendChild(inside);
34+
document.body!.appendChild(outside);
35+
const dispatch = createNativeDispatch(document);
36+
const descendant = compile('section:focus-within button');
37+
const child = compile('section:focus-within > button');
38+
const hasFocus = compile('section:has(:focus)');
39+
40+
for (const [shiftKey, focused] of [
41+
[false, inside],
42+
[false, outside],
43+
[true, inside],
44+
] as const) {
45+
dispatch({ type: 'keydown', key: 'Tab', shiftKey });
46+
expect(document.querySelectorAll(':focus')).toEqual([focused]);
47+
expect(focused.matches(':focus:focus-visible:focus-within')).toBe(true);
48+
expect(container.matches(':focus')).toBe(false);
49+
expect(child(inside)).toBe(focused === inside);
50+
expect(hasFocus(container)).toBe(focused === inside);
51+
expect(descendant(inside)).toBe(focused === inside);
52+
}
53+
});
54+
55+
it('clears focus selectors when an ancestor is removed and reinserted', () => {
56+
const document = createHTMLDocument(() => {});
57+
const container = document.createElement('section');
58+
const input = document.createElement('input') as HTMLElement;
59+
document.body!.appendChild(container);
60+
container.appendChild(input);
61+
input.focus();
62+
expect(container.matches(':focus-within')).toBe(true);
63+
64+
container.remove();
65+
expect(input.matches(':focus, :focus-visible, :focus-within')).toBe(false);
66+
expect(container.matches(':focus-within')).toBe(false);
67+
expect(document.querySelector(':focus-within')).toBeNull();
68+
69+
document.body!.appendChild(container);
70+
expect(input.matches(':focus, :focus-visible, :focus-within')).toBe(false);
71+
expect(container.matches(':focus-within')).toBe(false);
72+
});
73+
74+
it('reflects focus redirected by a blur handler before the outer focus call returns', () => {
75+
const document = createHTMLDocument(() => {});
76+
const container = document.createElement('section');
77+
const current = document.createElement('input') as HTMLElement;
78+
const pending = document.createElement('button') as HTMLElement;
79+
const redirected = document.createElement('button') as HTMLElement;
80+
document.body!.appendChild(container);
81+
container.appendChild(current);
82+
container.appendChild(pending);
83+
document.body!.appendChild(redirected);
84+
current.focus();
85+
current.addEventListener('blur', () => redirected.focus());
86+
87+
pending.focus();
88+
expect(document.querySelectorAll(':focus')).toEqual([redirected]);
89+
expect(container.matches(':focus-within')).toBe(false);
90+
expect(pending.matches(':focus')).toBe(false);
91+
expect(redirected.matches(':focus:focus-visible:focus-within')).toBe(true);
92+
});
93+
94+
it('keeps focus state separate between documents', () => {
95+
const first = createHTMLDocument(() => {});
96+
const second = createHTMLDocument(() => {});
97+
const input = first.createElement('input') as HTMLElement;
98+
const other = second.createElement('input') as HTMLElement;
99+
first.body!.appendChild(input);
100+
second.body!.appendChild(other);
101+
input.focus();
102+
103+
expect(second.querySelector(':focus-within')).toBeNull();
104+
other.focus();
105+
expect(first.querySelector(':focus')).toBe(input);
106+
expect(second.querySelector(':focus')).toBe(other);
107+
input.blur();
108+
expect(other.matches(':focus')).toBe(true);
109+
});
110+
});
111+
112+
describe('Element.matches', () => {
113+
it('matches the element in context, including detached elements and :scope', () => {
114+
const document = createHTMLDocument(() => {});
115+
const container = document.createElement('section');
116+
const button = document.createElement('button');
117+
container.appendChild(button);
118+
119+
expect(button.matches('section > button')).toBe(true);
120+
expect(button.matches(':scope')).toBe(true);
121+
expect(button.matches('section')).toBe(false);
122+
expect(container.matches(':scope > button')).toBe(false);
123+
});
124+
125+
it('rejects missing arguments, invalid selectors, and functional focus pseudos', () => {
126+
const element = createHTMLDocument(() => {}).body!;
127+
// @ts-expect-error Missing required argument.
128+
expect(() => element.matches()).toThrow(TypeError);
129+
for (const selector of [
130+
'',
131+
' ',
132+
'???',
133+
'> body',
134+
':focus()',
135+
':focus-visible()',
136+
':focus-within(x)',
137+
]) {
138+
expect(() => element.matches(selector)).toThrow(
139+
expect.objectContaining({ name: 'SyntaxError' }),
140+
);
141+
}
142+
});
143+
});

‎packages/ui/src/dom.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
/* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */
22
/* oxlint-disable bombshell-dev/exported-function-async -- DOM apis are synchronous. */
33

4-
import { findElement, findElements, querySelector, querySelectorAll } from './css-select.ts';
4+
import {
5+
compile,
6+
findElement,
7+
findElements,
8+
querySelector,
9+
querySelectorAll,
10+
} from './css-select.ts';
511
import { asciiUppercase, asciiLowercase } from './ascii.ts';
612
import { NamedNodeMap } from './named-node-map.ts';
713
import { HTMLCollection } from './html-collection.ts';
@@ -630,6 +636,13 @@ export class Element extends Node {
630636
return serializeOuter(this);
631637
}
632638

639+
matches(selector: string): boolean {
640+
if (arguments.length === 0) {
641+
throw new TypeError('matches requires a selector');
642+
}
643+
return compile(`${selector}`, this)(this);
644+
}
645+
633646
override get textContent(): string {
634647
return getTextContent(this);
635648
}

‎packages/ui/wpt.config.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ const config: WPTConfig<Document> = {
7575
XMLDocument,
7676
},
7777
include: {
78+
'css/selectors/focus-in-focus-event-001.html': true,
79+
'css/selectors/focus-in-focusin-event-001.html': true,
80+
'dom/nodes/ParentNode-querySelector-matches.html': true,
7881
'html/syntax/parsing/the-end.html': ['DOMContentLoaded', 'load'],
7982
'domparsing/Comment-serialization-double-hyphen.html': true,
8083
'domparsing/innerhtml-06.html': true,

0 commit comments

Comments
 (0)