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
5 changes: 5 additions & 0 deletions .changeset/dom-get-element-by-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/ui': patch
---

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.
3 changes: 2 additions & 1 deletion packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
}
},
"devDependencies": {
"@bomb.sh/web-platform-tests": "workspace:*"
"@bomb.sh/web-platform-tests": "workspace:*",
"parse5": "^8.1.1"
}
}
4 changes: 2 additions & 2 deletions packages/ui/src/dom.compatibility.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { describe, it, expect } from 'vitest';
import { testDOMCompatibility } from '@bomb.sh/web-platform-tests';
import { Document } from './dom.ts';
import { createDocument } from '../test/document.ts';
import config from '../test/wpt.config.ts';

testDOMCompatibility({
runner: { describe, it, expect },
config,
create: () => new Document(() => {}),
create: createDocument,
});
70 changes: 68 additions & 2 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

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

export class Document {
readonly documentElement: Element;
readonly body: HTMLBodyElement;
readonly notify: () => void;

#registry: Map<string, typeof Element> = new Map([['span', HTMLSpanElement]]);
#registry: Map<string, typeof Element> = new Map([
['html', HTMLHtmlElement],
['body', HTMLBodyElement],
['span', HTMLSpanElement],
['div', HTMLDivElement],
]);

constructor(notify: () => void) {
this.notify = notify;
this.documentElement = new Element(this, 'document', notify);
this.documentElement = this.createElement('html');
this.body = this.createElement('body');
this.documentElement.appendChild(this.body);
}

getElementsByTagName(qualifiedName: string): HTMLCollection {
if (arguments.length === 0) {
throw new TypeError('getElementsByTagName requires a qualified name');
}
const name = `${qualifiedName}`;
const lowerName = asciiLowercase(name);
return new HTMLCollection(() => {
const matches: Element[] = [];
const stack = [this.documentElement];
while (stack.length > 0) {
const element = stack.pop()!;
const elementName =
element.prefix === null ? element.localName : `${element.prefix}:${element.localName}`;
if (name === '*' || elementName === (element.namespaceURI === HTML_NS ? lowerName : name)) {
matches.push(element);
}
for (let i = element.childNodes.length - 1; i >= 0; i--) {
const child = element.childNodes[i];
if (child instanceof Element) {
stack.push(child);
}
}
}
return matches;
});
}

getElementById(id: string): Element | null {
if (arguments.length === 0) {
throw new TypeError('getElementById requires an ID');
}
const name = `${id}`;
if (name === '') {
return null;
}
const stack = [this.documentElement];
while (stack.length > 0) {
const element = stack.pop()!;
if (element.id === name) {
return element;
}
for (let i = element.childNodes.length - 1; i >= 0; i--) {
const child = element.childNodes[i];
if (child instanceof Element) {
stack.push(child);
}
}
}
return null;
}

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

export class HTMLElement extends Element {}

export class HTMLHtmlElement extends HTMLElement {}

export class HTMLSpanElement extends HTMLElement {}

export class HTMLDivElement extends HTMLElement {}

export class HTMLBodyElement extends HTMLElement {}

export class HTMLUnknownElement extends HTMLElement {}

export class Attr extends Node {
Expand Down
102 changes: 102 additions & 0 deletions packages/ui/src/html-collection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import type { Element } from './dom.ts';

const sources = new WeakMap<HTMLCollection, () => Element[]>();

export class HTMLCollection implements Iterable<Element> {
readonly [index: number]: Element;

constructor(elements: () => Element[]) {
sources.set(this, elements);
const collection = new Proxy(this, {
get(target, key, receiver) {
if (isArrayIndex(key)) {
return elements()[Number(key)] ?? Reflect.get(target, key, receiver);
}
if (typeof key === 'string' && !(key in target)) {
return namedElement(elements(), key) ?? undefined;
}
return Reflect.get(target, key, receiver);
},
has(target, key) {
if (isArrayIndex(key) && Number(key) < elements().length) {
return true;
}
return Reflect.has(target, key);
},
getOwnPropertyDescriptor(target, key) {
if (isArrayIndex(key)) {
const element = elements()[Number(key)];
if (element !== undefined) {
return { value: element, writable: false, enumerable: true, configurable: true };
}
}
return Reflect.getOwnPropertyDescriptor(target, key);
},
ownKeys(target) {
const indices = elements().map((_, index) => `${index}`);
return [...indices, ...Reflect.ownKeys(target)];
},
set(target, key, value, receiver) {
if (isArrayIndex(key) && Number(key) < elements().length) {
return false;
}
return Reflect.set(target, key, value, receiver);
},
defineProperty(target, key, descriptor) {
if (isArrayIndex(key)) {
return false;
}
return Reflect.defineProperty(target, key, descriptor);
},
deleteProperty(target, key) {
if (isArrayIndex(key)) {
return Number(key) >= elements().length;
}
return Reflect.deleteProperty(target, key);
},
preventExtensions() {
// Live indices must remain able to appear and disappear.
return false;
},
});
sources.set(collection, elements);
return collection;
}

get length(): number {
return sources.get(this)!().length;
}

item(index: number): Element | null {
return sources.get(this)!()[index >>> 0] ?? null;
}

namedItem(name: string): Element | null {
const key = `${name}`;
return namedElement(sources.get(this)!(), key);
}

*[Symbol.iterator](): IterableIterator<Element> {
for (let index = 0; index < this.length; index++) {
yield this.item(index)!;
}
}
}

function isArrayIndex(key: PropertyKey): key is string {
return typeof key === 'string' && /^(0|[1-9]\d*)$/.test(key) && Number(key) < 2 ** 32 - 1;
}

function namedElement(elements: Element[], name: string): Element | null {
if (name === '') {
return null;
}
return (
elements.find(
(element) =>
element.id === name ||
(element.namespaceURI === 'http://www.w3.org/1999/xhtml' &&
element.getAttribute('name') === name),
) ?? null
);
}
10 changes: 5 additions & 5 deletions packages/ui/src/layout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Layout } from './layout.ts';
describe('Layout', () => {
it('groups adjacent text around nested and empty elements and keeps IDs stable', () => {
const document = new Document(() => {});
const root = document.documentElement;
const root = document.body;
const child = document.createElement('document');
const empty = document.createElement('document');
root.appendChild(document.createTextNode('before'));
Expand All @@ -17,7 +17,7 @@ describe('Layout', () => {
root.appendChild(empty);
const layout = new Layout(root);
const expected = [
open('DOCUMENT: 0'),
open('BODY: 0'),
text('before child'),
open('DOCUMENT: 1'),
text('inside'),
Expand All @@ -35,7 +35,7 @@ describe('Layout', () => {

it('lays out a deeply nested tree without recursive generator delegation', () => {
const document = new Document(() => {});
const root = document.documentElement;
const root = document.body;
const depth = 20_000;
let current = root;
for (let i = 1; i < depth; i++) {
Expand All @@ -46,7 +46,7 @@ describe('Layout', () => {
current.appendChild(document.createTextNode('leaf'));
const iterator = new Layout(root).layout();
for (let i = 0; i < depth; i++) {
expect(iterator.next().value).toEqual(open(`DOCUMENT: ${i}`));
expect(iterator.next().value).toEqual(open(`${i === 0 ? 'BODY' : 'DOCUMENT'}: ${i}`));
}
expect(iterator.next().value).toEqual(text('leaf'));
for (let i = 0; i < depth; i++) {
Expand All @@ -57,7 +57,7 @@ describe('Layout', () => {

it('closes active elements when iteration is returned early', () => {
const document = new Document(() => {});
const root = document.documentElement;
const root = document.body;
const child = document.createElement('document');
root.appendChild(child);
child.appendChild(document.createTextNode('inside'));
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Rendering, scheduling, notifications, and lifecycle behavior belong in the UI te

## DOM compatibility

[`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.
[`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.

[`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()`

Expand Down
71 changes: 71 additions & 0 deletions packages/ui/test/document.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/* oxlint-disable bombshell-dev/exported-function-async -- WPT document creation is synchronous. */
import { parse, defaultTreeAdapter as tree, type DefaultTreeAdapterTypes } from 'parse5';
import type { DOMDocumentOptions } from '@bomb.sh/web-platform-tests';
import { Document, type Element } from '../src/dom.ts';

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

class UnsupportedFixtureError extends Error {
constructor(message: string) {
super(message);
this.name = 'UnsupportedFixtureError';
}
}

/** Parse test markup and materialize its element tree using the UI's own DOM. */
export function createDocument(options?: DOMDocumentOptions): Document {
const document = new Document(() => {});
if (!options) return document;
if (options.contentType !== 'text/html') {
throw new UnsupportedFixtureError(`Unsupported fixture MIME type: ${options.contentType}`);
}
if (options.fragment !== undefined) {
throw new UnsupportedFixtureError('URL fragments are not supported by the UI fixture');
}
const parsed = parse(options.content);
const root = parsed.childNodes.find(tree.isElementNode)!;
if (!root.childNodes.some((node) => tree.isElementNode(node) && node.tagName === 'body')) {
throw new UnsupportedFixtureError('Frameset documents are not supported by the UI fixture');
}
const body = document.body;
while (document.documentElement.firstChild) document.documentElement.firstChild.remove();
copyAttributes(root, document.documentElement);
const pending = [{ source: root, target: document.documentElement }];
while (pending.length > 0) {
const { source, target } = pending.pop()!;
for (const child of source.childNodes) {
if (tree.isTextNode(child)) {
target.appendChild(document.createTextNode(child.value));
} else if (tree.isCommentNode(child)) {
target.appendChild(document.createComment(child.data));
} else if (tree.isElementNode(child)) {
if ('content' in child || child.tagName === 'script') {
throw new UnsupportedFixtureError(
'Templates and scripts are not supported by the UI fixture',
);
}
const element =
source === root && child.tagName === 'body' && body
? body
: child.namespaceURI === HTML_NS
? document.createElement(child.tagName)
: document.createElementNS(child.namespaceURI, child.tagName);
copyAttributes(child, element);
target.appendChild(element);
pending.push({ source: child, target: element });
}
}
}
return document;
}

function copyAttributes(source: DefaultTreeAdapterTypes.Element, target: Element): void {
for (const attribute of source.attrs) {
const name = attribute.prefix ? `${attribute.prefix}:${attribute.name}` : attribute.name;
if (attribute.namespace) {
target.setAttributeNS(attribute.namespace, name, attribute.value);
} else {
target.setAttribute(name, attribute.value);
}
}
}
Loading
Loading