Skip to content

Commit 6c77904

Browse files
committed
Support shared DOM lookup and live collections
1 parent 8ce47b6 commit 6c77904

5 files changed

Lines changed: 211 additions & 4 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clack/ui': patch
3+
---
4+
5+
Add document ID lookup in tree order and live tag-name collections with indexed own properties, covered by original upstream Web Platform Tests.

‎packages/ui/src/css-select.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,17 @@ export function compile(selector: string): (node: Node) => boolean {
7272
}
7373
}
7474

75+
export function findElement(
76+
nodes: Node[],
77+
predicate: (element: Element) => boolean,
78+
): Element | null {
79+
return selectOne(predicate, nodes, { adapter, xmlMode: true });
80+
}
81+
82+
export function findElements(nodes: Node[], predicate: (element: Element) => boolean): Element[] {
83+
return selectAll(predicate, nodes, { adapter, xmlMode: true });
84+
}
85+
7586
export function querySelector(nodes: Node[], selector: string): Element | null {
7687
const query = compile(selector);
7788
return selectOne(query, nodes, { adapter });

‎packages/ui/src/dom.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
/* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */
22

3-
import { querySelector } from './css-select.ts';
3+
import { findElement, findElements, querySelector } from './css-select.ts';
44
import { asciiUppercase, asciiLowercase } from './ascii.ts';
55
import { NamedNodeMap } from './named-node-map.ts';
6+
import { HTMLCollection } from './html-collection.ts';
67
import {
78
validateElementName,
89
validateElementNamespace,
@@ -325,6 +326,36 @@ export class Document extends Node {
325326
return querySelector(Array.from(this.childNodes), selector);
326327
}
327328

329+
getElementsByTagName(qualifiedName: string): HTMLCollection {
330+
if (arguments.length === 0) {
331+
throw new TypeError('getElementsByTagName requires a qualified name');
332+
}
333+
const name = `${qualifiedName}`;
334+
const lowerName = asciiLowercase(name);
335+
return new HTMLCollection(() =>
336+
findElements(Array.from(this.childNodes), (element) => {
337+
const elementName =
338+
element.prefix === null ? element.localName : `${element.prefix}:${element.localName}`;
339+
return (
340+
name === '*' ||
341+
elementName ===
342+
(this instanceof HTMLDocument && element.namespaceURI === HTML_NS ? lowerName : name)
343+
);
344+
}),
345+
);
346+
}
347+
348+
getElementById(id: string): Element | null {
349+
if (arguments.length === 0) {
350+
throw new TypeError('getElementById requires an ID');
351+
}
352+
const name = `${id}`;
353+
if (name === '') {
354+
return null;
355+
}
356+
return findElement(Array.from(this.childNodes), (element) => element.id === name);
357+
}
358+
328359
createElement(tagName: string): Element {
329360
if (arguments.length === 0) {
330361
throw new TypeError('createElement requires a tag name');
@@ -765,6 +796,7 @@ export class HTMLDocument extends Document {
765796
['title', HTMLTitleElement],
766797
['body', HTMLBodyElement],
767798
['span', HTMLSpanElement],
799+
['div', HTMLDivElement],
768800
]);
769801
constructor(notify: Node['notify']) {
770802
super(notify, (owner, localName, notifyElement, namespace) => {
@@ -811,6 +843,8 @@ export class HTMLBodyElement extends HTMLElement {}
811843

812844
export class HTMLSpanElement extends HTMLElement {}
813845

846+
export class HTMLDivElement extends HTMLElement {}
847+
814848
export class HTMLUnknownElement extends HTMLElement {}
815849

816850
/** XML */

‎packages/ui/src/html-collection.ts‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import type { Element } from './dom.ts';
2+
3+
const sources = new WeakMap<HTMLCollection, () => Element[]>();
4+
5+
export class HTMLCollection implements Iterable<Element> {
6+
readonly [index: number]: Element;
7+
8+
constructor(elements: () => Element[]) {
9+
sources.set(this, elements);
10+
const collection = new Proxy(this, {
11+
get(target, key, receiver) {
12+
if (isArrayIndex(key)) {
13+
return elements()[Number(key)] ?? Reflect.get(target, key, receiver);
14+
}
15+
if (typeof key === 'string' && !(key in target)) {
16+
return namedElement(elements(), key) ?? undefined;
17+
}
18+
return Reflect.get(target, key, receiver);
19+
},
20+
has(target, key) {
21+
if (isArrayIndex(key) && Number(key) < elements().length) {
22+
return true;
23+
}
24+
return Reflect.has(target, key);
25+
},
26+
getOwnPropertyDescriptor(target, key) {
27+
if (isArrayIndex(key)) {
28+
const element = elements()[Number(key)];
29+
if (element !== undefined) {
30+
return { value: element, writable: false, enumerable: true, configurable: true };
31+
}
32+
}
33+
return Reflect.getOwnPropertyDescriptor(target, key);
34+
},
35+
ownKeys(target) {
36+
const indices = elements().map((_, index) => `${index}`);
37+
return [...indices, ...Reflect.ownKeys(target)];
38+
},
39+
set(target, key, value, receiver) {
40+
if (isArrayIndex(key) && Number(key) < elements().length) {
41+
return false;
42+
}
43+
return Reflect.set(target, key, value, receiver);
44+
},
45+
defineProperty(target, key, descriptor) {
46+
if (isArrayIndex(key)) {
47+
return false;
48+
}
49+
return Reflect.defineProperty(target, key, descriptor);
50+
},
51+
deleteProperty(target, key) {
52+
if (isArrayIndex(key)) {
53+
return Number(key) >= elements().length;
54+
}
55+
return Reflect.deleteProperty(target, key);
56+
},
57+
preventExtensions() {
58+
// Live indices must remain able to appear and disappear.
59+
return false;
60+
},
61+
});
62+
sources.set(collection, elements);
63+
return collection;
64+
}
65+
66+
get length(): number {
67+
return sources.get(this)!().length;
68+
}
69+
70+
item(index: number): Element | null {
71+
return sources.get(this)!()[index >>> 0] ?? null;
72+
}
73+
74+
namedItem(name: string): Element | null {
75+
const key = `${name}`;
76+
return namedElement(sources.get(this)!(), key);
77+
}
78+
79+
*[Symbol.iterator](): IterableIterator<Element> {
80+
for (let index = 0; index < this.length; index++) {
81+
yield this.item(index)!;
82+
}
83+
}
84+
}
85+
86+
function isArrayIndex(key: PropertyKey): key is string {
87+
return typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key) && Number(key) < 2 ** 32 - 1;
88+
}
89+
90+
function namedElement(elements: Element[], name: string): Element | null {
91+
if (name === '') {
92+
return null;
93+
}
94+
return (
95+
elements.find(
96+
(element) =>
97+
element.id === name ||
98+
(element.namespaceURI === 'http://www.w3.org/1999/xhtml' &&
99+
element.getAttribute('name') === name),
100+
) ?? null
101+
);
102+
}

‎packages/ui/wpt.config.ts‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
DocumentType,
1010
Element,
1111
HTMLBodyElement,
12+
HTMLDivElement,
1213
HTMLElement,
1314
HTMLHeadElement,
1415
HTMLHtmlElement,
@@ -20,6 +21,7 @@ import {
2021
XMLDocument,
2122
} from './src/dom.ts';
2223
import { NamedNodeMap } from './src/named-node-map.ts';
24+
import { HTMLCollection } from './src/html-collection.ts';
2325

2426
const config: WPTConfig = {
2527
createDocument: () => createHTMLDocument(() => {}),
@@ -37,6 +39,8 @@ const config: WPTConfig = {
3739
Event: globalThis.Event,
3840
EventTarget: globalThis.EventTarget,
3941
HTMLBodyElement,
42+
HTMLDivElement,
43+
HTMLCollection,
4044
HTMLElement,
4145
HTMLHeadElement,
4246
HTMLHtmlElement,
@@ -49,6 +53,14 @@ const config: WPTConfig = {
4953
XMLDocument,
5054
},
5155
include: {
56+
'html/dom/elements/global-attributes/id-name.html': true,
57+
'html/dom/elements/global-attributes/id-attribute.html': [
58+
'After setting id via id attribute, getElementById find the element by the new id.',
59+
"After setting id via id attribute, getElementById doesn't find the element by the old id.",
60+
'After setting id via setAttribute attribute, getElementById find the element by the new id.',
61+
"After setting id via setAttribute attribute, getElementById doesn't find the element by the old id.",
62+
// Preserve the existing ID selection; CSS association requires getComputedStyle().
63+
],
5264
'dom/events/Event-constructors.any.js': true,
5365
'dom/events/EventTarget-addEventListener.any.js': true,
5466
'dom/events/EventTarget-add-remove-listener.any.js': true,
@@ -62,6 +74,51 @@ const config: WPTConfig = {
6274
// Native EventTarget reads handleEvent at registration; the getter-timing
6375
// case remains excluded until that behavior is implemented.
6476
],
77+
'dom/collections/HTMLCollection-iterator.html': true,
78+
'dom/collections/HTMLCollection-supported-property-indices.html': true,
79+
'dom/collections/HTMLCollection-supported-property-names.html': [
80+
'Object.getOwnPropertyNames on HTMLCollection with non-HTML namespace',
81+
'Object.getOwnPropertyNames on HTMLCollection with expando object',
82+
'Trying to set an expando that shadows a named property that gets added later',
83+
'Trying to set a non-configurable expando that shadows a named property that gets added later',
84+
// The other cases require named own properties and their descriptors.
85+
],
86+
'dom/nodes/Document-getElementById.html': [
87+
'Calling document.getElementById with an empty string argument.',
88+
'Calling document.getElementById with a null argument.',
89+
'Calling document.getElementById with an undefined argument.',
90+
'on static page',
91+
'Document.getElementById with a script-inserted element',
92+
'update `id` attribute via setAttribute/removeAttribute',
93+
'Ensure that the id attribute only affects elements present in a document',
94+
"in tree order, within the context object's tree",
95+
'Modern browsers optimize this method with using internal id cache. This test checks that their optimization should effect only append to `Document`, not append to `Node`.',
96+
"changing attribute's value via `Attr` gotten from `Element.attribute`.",
97+
'update `id` attribute via element.id',
98+
"where insertion order and tree order don't match",
99+
'Inserting an id by inserting its parent node',
100+
'Document.getElementById must not return nodes not present in document',
101+
// Four other cases require innerHTML or outerHTML mutation.
102+
],
103+
'html/dom/documents/dom-tree-accessors/Document.body.html': ["existing document's body"],
104+
'dom/nodes/Document-getElementsByTagName.html': [
105+
'Caching is allowed',
106+
"Shouldn't be able to set unsigned properties on a HTMLCollection (non-strict mode)",
107+
"Shouldn't be able to set unsigned properties on a HTMLCollection (strict mode)",
108+
'Should be able to set expando shadowing a proto prop (item)',
109+
'Should be able to set expando shadowing a proto prop (namedItem)',
110+
'HTML element with uppercase tagName never matches in HTML Documents',
111+
'Element in non-HTML namespace, no prefix, lowercase name',
112+
'Element in non-HTML namespace, no prefix, uppercase name',
113+
'Element in non-HTML namespace, prefix, lowercase name',
114+
'Element in non-HTML namespace, prefix, uppercase name',
115+
'Element in HTML namespace, no prefix, non-ascii characters in name',
116+
'Element in non-HTML namespace, non-ascii characters in name',
117+
'Element in HTML namespace, prefix, non-ascii characters in name',
118+
'Element in non-HTML namespace, prefix, non-ascii characters in name',
119+
'getElementsByTagName() should be a live collection',
120+
// Preserve the existing selection; interface and named own-property coverage remains deferred.
121+
],
65122
'dom/nodes/Document-createTextNode.html': true,
66123
'dom/nodes/Document-createElement.html': [/^createElement\(.*\) in HTML document$/],
67124
'dom/nodes/Document-createElementNS.html': [
@@ -98,9 +155,7 @@ const config: WPTConfig = {
98155
'dom/nodes/Element-removeAttribute.html': true,
99156
'dom/nodes/Element-removeAttributeNS.html': true,
100157
'dom/nodes/Element-setAttribute-crbug-1138487.html': true,
101-
'dom/nodes/Element-hasAttribute.html': [
102-
'hasAttribute should check for attribute presence, irrespective of namespace',
103-
],
158+
'dom/nodes/Element-hasAttribute.html': true,
104159
'dom/nodes/attributes-namednodemap.html': true,
105160
'dom/nodes/attributes.html': [
106161
'Attribute loses its owner when removed',

0 commit comments

Comments
 (0)