Skip to content

Commit 2e1197b

Browse files
committed
Support document ID lookup with parsed WPT fixtures
1 parent 5b94813 commit 2e1197b

19 files changed

Lines changed: 1308 additions & 22 deletions
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+
Initialize an HTML document root and body, add document ID lookup in current tree order, and provide live tag-name collections with indexed own properties. Validate lookup, collections, and parsed attributes with upstream WPT cases loaded into the UI DOM through a parse5 test fixture.

‎packages/ui/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
}
5252
},
5353
"devDependencies": {
54-
"@bomb.sh/web-platform-tests": "workspace:*"
54+
"@bomb.sh/web-platform-tests": "workspace:*",
55+
"parse5": "^8.1.1"
5556
}
5657
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { describe, it, expect } from 'vitest';
22
import { testDOMCompatibility } from '@bomb.sh/web-platform-tests';
3-
import { Document } from './dom.ts';
3+
import { createDocument } from '../test/document.ts';
44
import config from '../test/wpt.config.ts';
55

66
testDOMCompatibility({
77
runner: { describe, it, expect },
88
config,
9-
create: () => new Document(() => {}),
9+
create: createDocument,
1010
});

‎packages/ui/src/dom.ts‎

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { asciiUppercase, asciiLowercase } from './ascii.ts';
44
import { NamedNodeMap } from './named-node-map.ts';
5+
import { HTMLCollection } from './html-collection.ts';
56
import {
67
validateElementName,
78
validateElementNamespace,
@@ -13,13 +14,72 @@ const HTML_NS = 'http://www.w3.org/1999/xhtml';
1314

1415
export class Document {
1516
readonly documentElement: Element;
17+
readonly body: HTMLBodyElement;
1618
readonly notify: () => void;
1719

18-
#registry: Map<string, typeof Element> = new Map([['span', HTMLSpanElement]]);
20+
#registry: Map<string, typeof Element> = new Map([
21+
['html', HTMLHtmlElement],
22+
['body', HTMLBodyElement],
23+
['span', HTMLSpanElement],
24+
['div', HTMLDivElement],
25+
]);
1926

2027
constructor(notify: () => void) {
2128
this.notify = notify;
22-
this.documentElement = new Element(this, 'document', notify);
29+
this.documentElement = this.createElement('html');
30+
this.body = this.createElement('body');
31+
this.documentElement.appendChild(this.body);
32+
}
33+
34+
getElementsByTagName(qualifiedName: string): HTMLCollection {
35+
if (arguments.length === 0) {
36+
throw new TypeError('getElementsByTagName requires a qualified name');
37+
}
38+
const name = `${qualifiedName}`;
39+
const lowerName = asciiLowercase(name);
40+
return new HTMLCollection(() => {
41+
const matches: Element[] = [];
42+
const stack = [this.documentElement];
43+
while (stack.length > 0) {
44+
const element = stack.pop()!;
45+
const elementName =
46+
element.prefix === null ? element.localName : `${element.prefix}:${element.localName}`;
47+
if (name === '*' || elementName === (element.namespaceURI === HTML_NS ? lowerName : name)) {
48+
matches.push(element);
49+
}
50+
for (let i = element.childNodes.length - 1; i >= 0; i--) {
51+
const child = element.childNodes[i];
52+
if (child instanceof Element) {
53+
stack.push(child);
54+
}
55+
}
56+
}
57+
return matches;
58+
});
59+
}
60+
61+
getElementById(id: string): Element | null {
62+
if (arguments.length === 0) {
63+
throw new TypeError('getElementById requires an ID');
64+
}
65+
const name = `${id}`;
66+
if (name === '') {
67+
return null;
68+
}
69+
const stack = [this.documentElement];
70+
while (stack.length > 0) {
71+
const element = stack.pop()!;
72+
if (element.id === name) {
73+
return element;
74+
}
75+
for (let i = element.childNodes.length - 1; i >= 0; i--) {
76+
const child = element.childNodes[i];
77+
if (child instanceof Element) {
78+
stack.push(child);
79+
}
80+
}
81+
}
82+
return null;
2383
}
2484

2585
createElement(tagName: string): Element {
@@ -392,8 +452,14 @@ export class Element extends Node {
392452

393453
export class HTMLElement extends Element {}
394454

455+
export class HTMLHtmlElement extends HTMLElement {}
456+
395457
export class HTMLSpanElement extends HTMLElement {}
396458

459+
export class HTMLDivElement extends HTMLElement {}
460+
461+
export class HTMLBodyElement extends HTMLElement {}
462+
397463
export class HTMLUnknownElement extends HTMLElement {}
398464

399465
export class Attr extends Node {

‎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/src/layout.test.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { Layout } from './layout.ts';
66
describe('Layout', () => {
77
it('groups adjacent text around nested and empty elements and keeps IDs stable', () => {
88
const document = new Document(() => {});
9-
const root = document.documentElement;
9+
const root = document.body;
1010
const child = document.createElement('document');
1111
const empty = document.createElement('document');
1212
root.appendChild(document.createTextNode('before'));
@@ -17,7 +17,7 @@ describe('Layout', () => {
1717
root.appendChild(empty);
1818
const layout = new Layout(root);
1919
const expected = [
20-
open('DOCUMENT: 0'),
20+
open('BODY: 0'),
2121
text('before child'),
2222
open('DOCUMENT: 1'),
2323
text('inside'),
@@ -35,7 +35,7 @@ describe('Layout', () => {
3535

3636
it('lays out a deeply nested tree without recursive generator delegation', () => {
3737
const document = new Document(() => {});
38-
const root = document.documentElement;
38+
const root = document.body;
3939
const depth = 20_000;
4040
let current = root;
4141
for (let i = 1; i < depth; i++) {
@@ -46,7 +46,7 @@ describe('Layout', () => {
4646
current.appendChild(document.createTextNode('leaf'));
4747
const iterator = new Layout(root).layout();
4848
for (let i = 0; i < depth; i++) {
49-
expect(iterator.next().value).toEqual(open(`DOCUMENT: ${i}`));
49+
expect(iterator.next().value).toEqual(open(`${i === 0 ? 'BODY' : 'DOCUMENT'}: ${i}`));
5050
}
5151
expect(iterator.next().value).toEqual(text('leaf'));
5252
for (let i = 0; i < depth; i++) {
@@ -57,7 +57,7 @@ describe('Layout', () => {
5757

5858
it('closes active elements when iteration is returned early', () => {
5959
const document = new Document(() => {});
60-
const root = document.documentElement;
60+
const root = document.body;
6161
const child = document.createElement('document');
6262
root.appendChild(child);
6363
child.appendChild(document.createTextNode('inside'));

‎packages/ui/test/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Rendering, scheduling, notifications, and lifecycle behavior belong in the UI te
1818

1919
## DOM compatibility
2020

21-
[`dom.compatibility.test.ts`](../src/dom.compatibility.test.ts) registers the shared compatibility suite with Vitest. Its synchronous factory creates a fresh instance of the real [`Document`](../src/dom.ts) for each case, with a no-op render notification callback. This fixture owns no external resources, so it needs no disposal callback.
21+
[`dom.compatibility.test.ts`](../src/dom.compatibility.test.ts) registers the shared compatibility suite with Vitest. Its [`document factory`](document.ts) creates a fresh instance of the real [`Document`](../src/dom.ts) for each case, with a no-op render notification callback. When a case supplies HTML, parse5 builds the parsed tree and the factory copies its document-element subtree into UI nodes. It reuses the document's HTML root and body, preserving attributes, namespaces, text, comments, and child order. Parsing stays in the test harness; assertions exercise the UI DOM. This fixture owns no external resources, so it needs no disposal callback.
2222

2323
[`dom.test.ts`](dom.test.ts) explicitly holds local DOM coverage missing from the enabled WPT cases. This is usually because getting the WPT test prequisites set up is too onerous a task. For example, testing node properties like nextSibling and previousSibling require things like `document.implementation.createDocumentType()`
2424

‎packages/ui/test/document.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/* oxlint-disable bombshell-dev/exported-function-async -- WPT document creation is synchronous. */
2+
import { parse, defaultTreeAdapter as tree, type DefaultTreeAdapterTypes } from 'parse5';
3+
import type { DOMDocumentOptions } from '@bomb.sh/web-platform-tests';
4+
import { Document, type Element } from '../src/dom.ts';
5+
6+
const HTML_NS = 'http://www.w3.org/1999/xhtml';
7+
8+
class UnsupportedFixtureError extends Error {
9+
constructor(message: string) {
10+
super(message);
11+
this.name = 'UnsupportedFixtureError';
12+
}
13+
}
14+
15+
/** Parse test markup and materialize its element tree using the UI's own DOM. */
16+
export function createDocument(options?: DOMDocumentOptions): Document {
17+
const document = new Document(() => {});
18+
if (!options) return document;
19+
if (options.contentType !== 'text/html') {
20+
throw new UnsupportedFixtureError(`Unsupported fixture MIME type: ${options.contentType}`);
21+
}
22+
if (options.fragment !== undefined) {
23+
throw new UnsupportedFixtureError('URL fragments are not supported by the UI fixture');
24+
}
25+
const parsed = parse(options.content);
26+
const root = parsed.childNodes.find(tree.isElementNode)!;
27+
if (!root.childNodes.some((node) => tree.isElementNode(node) && node.tagName === 'body')) {
28+
throw new UnsupportedFixtureError('Frameset documents are not supported by the UI fixture');
29+
}
30+
const body = document.body;
31+
while (document.documentElement.firstChild) document.documentElement.firstChild.remove();
32+
copyAttributes(root, document.documentElement);
33+
const pending = [{ source: root, target: document.documentElement }];
34+
while (pending.length > 0) {
35+
const { source, target } = pending.pop()!;
36+
for (const child of source.childNodes) {
37+
if (tree.isTextNode(child)) {
38+
target.appendChild(document.createTextNode(child.value));
39+
} else if (tree.isCommentNode(child)) {
40+
target.appendChild(document.createComment(child.data));
41+
} else if (tree.isElementNode(child)) {
42+
if ('content' in child || child.tagName === 'script') {
43+
throw new UnsupportedFixtureError(
44+
'Templates and scripts are not supported by the UI fixture',
45+
);
46+
}
47+
const element =
48+
source === root && child.tagName === 'body' && body
49+
? body
50+
: child.namespaceURI === HTML_NS
51+
? document.createElement(child.tagName)
52+
: document.createElementNS(child.namespaceURI, child.tagName);
53+
copyAttributes(child, element);
54+
target.appendChild(element);
55+
pending.push({ source: child, target: element });
56+
}
57+
}
58+
}
59+
return document;
60+
}
61+
62+
function copyAttributes(source: DefaultTreeAdapterTypes.Element, target: Element): void {
63+
for (const attribute of source.attrs) {
64+
const name = attribute.prefix ? `${attribute.prefix}:${attribute.name}` : attribute.name;
65+
if (attribute.namespace) {
66+
target.setAttributeNS(attribute.namespace, name, attribute.value);
67+
} else {
68+
target.setAttribute(name, attribute.value);
69+
}
70+
}
71+
}

0 commit comments

Comments
 (0)