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
6 changes: 6 additions & 0 deletions .changeset/dom-focus-selectors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@clack/ui': minor
---

Add Element.matches() and :focus, :focus-within, and :focus-visible matching.
Focus is always indicated for the current keyboard-only input dispatcher.
20 changes: 17 additions & 3 deletions packages/ui/src/css-select.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Options } from 'css-select';
import { compile as compileSelector, selectAll, selectOne } from 'css-select';
import { Element, Node } from './dom.ts';
import { Element, getActiveElement, Node } from './dom.ts';

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

Expand Down Expand Up @@ -61,9 +61,23 @@ const adapter: Adapter = {
},
};

export function compile(selector: string): (node: Node) => boolean {
export function compile(selector: string, context?: Element): (node: Node) => boolean {
if (selector.trim() === '') {
throw new DOMException('A selector must not be empty', 'SyntaxError');
}
try {
return compileSelector(selector, { adapter });
return compileSelector(selector, {
adapter,
context,
relativeSelector: false,
cacheResults: false,
pseudos: {
focus: (element) => getActiveElement(element.ownerDocument) === element,
// Native input is keyboard-only, so focused elements always indicate focus.
'focus-visible': ':focus',
'focus-within': (element) => element.contains(getActiveElement(element.ownerDocument)),
},
});
} catch (error) {
throw new DOMException(
error instanceof Error ? error.message : 'Invalid selector',
Expand Down
143 changes: 143 additions & 0 deletions packages/ui/src/dom-focus-selectors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { describe, expect, it } from 'vitest';
import { compile } from './css-select.ts';
import { createNativeDispatch } from './dispatch.ts';
import { createHTMLDocument, type HTMLElement } from './dom.ts';

describe('focus selectors', () => {
it('distinguishes document focus from explicitly focusing the body', () => {
const document = createHTMLDocument(() => {});
const body = document.body!;

expect(document.activeElement).toBe(body);
expect(document.querySelector(':focus')).toBeNull();
expect(document.querySelector(':focus-visible')).toBeNull();
expect(document.querySelector(':focus-within')).toBeNull();

body.tabIndex = -1;
body.focus();
expect(document.querySelectorAll(':focus')).toEqual([body]);
expect(document.querySelectorAll(':focus-visible')).toEqual([body]);
expect(document.querySelectorAll(':focus-within')).toEqual([document.documentElement, body]);

body.blur();
expect(document.activeElement).toBe(body);
expect(body.matches(':focus, :focus-visible, :focus-within')).toBe(false);
});

it('updates reused compound selectors when keyboard navigation moves focus', () => {
const document = createHTMLDocument(() => {});
const container = document.createElement('section');
const inside = document.createElement('button') as HTMLElement;
const outside = document.createElement('button') as HTMLElement;
document.body!.appendChild(container);
container.appendChild(inside);
document.body!.appendChild(outside);
const dispatch = createNativeDispatch(document);
const descendant = compile('section:focus-within button');
const child = compile('section:focus-within > button');
const hasFocus = compile('section:has(:focus)');

for (const [shiftKey, focused] of [
[false, inside],
[false, outside],
[true, inside],
] as const) {
dispatch({ type: 'keydown', key: 'Tab', shiftKey });
expect(document.querySelectorAll(':focus')).toEqual([focused]);
expect(focused.matches(':focus:focus-visible:focus-within')).toBe(true);
expect(container.matches(':focus')).toBe(false);
expect(child(inside)).toBe(focused === inside);
expect(hasFocus(container)).toBe(focused === inside);
expect(descendant(inside)).toBe(focused === inside);
}
});

it('clears focus selectors when an ancestor is removed and reinserted', () => {
const document = createHTMLDocument(() => {});
const container = document.createElement('section');
const input = document.createElement('input') as HTMLElement;
document.body!.appendChild(container);
container.appendChild(input);
input.focus();
expect(container.matches(':focus-within')).toBe(true);

container.remove();
expect(input.matches(':focus, :focus-visible, :focus-within')).toBe(false);
expect(container.matches(':focus-within')).toBe(false);
expect(document.querySelector(':focus-within')).toBeNull();

document.body!.appendChild(container);
expect(input.matches(':focus, :focus-visible, :focus-within')).toBe(false);
expect(container.matches(':focus-within')).toBe(false);
});

it('reflects focus redirected by a blur handler before the outer focus call returns', () => {
const document = createHTMLDocument(() => {});
const container = document.createElement('section');
const current = document.createElement('input') as HTMLElement;
const pending = document.createElement('button') as HTMLElement;
const redirected = document.createElement('button') as HTMLElement;
document.body!.appendChild(container);
container.appendChild(current);
container.appendChild(pending);
document.body!.appendChild(redirected);
current.focus();
current.addEventListener('blur', () => redirected.focus());

pending.focus();
expect(document.querySelectorAll(':focus')).toEqual([redirected]);
expect(container.matches(':focus-within')).toBe(false);
expect(pending.matches(':focus')).toBe(false);
expect(redirected.matches(':focus:focus-visible:focus-within')).toBe(true);
});

it('keeps focus state separate between documents', () => {
const first = createHTMLDocument(() => {});
const second = createHTMLDocument(() => {});
const input = first.createElement('input') as HTMLElement;
const other = second.createElement('input') as HTMLElement;
first.body!.appendChild(input);
second.body!.appendChild(other);
input.focus();

expect(second.querySelector(':focus-within')).toBeNull();
other.focus();
expect(first.querySelector(':focus')).toBe(input);
expect(second.querySelector(':focus')).toBe(other);
input.blur();
expect(other.matches(':focus')).toBe(true);
});
});

describe('Element.matches', () => {
it('matches the element in context, including detached elements and :scope', () => {
const document = createHTMLDocument(() => {});
const container = document.createElement('section');
const button = document.createElement('button');
container.appendChild(button);

expect(button.matches('section > button')).toBe(true);
expect(button.matches(':scope')).toBe(true);
expect(button.matches('section')).toBe(false);
expect(container.matches(':scope > button')).toBe(false);
});

it('rejects missing arguments, invalid selectors, and functional focus pseudos', () => {
const element = createHTMLDocument(() => {}).body!;
// @ts-expect-error Missing required argument.
expect(() => element.matches()).toThrow(TypeError);
for (const selector of [
'',
' ',
'???',
'> body',
':focus()',
':focus-visible()',
':focus-within(x)',
]) {
expect(() => element.matches(selector)).toThrow(
expect.objectContaining({ name: 'SyntaxError' }),
);
}
});
});
15 changes: 14 additions & 1 deletion packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
/* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */
/* oxlint-disable bombshell-dev/exported-function-async -- DOM apis are synchronous. */

import { findElement, findElements, querySelector, querySelectorAll } from './css-select.ts';
import {
compile,
findElement,
findElements,
querySelector,
querySelectorAll,
} from './css-select.ts';
import { asciiUppercase, asciiLowercase } from './ascii.ts';
import { NamedNodeMap } from './named-node-map.ts';
import { HTMLCollection } from './html-collection.ts';
Expand Down Expand Up @@ -644,6 +650,13 @@ export class Element extends Node {
return serializeOuter(this);
}

matches(selector: string): boolean {
if (arguments.length === 0) {
throw new TypeError('matches requires a selector');
}
return compile(`${selector}`, this)(this);
}

override get textContent(): string {
return getTextContent(this);
}
Expand Down
3 changes: 3 additions & 0 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ const config: WPTConfig<Document> = {
XMLDocument,
},
include: {
'css/selectors/focus-in-focus-event-001.html': true,
'css/selectors/focus-in-focusin-event-001.html': true,
'dom/nodes/ParentNode-querySelector-matches.html': true,
'html/syntax/parsing/the-end.html': ['DOMContentLoaded', 'load'],
'domparsing/Comment-serialization-double-hyphen.html': true,
'domparsing/innerhtml-06.html': true,
Expand Down
Loading