From 19f4b81440310908363d161ecacaad4af174aeb8 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Mon, 30 Nov 2026 16:28:53 -0600 Subject: [PATCH 1/4] Add focus pseudo-class selectors and Element.matches --- .changeset/dom-focus-selectors.md | 6 + packages/ui/src/css-select.ts | 18 ++- packages/ui/src/dom-focus-selectors.test.ts | 150 ++++++++++++++++++++ packages/ui/src/dom.ts | 17 ++- packages/ui/wpt.config.ts | 3 + 5 files changed, 190 insertions(+), 4 deletions(-) create mode 100644 .changeset/dom-focus-selectors.md create mode 100644 packages/ui/src/dom-focus-selectors.test.ts diff --git a/.changeset/dom-focus-selectors.md b/.changeset/dom-focus-selectors.md new file mode 100644 index 0000000..6a18ced --- /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. +Treat focused elements as focus-visible in the terminal. diff --git a/packages/ui/src/css-select.ts b/packages/ui/src/css-select.ts index 0d791eb..abad3c4 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']>; @@ -62,8 +62,22 @@ const adapter: Adapter = { }; export function compile(selector: string, context?: Node): (node: Node) => boolean { + if (selector.trim() === '') { + throw new DOMException('A selector must not be empty', 'SyntaxError'); + } try { - return compileSelector(selector, { adapter, context, relativeSelector: false }); + return compileSelector(selector, { + adapter, + context, + relativeSelector: false, + cacheResults: false, + pseudos: { + focus: (element) => getActiveElement(element.ownerDocument) === element, + // Focused elements always indicate focus in the terminal. + '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..3d98b69 --- /dev/null +++ b/packages/ui/src/dom-focus-selectors.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, it } from 'vitest'; +import { compile } from './css-select.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 programmatic focus changes', () => { + 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 descendant = compile('section:focus-within button'); + const child = compile('section:focus-within > button'); + const hasFocus = compile('section:has(:focus)'); + + for (const focused of [inside, outside, inside]) { + focused.focus(); + 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('updates selectors synchronously during blur and focus handlers', () => { + const document = createHTMLDocument(() => {}); + const container = document.createElement('section'); + const current = document.createElement('input') as HTMLElement; + const pending = document.createElement('button') as HTMLElement; + const outside = document.createElement('button') as HTMLElement; + document.body!.appendChild(container); + container.appendChild(current); + container.appendChild(pending); + document.body!.appendChild(outside); + current.focus(); + const observed: boolean[] = []; + current.addEventListener('blur', () => { + observed.push( + document.querySelector(':focus') === null && !container.matches(':focus-within'), + ); + }); + pending.addEventListener('focus', () => { + observed.push(pending.matches(':focus') && container.matches(':focus-within')); + }); + outside.addEventListener('focus', () => { + observed.push(outside.matches(':focus') && !container.matches(':focus-within')); + }); + + pending.focus(); + outside.focus(); + expect(observed).toEqual([true, true, true]); + expect(document.querySelectorAll(':focus')).toEqual([outside]); + expect(container.matches(':focus-within')).toBe(false); + expect(pending.matches(':focus')).toBe(false); + expect(outside.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 ada5c88..eca1edb 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 { exposeAttributes, NamedNodeMap } from './named-node-map.ts'; import { HTMLCollection } from './html-collection.ts'; @@ -662,6 +668,13 @@ export class Element extends Node { return querySelectorAll(this, { selector: `${selector}` }); } + 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); } @@ -1117,7 +1130,7 @@ function setActiveElement(document: Document, element: Element | null): void { } } -function getActiveElement(document: Document): Element | null { +export function getActiveElement(document: Document): Element | null { return activeElements.get(document) ?? null; } diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index e3e4ba6..f9dda46 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -71,6 +71,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'], 'html/browsers/the-window-object/Document-defaultView.html': [ 'Document in a browsing context', From 0d85c3ce26f9050cbc35cb39368f69af365a95bb Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Sat, 5 Dec 2026 20:52:33 -0600 Subject: [PATCH 2/4] Use upstream WPT coverage for focus selectors --- packages/ui/src/dom-focus-selectors.test.ts | 150 -------------------- packages/ui/wpt.config.ts | 8 ++ 2 files changed, 8 insertions(+), 150 deletions(-) delete mode 100644 packages/ui/src/dom-focus-selectors.test.ts diff --git a/packages/ui/src/dom-focus-selectors.test.ts b/packages/ui/src/dom-focus-selectors.test.ts deleted file mode 100644 index 3d98b69..0000000 --- a/packages/ui/src/dom-focus-selectors.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { compile } from './css-select.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 programmatic focus changes', () => { - 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 descendant = compile('section:focus-within button'); - const child = compile('section:focus-within > button'); - const hasFocus = compile('section:has(:focus)'); - - for (const focused of [inside, outside, inside]) { - focused.focus(); - 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('updates selectors synchronously during blur and focus handlers', () => { - const document = createHTMLDocument(() => {}); - const container = document.createElement('section'); - const current = document.createElement('input') as HTMLElement; - const pending = document.createElement('button') as HTMLElement; - const outside = document.createElement('button') as HTMLElement; - document.body!.appendChild(container); - container.appendChild(current); - container.appendChild(pending); - document.body!.appendChild(outside); - current.focus(); - const observed: boolean[] = []; - current.addEventListener('blur', () => { - observed.push( - document.querySelector(':focus') === null && !container.matches(':focus-within'), - ); - }); - pending.addEventListener('focus', () => { - observed.push(pending.matches(':focus') && container.matches(':focus-within')); - }); - outside.addEventListener('focus', () => { - observed.push(outside.matches(':focus') && !container.matches(':focus-within')); - }); - - pending.focus(); - outside.focus(); - expect(observed).toEqual([true, true, true]); - expect(document.querySelectorAll(':focus')).toEqual([outside]); - expect(container.matches(':focus-within')).toBe(false); - expect(pending.matches(':focus')).toBe(false); - expect(outside.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/wpt.config.ts b/packages/ui/wpt.config.ts index f9dda46..9911855 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -73,6 +73,12 @@ const config: WPTConfig = { include: { 'css/selectors/focus-in-focus-event-001.html': true, 'css/selectors/focus-in-focusin-event-001.html': true, + 'css/selectors/focus-within.html': true, + 'dom/nodes/Element-matches-namespaced-elements.html': [ + 'empty string namespace, matches', + 'has a namespace, matches', + // Wildcard namespace selectors and webkitMatchesSelector remain unsupported. + ], 'dom/nodes/ParentNode-querySelector-matches.html': true, 'html/syntax/parsing/the-end.html': ['DOMContentLoaded', 'load'], 'html/browsers/the-window-object/Document-defaultView.html': [ @@ -319,6 +325,7 @@ const config: WPTConfig = { 'dom/nodes/ParentNode-querySelector-empty-attribute-value.html': true, 'dom/nodes/ParentNode-querySelector-invalid-comment-like.html': [ 'querySelectorAll throws SyntaxError for comment-like selector', + 'matches throws SyntaxError for comment-like selector', ], 'dom/nodes/ParentNode-querySelector-is-nested-pseudo-class.html': true, 'dom/nodes/ParentNode-querySelector-orphan-scope.html': true, @@ -355,6 +362,7 @@ const config: WPTConfig = { // The focused-descendant removal case requires innerHTML mutation. ], 'dom/nodes/insertion-removing-steps/blur-event.window.js': true, + 'html/editing/focus/focus-management/focus-blur.html': true, '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, From 43f445bdd55a5ce6b5d9d7e8c5d0a20ca2593e07 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Sat, 5 Dec 2026 21:16:52 -0600 Subject: [PATCH 3/4] Notify the renderer when focus changes --- .changeset/dom-focus-selectors.md | 1 + packages/ui/src/dom.ts | 2 ++ packages/ui/src/render.test.ts | 33 +++++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/.changeset/dom-focus-selectors.md b/.changeset/dom-focus-selectors.md index 6a18ced..2395b8f 100644 --- a/.changeset/dom-focus-selectors.md +++ b/.changeset/dom-focus-selectors.md @@ -4,3 +4,4 @@ Add Element.matches() and :focus, :focus-within, and :focus-visible matching. Treat focused elements as focus-visible in the terminal. +Notify the renderer of the previous and next focused elements when focus changes. diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index eca1edb..b06e3b9 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -1174,6 +1174,8 @@ function transitionActiveElement(document: Document, to: Element | null): void { isTrusted: true, }); } + + document.notify([current, to].filter((element) => element !== null)); } /** internal helpers **/ diff --git a/packages/ui/src/render.test.ts b/packages/ui/src/render.test.ts index 424b153..cbfa0ee 100644 --- a/packages/ui/src/render.test.ts +++ b/packages/ui/src/render.test.ts @@ -28,6 +28,39 @@ describe('RenderApi', () => { expect(first.value).toEqual(new Set([text, branch, ...ancestors])); }); + test('invalidates both focus ancestry chains without scheduling frames for unchanged focus', async () => { + using fixture = setup(); + const { renderer, iterator } = fixture; + const document = createHTMLDocument((nodes) => renderer.request(nodes)); + const ancestors = [document.body!, document.documentElement!, document]; + const left = document.createElement('div'); + const right = document.createElement('div'); + const first = document.createElement('button'); + const second = document.createElement('button'); + document.body!.append(left, right); + left.appendChild(first); + right.appendChild(second); + await iterator.next(); + + first.focus(); + expect((await iterator.next()).value).toEqual(new Set([first, left, ...ancestors])); + + const moving = iterator.next(); + first.focus(); + second.blur(); + await expectPending(moving); + + second.focus(); + expect((await moving).value).toEqual(new Set([first, left, second, right, ...ancestors])); + + second.blur(); + expect((await iterator.next()).value).toEqual(new Set([second, right, ...ancestors])); + + const unchanged = iterator.next(); + second.blur(); + await expectPending(unchanged); + }); + test('invalidates both ancestor chains when an element moves and its old parent on removal', async () => { using fixture = setup(); const { renderer, iterator } = fixture; From 307dea447a1083709d28dcaae6751fa4c4db29dd Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Sat, 5 Dec 2026 21:24:13 -0600 Subject: [PATCH 4/4] Remove the custom focus rendering test --- packages/ui/src/render.test.ts | 33 --------------------------------- 1 file changed, 33 deletions(-) diff --git a/packages/ui/src/render.test.ts b/packages/ui/src/render.test.ts index cbfa0ee..424b153 100644 --- a/packages/ui/src/render.test.ts +++ b/packages/ui/src/render.test.ts @@ -28,39 +28,6 @@ describe('RenderApi', () => { expect(first.value).toEqual(new Set([text, branch, ...ancestors])); }); - test('invalidates both focus ancestry chains without scheduling frames for unchanged focus', async () => { - using fixture = setup(); - const { renderer, iterator } = fixture; - const document = createHTMLDocument((nodes) => renderer.request(nodes)); - const ancestors = [document.body!, document.documentElement!, document]; - const left = document.createElement('div'); - const right = document.createElement('div'); - const first = document.createElement('button'); - const second = document.createElement('button'); - document.body!.append(left, right); - left.appendChild(first); - right.appendChild(second); - await iterator.next(); - - first.focus(); - expect((await iterator.next()).value).toEqual(new Set([first, left, ...ancestors])); - - const moving = iterator.next(); - first.focus(); - second.blur(); - await expectPending(moving); - - second.focus(); - expect((await moving).value).toEqual(new Set([first, left, second, right, ...ancestors])); - - second.blur(); - expect((await iterator.next()).value).toEqual(new Set([second, right, ...ancestors])); - - const unchanged = iterator.next(); - second.blur(); - await expectPending(unchanged); - }); - test('invalidates both ancestor chains when an element moves and its old parent on removal', async () => { using fixture = setup(); const { renderer, iterator } = fixture;