From 04dde52b7c0a79d696f382dab9d09d9b4820f8ce Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Sun, 15 Nov 2026 16:30:09 -0600 Subject: [PATCH] Add initial Element.matches support with css-select --- packages/ui/package.json | 3 +- packages/ui/src/css-select.ts | 73 ++++++++++++++++++ packages/ui/src/dom.ts | 6 +- packages/ui/test/wpt.config.ts | 16 ++++ .../web-platform-tests/src/shared/registry.ts | 2 + .../child-indexed-pseudo-class.html.ts | 55 +++++++++++++ ...lement-matches-active-pseudo-class.html.ts | 38 +++++---- ...querySelector-invalid-comment-like.html.ts | 77 ++++++------------- pnpm-lock.yaml | 75 ++++++++++++++++++ 9 files changed, 269 insertions(+), 76 deletions(-) create mode 100644 packages/ui/src/css-select.ts create mode 100644 packages/web-platform-tests/src/wpt/css/selectors/child-indexed-pseudo-class.html.ts diff --git a/packages/ui/package.json b/packages/ui/package.json index a60b9d0..fa82b52 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -36,7 +36,8 @@ "test": "pnpm --filter @bomb.sh/web-platform-tests build && bsh test" }, "dependencies": { - "@bomb.sh/tty": "catalog:" + "@bomb.sh/tty": "catalog:", + "css-select": "^7.0.0" }, "devEngines": { "packageManager": { diff --git a/packages/ui/src/css-select.ts b/packages/ui/src/css-select.ts new file mode 100644 index 0000000..28fdad8 --- /dev/null +++ b/packages/ui/src/css-select.ts @@ -0,0 +1,73 @@ +import type { Options } from 'css-select'; +import { compile as compileSelector } from 'css-select'; +import { Element, Node } from './dom.ts'; + +export type Adapter = NonNullable['adapter']>; + +export const adapter: Adapter = { + isTag(node): node is Element { + return node instanceof Element; + }, + + getAttributeValue(element, name): string | undefined { + return element.getAttributeNS(null, name) ?? undefined; + }, + + getChildren(node): Node[] { + return [...node.childNodes]; + }, + + getName(element): string { + return element.localName; + }, + + getParent(node): Node | null { + return node.parentNode; + }, + + getSiblings(node): Node[] { + return node.parentNode ? [...node.parentNode.childNodes] : [node]; + }, + + getText(node): string { + const parts: string[] = []; + const stack = [node]; + while (stack.length > 0) { + const current = stack.pop()!; + if (current.nodeType === Node.TEXT_NODE) { + parts.push(current.nodeValue ?? ''); + } + for (let index = current.childNodes.length - 1; index >= 0; index--) { + stack.push(current.childNodes[index]!); + } + } + return parts.join(''); + }, + + hasAttrib(element, name): boolean { + return element.hasAttributeNS(null, name); + }, + + removeSubsets(nodes): Node[] { + const candidates = new Set(nodes); + return [...candidates].filter((node) => { + for (let parent = node.parentNode; parent; parent = parent.parentNode) { + if (candidates.has(parent)) { + return false; + } + } + return true; + }); + }, +}; + +export function compile(selector: string): (node: Node) => boolean { + try { + return compileSelector(selector, { adapter }); + } catch (error) { + throw new DOMException( + error instanceof Error ? error.message : 'Invalid selector', + 'SyntaxError', + ); + } +} diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 95493cb..bdf5a06 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -1,5 +1,5 @@ /* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */ - +import { compile } from './css-select.ts'; import { asciiUppercase, asciiLowercase } from './ascii.ts'; import { NamedNodeMap } from './named-node-map.ts'; import { HTMLCollection } from './html-collection.ts'; @@ -441,6 +441,10 @@ export class Element extends Node { return this.#attributes.toggleAttribute(name, force); } + matches(selector: string): boolean { + return compile(selector)(this); + } + get id(): string { return this.#attributes.getNamedItemNS(null, 'id')?.value ?? ''; } diff --git a/packages/ui/test/wpt.config.ts b/packages/ui/test/wpt.config.ts index 13e5088..38763a9 100644 --- a/packages/ui/test/wpt.config.ts +++ b/packages/ui/test/wpt.config.ts @@ -107,6 +107,22 @@ const config: WPTConfig = { 'dom/nodes/CharacterData-data.html': true, 'dom/nodes/CharacterData-remove.html': true, 'dom/nodes/Element-remove.html': true, + 'dom/nodes/Element-matches-namespaced-elements.html': [ + 'WPT Element-matches-namespaced-elements.html: empty string namespace, matches', + 'WPT Element-matches-namespaced-elements.html: has a namespace, matches', + ], + 'dom/nodes/Element-matches-active-pseudo-class.html': [ + 'WPT Element-matches-active-pseudo-class.html: Regular div should not match :active by default', + 'WPT Element-matches-active-pseudo-class.html: Button should not match :active by default', + 'WPT Element-matches-active-pseudo-class.html: Link should not match :active by default', + ], + 'dom/nodes/ParentNode-querySelector-invalid-comment-like.html': [ + 'WPT ParentNode-querySelector-invalid-comment-like.html: matches throws SyntaxError for comment-like selector', + ], + 'css/selectors/child-indexed-pseudo-class.html': [ + // Defer the four detached :nth-*(n) cases until https://github.com/fb55/css-select/issues/1945 is fixed. + /^Expected DIV element to (?!.*\(n\)).* with matches$/, + ], 'dom/nodes/Element-setAttribute.html': true, 'dom/nodes/Element-setAttributeNodeNS.html': true, 'dom/nodes/Element-removeAttribute.html': true, diff --git a/packages/web-platform-tests/src/shared/registry.ts b/packages/web-platform-tests/src/shared/registry.ts index 347da1c..2bc27ba 100644 --- a/packages/web-platform-tests/src/shared/registry.ts +++ b/packages/web-platform-tests/src/shared/registry.ts @@ -19,6 +19,7 @@ import { register as register_css_cssom_computed_style_set_property_html } from import { register as register_css_cssom_css_style_attr_decl_block_html } from '../wpt/css/cssom/css-style-attr-decl-block.html.ts'; import { register as register_css_cssom_css_style_attribute_modifications_html } from '../wpt/css/cssom/css-style-attribute-modifications.html.ts'; import { register as register_css_cssom_cssom_setProperty_shorthand_html } from '../wpt/css/cssom/cssom-setProperty-shorthand.html.ts'; +import { register as register_css_selectors_child_indexed_pseudo_class_html } from '../wpt/css/selectors/child-indexed-pseudo-class.html.ts'; import { register as register_css_selectors_focus_visible_001_html, input as input_css_selectors_focus_visible_001_html, @@ -477,6 +478,7 @@ export const registry = { 'css/cssom/css-style-attr-decl-block.html': { register: register_css_cssom_css_style_attr_decl_block_html }, 'css/cssom/css-style-attribute-modifications.html': { register: register_css_cssom_css_style_attribute_modifications_html }, 'css/cssom/cssom-setProperty-shorthand.html': { register: register_css_cssom_cssom_setProperty_shorthand_html }, + 'css/selectors/child-indexed-pseudo-class.html': { register: register_css_selectors_child_indexed_pseudo_class_html }, 'css/selectors/focus-visible-001.html': { register: register_css_selectors_focus_visible_001_html, input: input_css_selectors_focus_visible_001_html }, 'css/selectors/focus-visible-002.html': { register: register_css_selectors_focus_visible_002_html, input: input_css_selectors_focus_visible_002_html }, 'css/selectors/focus-visible-003.html': { register: register_css_selectors_focus_visible_003_html, input: input_css_selectors_focus_visible_003_html }, diff --git a/packages/web-platform-tests/src/wpt/css/selectors/child-indexed-pseudo-class.html.ts b/packages/web-platform-tests/src/wpt/css/selectors/child-indexed-pseudo-class.html.ts new file mode 100644 index 0000000..87f937d --- /dev/null +++ b/packages/web-platform-tests/src/wpt/css/selectors/child-indexed-pseudo-class.html.ts @@ -0,0 +1,55 @@ +import type { CompatibilityContext } from '../../../shared/context.ts'; + +// Upstream author: Emilio Cobos Álvarez . +export function register(context: CompatibilityContext): void { + const { expect } = context.runner; + const rootOfSubtreeSelectors = [ + [':first-child', true], + [':last-child', true], + [':only-child', true], + [':first-of-type', true], + [':last-of-type', true], + [':only-of-type', true], + [':nth-child(1)', true], + [':nth-child(n)', true], + [':nth-last-child(1)', true], + [':nth-last-child(n)', true], + [':nth-of-type(1)', true], + [':nth-of-type(n)', true], + [':nth-last-of-type(1)', true], + [':nth-last-of-type(n)', true], + [':nth-child(0)', false], + [':nth-child(2)', false], + [':nth-last-child(2)', false], + [':nth-of-type(2)', false], + [':nth-last-of-type(2)', false], + ] as const; + + for (const kind of ['document', 'detached', 'fragment'] as const) { + const tagName = kind === 'document' ? 'HTML' : 'DIV'; + const querySuffix = kind === 'detached' ? '' : ', querySelector(), and querySelectorAll()'; + for (const [selector, expected] of rootOfSubtreeSelectors) { + context.test( + `Expected ${tagName} element to ${expected ? 'match ' : 'not match '}${selector} with matches${querySuffix}`, + ({ document }) => { + const element = + kind === 'document' ? document.documentElement : document.createElement('div'); + let qsRoot: Document | DocumentFragment | undefined; + if (kind === 'document') { + qsRoot = document; + } else if (kind === 'fragment') { + qsRoot = document.createDocumentFragment(); + qsRoot.appendChild(element); + } + + expect(element.matches(selector)).toBe(expected); + if (qsRoot) { + expect(element === qsRoot.querySelector(selector)).toBe(expected); + const qsa = qsRoot.querySelectorAll(selector); + expect(!!qsa.length && element === qsa[0]).toBe(expected); + } + }, + ); + } + } +} diff --git a/packages/web-platform-tests/src/wpt/dom/nodes/Element-matches-active-pseudo-class.html.ts b/packages/web-platform-tests/src/wpt/dom/nodes/Element-matches-active-pseudo-class.html.ts index d135e84..2560bc1 100644 --- a/packages/web-platform-tests/src/wpt/dom/nodes/Element-matches-active-pseudo-class.html.ts +++ b/packages/web-platform-tests/src/wpt/dom/nodes/Element-matches-active-pseudo-class.html.ts @@ -1,36 +1,34 @@ -import type { CompatibilityContext, DOMFixture } from '../../../shared/context.ts'; +import type { CompatibilityContext } from '../../../shared/context.ts'; export function register(context: CompatibilityContext): void { - function html({ document, connect }: DOMFixture, markup: string): Document { - const container = document.createElement('div'); - container.innerHTML = markup; - for (const child of Array.from(container.children)) connect(child); - return document; - } - const { expect } = context.runner; + const content = ` +:active pseudo-class matching behavior + + + +
Test element
+ +Link element`; for (const [id, title] of [ ['test', 'Regular div should not match :active by default'], ['button', 'Button should not match :active by default'], ['link', 'Link should not match :active by default'], ] as const) { - context.test(`WPT Element-matches-active-pseudo-class.html: ${title}`, (fixture) => { - const document = html( - fixture, - '
Test element
\n\nLink element', - ); - expect(document.getElementById(id)!.matches(':active')).toBe(false); - }); + context.test( + `WPT Element-matches-active-pseudo-class.html: ${title}`, + ({ document }) => { + expect(document.getElementById(id)!.matches(':active')).toBe(false); + }, + { document: { contentType: 'text/html', content } }, + ); } context.test( 'WPT Element-matches-active-pseudo-class.html: No elements should match :active by default via querySelectorAll', - (fixture) => { - const document = html( - fixture, - '
Test element
\n\nLink element', - ); + ({ document }) => { expect(document.querySelectorAll(':active').length).toBe(0); }, + { document: { contentType: 'text/html', content } }, ); } diff --git a/packages/web-platform-tests/src/wpt/dom/nodes/ParentNode-querySelector-invalid-comment-like.html.ts b/packages/web-platform-tests/src/wpt/dom/nodes/ParentNode-querySelector-invalid-comment-like.html.ts index 173afe5..b306921 100644 --- a/packages/web-platform-tests/src/wpt/dom/nodes/ParentNode-querySelector-invalid-comment-like.html.ts +++ b/packages/web-platform-tests/src/wpt/dom/nodes/ParentNode-querySelector-invalid-comment-like.html.ts @@ -1,14 +1,23 @@ -import type { CompatibilityContext, DOMFixture } from '../../../shared/context.ts'; +import type { + CompatibilityContext, + CompatibilityTestOptions, + DOMFixture, +} from '../../../shared/context.ts'; export function register(context: CompatibilityContext): void { - function prepare({ document, connect }: DOMFixture, markup: string): Document { - const root = document.createElement('div'); - root.innerHTML = markup; - connect(root); - return document; - } - const { expect } = context.runner; + const options: CompatibilityTestOptions = { + document: { + contentType: 'text/html', + content: ` + +querySelector with invalid comment-like selector throws SyntaxError + +`, + }, + }; + const selector = + ' //MAIN MENU - (used to keep mobile menu options hidden) // #tncms-region-nav-main-nav-right-nav'; function syntaxError({ DOMException }: DOMFixture, operation: () => unknown): void { let caught: unknown; @@ -24,64 +33,24 @@ export function register(context: CompatibilityContext): void { context.test( 'WPT ParentNode-querySelector-invalid-comment-like.html: querySelector throws SyntaxError for comment-like selector', (fixture) => { - const document = prepare( - fixture, - '', - ); - - const selector = - ' //MAIN MENU - (used to keep mobile menu options hidden) // #tncms-region-nav-main-nav-right-nav'; - - syntaxError(fixture, () => document.querySelector(selector)!); + syntaxError(fixture, () => fixture.document.querySelector(selector)); }, + options, ); context.test( 'WPT ParentNode-querySelector-invalid-comment-like.html: querySelectorAll throws SyntaxError for comment-like selector', (fixture) => { - const document = prepare( - fixture, - '', - ); - - const selector = - ' //MAIN MENU - (used to keep mobile menu options hidden) // #tncms-region-nav-main-nav-right-nav'; - - syntaxError(fixture, () => document.querySelectorAll(selector)); + syntaxError(fixture, () => fixture.document.querySelectorAll(selector)); }, + options, ); context.test( 'WPT ParentNode-querySelector-invalid-comment-like.html: matches throws SyntaxError for comment-like selector', (fixture) => { - const document = prepare( - fixture, - '', - ); - - const selector = - ' //MAIN MENU - (used to keep mobile menu options hidden) // #tncms-region-nav-main-nav-right-nav'; - - syntaxError(fixture, () => document.body.matches(selector)); + syntaxError(fixture, () => fixture.document.body.matches(selector)); }, + options, ); - - // 4.3.7 from https://drafts.csswg.org/css-syntax/#consume-escaped-code-point - - // - escape hex digit - - // - hex digit special replacement - // 1. zero points - - // 2. surrogate points - - // 3. out of range points - - // - escape EOF - - // - escape anythong else - - // non edge cases - - // ident tests case from CSS tests of chromium source: https://goo.gl/3Cxdov } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7597c3f..1e40e46 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -44,6 +44,9 @@ importers: '@bomb.sh/tty': specifier: 'catalog:' version: 0.10.0 + css-select: + specifier: ^7.0.0 + version: 7.0.0 devDependencies: '@bomb.sh/web-platform-tests': specifier: workspace:* @@ -1272,6 +1275,10 @@ packages: axios@1.21.0: resolution: {integrity: sha512-YCzXMB53Q9PZBsh7yN7wtapit4WepwcHS2fP8QhGsBxSz5YtgYobV7GGlWlAJi+RxfU77GQTQi2DSLUma42EYA==} + boolbase@2.0.0: + resolution: {integrity: sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==} + engines: {node: '>=20.19.0'} + cac@7.1.0: resolution: {integrity: sha512-LMDU/U2yA4IPIY8KT0NsNPWEYZvAMkbgyspxJ6btJaYV+WMDOHAZCmB0lsTObiHaRS1V/ztKAl7+TSkTqXyeoA==} engines: {node: '>=20.19.0'} @@ -1291,6 +1298,14 @@ packages: convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + css-select@7.0.0: + resolution: {integrity: sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==} + engines: {node: '>=20.19.0'} + + css-what@8.0.0: + resolution: {integrity: sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==} + engines: {node: '>=20.19.0'} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -1311,6 +1326,22 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + dom-serializer@3.1.1: + resolution: {integrity: sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==} + engines: {node: '>=20.19.0'} + + domelementtype@3.0.0: + resolution: {integrity: sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==} + engines: {node: '>=20.19.0'} + + domhandler@6.0.1: + resolution: {integrity: sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==} + engines: {node: '>=20.19.0'} + + domutils@4.0.2: + resolution: {integrity: sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==} + engines: {node: '>=20.19.0'} + dts-resolver@3.0.0: resolution: {integrity: sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q==} engines: {node: ^22.18.0 || >=24.0.0} @@ -1328,6 +1359,10 @@ packages: resolution: {integrity: sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==} engines: {node: '>=14'} + entities@8.1.0: + resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==} + engines: {node: '>=20.19.0'} + entities@9.0.0: resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} engines: {node: '>=20.19.0'} @@ -1585,6 +1620,10 @@ packages: node-pty@1.2.0-beta.15: resolution: {integrity: sha512-vORSzHXi4Ofl7HemVWpuudLqCPdaQb4LfpRCUpE5HPxhp4JYscl8zZwxh11p26v2wvW24WMwnMfLjhRLixrfxA==} + nth-check@3.0.1: + resolution: {integrity: sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==} + engines: {node: '>=20.19.0'} + obug@3.0.0: resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} @@ -2855,6 +2894,8 @@ snapshots: - debug - supports-color + boolbase@2.0.0: {} + cac@7.1.0: {} call-bind-apply-helpers@1.0.2: @@ -2870,6 +2911,16 @@ snapshots: convert-source-map@2.0.0: {} + css-select@7.0.0: + dependencies: + boolbase: 2.0.0 + css-what: 8.0.0 + domhandler: 6.0.1 + domutils: 4.0.2 + nth-check: 3.0.1 + + css-what@8.0.0: {} + debug@4.4.3: dependencies: ms: 2.1.3 @@ -2880,6 +2931,24 @@ snapshots: detect-libc@2.1.2: {} + dom-serializer@3.1.1: + dependencies: + domelementtype: 3.0.0 + domhandler: 6.0.1 + entities: 8.1.0 + + domelementtype@3.0.0: {} + + domhandler@6.0.1: + dependencies: + domelementtype: 3.0.0 + + domutils@4.0.2: + dependencies: + dom-serializer: 3.1.1 + domelementtype: 3.0.0 + domhandler: 6.0.1 + dts-resolver@3.0.0(oxc-resolver@11.20.0): optionalDependencies: oxc-resolver: 11.20.0 @@ -2892,6 +2961,8 @@ snapshots: empathic@2.1.0: {} + entities@8.1.0: {} + entities@9.0.0: {} es-define-property@1.0.1: {} @@ -3115,6 +3186,10 @@ snapshots: dependencies: node-addon-api: 7.1.1 + nth-check@3.0.1: + dependencies: + boolbase: 2.0.0 + obug@3.0.0: {} oxc-parser@0.133.0: