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
12 changes: 11 additions & 1 deletion packages/ui/src/css-select.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Options } from 'css-select';
import { compile as compileSelector } from 'css-select';
import { compile as compileSelector, selectAll, selectOne } from 'css-select';
import { Element, Node } from './dom.ts';

export type Adapter = NonNullable<Options<Node, Element>['adapter']>;
Expand Down Expand Up @@ -71,3 +71,13 @@ export function compile(selector: string): (node: Node) => boolean {
);
}
}

export function querySelector(nodes: Node[], selector: string): Element | null {
const query = compile(selector);
return selectOne(query, nodes, { adapter });
}

export function querySelectorAll(nodes: Node[], selector: string): Element[] {
const query = compile(selector);
return selectAll(query, nodes, { adapter });
}
19 changes: 18 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 { compile, 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 All @@ -9,6 +9,7 @@ import {
validateAttributeName,
validateAttributeNamespace,
} from './validation.ts';
import { NodeList } from './node-list.ts';

const HTML_NS = 'http://www.w3.org/1999/xhtml';

Expand Down Expand Up @@ -82,6 +83,14 @@ export class Document {
return null;
}

querySelector(selector: string): Element | null {
return querySelector([this.documentElement], selector);
}

querySelectorAll(selector: string): NodeList {
return new NodeList(querySelectorAll([this.documentElement], selector));
}

createElement(tagName: string): Element {
if (arguments.length === 0) {
throw new TypeError('createElement requires a tag name');
Expand Down Expand Up @@ -445,6 +454,14 @@ export class Element extends Node {
return compile(selector)(this);
}

querySelector(selector: string): Element | null {
return querySelector(Array.from(this.childNodes), selector);
}

querySelectorAll(selector: string): NodeList {
return new NodeList(querySelectorAll(Array.from(this.childNodes), selector));
}

get id(): string {
return this.#attributes.getNamedItemNS(null, 'id')?.value ?? '';
}
Expand Down
59 changes: 59 additions & 0 deletions packages/ui/src/node-list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */
import type { Element } from './dom.ts';

/**
* A static snapshot of nodes, as returned by querySelectorAll.
* Full Web IDL indexed-property deletion and redefinition are not supported.
*/
export class NodeList implements Iterable<Element> {
readonly [index: number]: Element;
#elements: Element[];

constructor(nodes: Element[]) {
this.#elements = nodes;
for (const [index, node] of nodes.entries()) {
Object.defineProperty(this, index, {
value: node,
writable: false,
enumerable: true,
configurable: true,
});
}
}

get length(): number {
return this.#elements.length;
}

item(index: number): Element | null {
if (arguments.length === 0) {
throw new TypeError('item requires an index');
}
return this.#elements[index >>> 0] ?? null;
}

keys(): ArrayIterator<number> {
return this.#elements.keys();
}

values(): ArrayIterator<Element> {
return this.#elements.values();
}

entries(): ArrayIterator<[number, Element]> {
return this.#elements.entries();
}

forEach(
callback: (value: Element, index: number, list: NodeList) => void,
thisArg?: unknown,
): void {
this.#elements.forEach((element, index) => {
callback.call(thisArg, element, index, this);
});
}

[Symbol.iterator](): ArrayIterator<Element> {
return this.#elements[Symbol.iterator]();
}
}
71 changes: 64 additions & 7 deletions packages/ui/test/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,74 @@ const config: WPTConfig = {
'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/Element-matches-active-pseudo-class.html': true,
'dom/nodes/Element-querySelectorAll-context-element.html': true,
'dom/nodes/ParentNode-querySelector-All-comma-selector.html': true,
'dom/nodes/ParentNode-querySelector-escapes.html': [
'WPT ParentNode-querySelector-escapes.html: "nonescaped" should match with "#nonescaped"',
'WPT ParentNode-querySelector-escapes.html: "0nextIsWhiteSpace" should match with "#\\\\30 nextIsWhiteSpace"',
'WPT ParentNode-querySelector-escapes.html: "0nextIsNotHexLetters" should match with "#\\\\30nextIsNotHexLetters"',
'WPT ParentNode-querySelector-escapes.html: "0connectHexMoreThan6Hex" should match with "#\\\\000030connectHexMoreThan6Hex"',
'WPT ParentNode-querySelector-escapes.html: "0spaceMoreThan6Hex" should match with "#\\\\000030 spaceMoreThan6Hex"',
'WPT ParentNode-querySelector-escapes.html: "outOfRange0" should never match with "#outOfRange\\\\110030"',
'WPT ParentNode-querySelector-escapes.html: ".comma" should match with "#\\\\.comma"',
'WPT ParentNode-querySelector-escapes.html: "-minus" should match with "#\\\\-minus"',
'WPT ParentNode-querySelector-escapes.html: "g" should match with "#\\\\g"',
'WPT ParentNode-querySelector-escapes.html: "aBMPRegular" should match with "#\\\\61 BMPRegular"',
'WPT ParentNode-querySelector-escapes.html: "\ud83d\udd11nonBMP" should match with "#\\\\1f511 nonBMP"',
'WPT ParentNode-querySelector-escapes.html: "00continueEscapes" should match with "#\\\\30\\\\30 continueEscapes"',
'WPT ParentNode-querySelector-escapes.html: "00continueEscapes" should match with "#\\\\30 \\\\30 continueEscapes"',
'WPT ParentNode-querySelector-escapes.html: "continueEscapes00" should match with "#continueEscapes\\\\30 \\\\30 "',
'WPT ParentNode-querySelector-escapes.html: "continueEscapes00" should match with "#continueEscapes\\\\30 \\\\30"',
'WPT ParentNode-querySelector-escapes.html: "continueEscapes00" should match with "#continueEscapes\\\\30\\\\30 "',
'WPT ParentNode-querySelector-escapes.html: "continueEscapes00" should match with "#continueEscapes\\\\30\\\\30"',
'WPT ParentNode-querySelector-escapes.html: "hello" should match with "#hel\\\\6Co"',
'WPT ParentNode-querySelector-escapes.html: "&B" should match with "#\\\\26 B"',
'WPT ParentNode-querySelector-escapes.html: "spaces" should match with "#sp\\\\61\\tc\\\\65\\fs"',
'WPT ParentNode-querySelector-escapes.html: "test\ud799" should match with "#test\\\\D799"',
'WPT ParentNode-querySelector-escapes.html: "\ue000" should match with "#\\\\E000"',
'WPT ParentNode-querySelector-escapes.html: "test" should match with "#te\\\\s\\\\t"',
'WPT ParentNode-querySelector-escapes.html: "spaces in\\tident" should match with "#spaces\\\\ in\\\\\\tident"',
'WPT ParentNode-querySelector-escapes.html: ".,:!" should match with "#\\\\.\\\\,\\\\:\\\\!"',
'WPT ParentNode-querySelector-escapes.html: "\udbff\udfff" should match with "#\\\\10fFfF"',
'WPT ParentNode-querySelector-escapes.html: "\udbff\udfff0" should match with "#\\\\10fFfF0"',
'WPT ParentNode-querySelector-escapes.html: "\udbc0\udc0000" should match with "#\\\\10000000"',
'WPT ParentNode-querySelector-escapes.html: "simple-ident" should match with "#simple-ident"',
'WPT ParentNode-querySelector-escapes.html: "testing123" should match with "#testing123"',
'WPT ParentNode-querySelector-escapes.html: "_underscore" should match with "#_underscore"',
'WPT ParentNode-querySelector-escapes.html: "-text" should match with "#-text"',
'WPT ParentNode-querySelector-escapes.html: "-m" should match with "#-\\\\6d"',
'WPT ParentNode-querySelector-escapes.html: "--abc" should match with "#--abc"',
'WPT ParentNode-querySelector-escapes.html: "--" should match with "#--"',
'WPT ParentNode-querySelector-escapes.html: "--11" should match with "#--11"',
'WPT ParentNode-querySelector-escapes.html: "---" should match with "#---"',
'WPT ParentNode-querySelector-escapes.html: "\u2003" should match with "#\u2003"',
'WPT ParentNode-querySelector-escapes.html: "\u1234" should match with "#\u1234"',
'WPT ParentNode-querySelector-escapes.html: "\ud808\udf45" should match with "#\ud808\udf45"',
// Remaining cases expose escape parsing and invalid code point handling gaps.
],
'dom/nodes/ParentNode-querySelector-invalid-comment-like.html': [
'WPT ParentNode-querySelector-invalid-comment-like.html: matches throws SyntaxError for comment-like selector',
'dom/nodes/ParentNode-querySelector-invalid-comment-like.html': true,
'dom/nodes/ParentNode-querySelector-nested.html': true,
'dom/nodes/ParentNode-querySelector-orphan-scope.html': true,
'dom/nodes/ParentNode-querySelector-tag-case.html': [
'WPT ParentNode-querySelector-tag-case.html: Tag name case-insensitivity with child combinator (>) dynamically created',
],
'dom/nodes/ParentNode-querySelectorAll-not-descendant.html': true,
'dom/nodes/NodeList-Iterable.html': [
'NodeList has length method.',
'NodeList has values method.',
'NodeList has entries method.',
'NodeList has forEach method.',
'NodeList has Symbol.iterator.',
'NodeList is iterable via for-of loop.',
'NodeList responds to Object.keys correctly',
// The remaining case exercises live childNodes rather than querySelectorAll results.
],
'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.
// Defer :nth-*(n) cases for detached elements and the document root until
// https://github.com/fb55/css-select/issues/1945 is fixed.
/^Expected DIV element to (?!.*\(n\)).* with matches$/,
/^Expected HTML element to (?!.*\(n\)).* with matches, querySelector\(\), and querySelectorAll\(\)$/,
],
'dom/nodes/Element-setAttribute.html': true,
'dom/nodes/Element-setAttributeNodeNS.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 @@ -144,6 +144,7 @@ import { register as register_dom_nodes_Node_parentNode_html } from '../wpt/dom/
import { register as register_dom_nodes_Node_removeChild_html } from '../wpt/dom/nodes/Node-removeChild.html.ts';
import { register as register_dom_nodes_Node_replaceChild_html } from '../wpt/dom/nodes/Node-replaceChild.html.ts';
import { register as register_dom_nodes_Node_textContent_html } from '../wpt/dom/nodes/Node-textContent.html.ts';
import { register as register_dom_nodes_NodeList_Iterable_html } from '../wpt/dom/nodes/NodeList-Iterable.html.ts';
import { register as register_dom_nodes_ParentNode_append_html } from '../wpt/dom/nodes/ParentNode-append.html.ts';
import { register as register_dom_nodes_ParentNode_children_html } from '../wpt/dom/nodes/ParentNode-children.html.ts';
import { register as register_dom_nodes_ParentNode_prepend_html } from '../wpt/dom/nodes/ParentNode-prepend.html.ts';
Expand Down Expand Up @@ -591,6 +592,7 @@ export const registry = {
'dom/nodes/Node-removeChild.html': { register: register_dom_nodes_Node_removeChild_html },
'dom/nodes/Node-replaceChild.html': { register: register_dom_nodes_Node_replaceChild_html },
'dom/nodes/Node-textContent.html': { register: register_dom_nodes_Node_textContent_html },
'dom/nodes/NodeList-Iterable.html': { register: register_dom_nodes_NodeList_Iterable_html },
'dom/nodes/ParentNode-append.html': { register: register_dom_nodes_ParentNode_append_html },
'dom/nodes/ParentNode-children.html': { register: register_dom_nodes_ParentNode_children_html },
'dom/nodes/ParentNode-prepend.html': { register: register_dom_nodes_ParentNode_prepend_html },
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,40 @@
import type { CompatibilityContext, DOMFixture } from '../../../shared/context.ts';
import type { CompatibilityContext } from '../../../shared/context.ts';

export function register(context: CompatibilityContext): void {
function title(source: string, name: string): string {
return `WPT ${source}: ${name}`;
}
function mount({ document, connect }: DOMFixture, markup: string): HTMLElement {
const container = document.createElement('main');
container.innerHTML = markup;
connect(container);
return container;
}

const { expect } = context.runner;
const content = `<!DOCTYPE html>
<meta charset="utf-8">
<title>element.querySelectorAll() with the context element in the selector</title>
<link rel="help" href="https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall">
<!-- Regression test for https://github.com/jsdom/jsdom/issues/4227 -->

<div id="test-container">
<div class="root" id="root">
<table>
<tbody>
<tr id="row"></tr>
</tbody>
</table>
</div>
</div>`;

for (const [name, selector, fromDocument] of [
['Query from document', '.root table tbody tr', true],
['Query without root class', 'table tbody tr', false],
['Query with root class', '.root table tbody tr', false],
] as const) {
context.test(title('Element-querySelectorAll-context-element.html', name), (fixture) => {
const { document } = fixture;
const container = mount(
fixture,
'<div id="test-container"><div class="root" id="root"><table><tbody><tr id="row"></tr></tbody></table></div></div>',
);
const root = container.firstElementChild!.firstElementChild!;
const target = root.firstElementChild!.firstElementChild!.firstElementChild!;
expect(Array.from((fromDocument ? document : root).querySelectorAll(selector))).toEqual([
target,
]);
});
context.test(
`WPT Element-querySelectorAll-context-element.html: ${name}`,
({ document }) => {
const root = document.getElementById('root')!;
const target = document.getElementById('row')!;
const result = (fromDocument ? document : root).querySelectorAll(selector);
// Upstream assert_array_equals checks own indices and node identity.
expect(result.length).toBe(1);
expect(Object.hasOwn(result, 0)).toBe(true);
expect(result[0]).toBe(target);
},
{ document: { contentType: 'text/html', content } },
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import type { CompatibilityContext } from '../../../shared/context.ts';

export function register(context: CompatibilityContext): void {
const { expect } = context.runner;
const content = `<!doctype html>
<meta charset="utf-8">
<title>NodeList Iterable Test</title>
<p id="1"></p>
<p id="2"></p>
<p id="3"></p>
<p id="4"></p>
<p id="5"></p>

<div id="live"><b id="b1">1</b><b id="b2">2</b><b id="b3">3</b></div>`;

context.test(
'NodeList has length method.',
({ document }) => {
const paragraphs = document.querySelectorAll('p');
expect('length' in paragraphs).toBe(true);
},
{ document: { contentType: 'text/html', content } },
);
context.test(
'NodeList has values method.',
({ document }) => {
const paragraphs = document.querySelectorAll('p');
expect('values' in paragraphs).toBe(true);
},
{ document: { contentType: 'text/html', content } },
);
context.test(
'NodeList has entries method.',
({ document }) => {
const paragraphs = document.querySelectorAll('p');
expect('entries' in paragraphs).toBe(true);
},
{ document: { contentType: 'text/html', content } },
);
context.test(
'NodeList has forEach method.',
({ document }) => {
const paragraphs = document.querySelectorAll('p');
expect('forEach' in paragraphs).toBe(true);
},
{ document: { contentType: 'text/html', content } },
);
context.test(
'NodeList has Symbol.iterator.',
({ document }) => {
const paragraphs = document.querySelectorAll('p');
expect(Symbol.iterator in paragraphs).toBe(true);
},
{ document: { contentType: 'text/html', content } },
);
context.test(
'NodeList is iterable via for-of loop.',
({ document }) => {
const paragraphs = document.querySelectorAll('p');
const ids = '12345';
let idx = 0;
for (const node of paragraphs) {
expect(node.getAttribute('id')).toBe(ids[idx++]);
}
},
{ document: { contentType: 'text/html', content } },
);
context.test(
'NodeList responds to Object.keys correctly',
({ document }) => {
const paragraphs = document.querySelectorAll('p');
expect(Object.keys(paragraphs)).toEqual(['0', '1', '2', '3', '4']);
},
{ document: { contentType: 'text/html', content } },
);
context.test(
'live NodeLists are for-of iterable and update appropriately',
({ document }) => {
const container = document.getElementById('live')!;
const nodeList = container.childNodes as NodeListOf<HTMLElement>;
const ids = [];
for (const el of nodeList) {
ids.push(el.id);
expect(el.localName).toBe('b');
if (ids.length < 3) {
const newEl = document.createElement('b');
newEl.id = 'after' + el.id;
container.appendChild(newEl);
}
}
expect(ids).toEqual(['b1', 'b2', 'b3', 'afterb1', 'afterb2']);
},
{ document: { contentType: 'text/html', content } },
);
}
Loading
Loading