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
3 changes: 2 additions & 1 deletion packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
73 changes: 73 additions & 0 deletions packages/ui/src/css-select.ts
Original file line number Diff line number Diff line change
@@ -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<Options<Node, Element>['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',
);
}
}
6 changes: 5 additions & 1 deletion packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 ?? '';
}
Expand Down
16 changes: 16 additions & 0 deletions packages/ui/test/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions packages/web-platform-tests/src/shared/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 },
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { CompatibilityContext } from '../../../shared/context.ts';

// Upstream author: Emilio Cobos Álvarez <ecoal95@gmail.com>.
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);
}
},
);
}
}
}
Original file line number Diff line number Diff line change
@@ -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 = `<!DOCTYPE html>
<title>:active pseudo-class matching behavior</title>
<meta charset="utf-8">
<!-- Regression test for https://github.com/jsdom/jsdom/issues/3610 -->

<div id="test">Test element</div>
<button id="button">Button element</button>
<a id="link" href="#">Link element</a>`;

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,
'<div id="test">Test element</div>\n<button id="button">Button element</button>\n<a id="link" href="#">Link element</a>',
);
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,
'<div id="test">Test element</div>\n<button id="button">Button element</button>\n<a id="link" href="#">Link element</a>',
);
({ document }) => {
expect(document.querySelectorAll(':active').length).toBe(0);
},
{ document: { contentType: 'text/html', content } },
);
}
Original file line number Diff line number Diff line change
@@ -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: `<!DOCTYPE html>
<meta charset="utf-8">
<title>querySelector with invalid comment-like selector throws SyntaxError</title>
<!-- Regression test for https://github.com/jsdom/jsdom/issues/1214 -->
<body>`,
},
};
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;
Expand All @@ -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,
'<!-- Regression test for https://github.com/jsdom/jsdom/issues/1214 -->',
);

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,
'<!-- Regression test for https://github.com/jsdom/jsdom/issues/1214 -->',
);

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,
'<!-- Regression test for https://github.com/jsdom/jsdom/issues/1214 -->',
);

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
}
Loading
Loading