diff --git a/.changeset/dom-focus-selectors.md b/.changeset/dom-focus-selectors.md new file mode 100644 index 0000000..bf831da --- /dev/null +++ b/.changeset/dom-focus-selectors.md @@ -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. diff --git a/packages/ui/src/css-select.ts b/packages/ui/src/css-select.ts index d393a9d..5c85c13 100644 --- a/packages/ui/src/css-select.ts +++ b/packages/ui/src/css-select.ts @@ -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['adapter']>; @@ -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', diff --git a/packages/ui/src/dom-focus-selectors.test.ts b/packages/ui/src/dom-focus-selectors.test.ts new file mode 100644 index 0000000..29cbd51 --- /dev/null +++ b/packages/ui/src/dom-focus-selectors.test.ts @@ -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' }), + ); + } + }); +}); diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 5b2566c..0afc8f9 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -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'; @@ -580,6 +586,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); } diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index bb36ec1..a62495d 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -75,6 +75,9 @@ const config: WPTConfig = { 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,