From 2e1197bef8783e4581da6dcaad2117ac4f80e18e Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Thu, 12 Nov 2026 21:39:39 -0600 Subject: [PATCH] Support document ID lookup with parsed WPT fixtures --- .changeset/dom-get-element-by-id.md | 5 + packages/ui/package.json | 3 +- packages/ui/src/dom.compatibility.test.ts | 4 +- packages/ui/src/dom.ts | 70 +++- packages/ui/src/html-collection.ts | 102 +++++ packages/ui/src/layout.test.ts | 10 +- packages/ui/test/README.md | 2 +- packages/ui/test/document.ts | 71 ++++ packages/ui/test/dom.test.ts | 11 +- packages/ui/test/wpt.config.ts | 62 ++- packages/web-platform-tests/docs/omissions.md | 1 + .../web-platform-tests/src/shared/registry.ts | 10 + .../HTMLCollection-iterator.html.ts | 78 ++++ ...lection-supported-property-indices.html.ts | 238 +++++++++++ ...ollection-supported-property-names.html.ts | 215 ++++++++++ ...ocument-Element-getElementsByTagName.js.ts | 392 ++++++++++++++++++ .../Document-getElementsByTagName.html.ts | 16 + .../dom-tree-accessors/Document.body.html.ts | 24 ++ pnpm-lock.yaml | 16 + 19 files changed, 1308 insertions(+), 22 deletions(-) create mode 100644 .changeset/dom-get-element-by-id.md create mode 100644 packages/ui/src/html-collection.ts create mode 100644 packages/ui/test/document.ts create mode 100644 packages/web-platform-tests/src/wpt/dom/collections/HTMLCollection-iterator.html.ts create mode 100644 packages/web-platform-tests/src/wpt/dom/collections/HTMLCollection-supported-property-indices.html.ts create mode 100644 packages/web-platform-tests/src/wpt/dom/collections/HTMLCollection-supported-property-names.html.ts create mode 100644 packages/web-platform-tests/src/wpt/dom/nodes/Document-Element-getElementsByTagName.js.ts create mode 100644 packages/web-platform-tests/src/wpt/dom/nodes/Document-getElementsByTagName.html.ts create mode 100644 packages/web-platform-tests/src/wpt/html/dom/documents/dom-tree-accessors/Document.body.html.ts diff --git a/.changeset/dom-get-element-by-id.md b/.changeset/dom-get-element-by-id.md new file mode 100644 index 0000000..f41336c --- /dev/null +++ b/.changeset/dom-get-element-by-id.md @@ -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. diff --git a/packages/ui/package.json b/packages/ui/package.json index 5e696f1..a60b9d0 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -51,6 +51,7 @@ } }, "devDependencies": { - "@bomb.sh/web-platform-tests": "workspace:*" + "@bomb.sh/web-platform-tests": "workspace:*", + "parse5": "^8.1.1" } } diff --git a/packages/ui/src/dom.compatibility.test.ts b/packages/ui/src/dom.compatibility.test.ts index 01055f5..e3c241b 100644 --- a/packages/ui/src/dom.compatibility.test.ts +++ b/packages/ui/src/dom.compatibility.test.ts @@ -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, }); diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 8a5bfd4..95493cb 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -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, @@ -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 = new Map([['span', HTMLSpanElement]]); + #registry: Map = 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 { @@ -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 { diff --git a/packages/ui/src/html-collection.ts b/packages/ui/src/html-collection.ts new file mode 100644 index 0000000..f18e30f --- /dev/null +++ b/packages/ui/src/html-collection.ts @@ -0,0 +1,102 @@ +import type { Element } from './dom.ts'; + +const sources = new WeakMap Element[]>(); + +export class HTMLCollection implements Iterable { + 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 { + 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 + ); +} diff --git a/packages/ui/src/layout.test.ts b/packages/ui/src/layout.test.ts index 632e650..28b24be 100644 --- a/packages/ui/src/layout.test.ts +++ b/packages/ui/src/layout.test.ts @@ -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')); @@ -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'), @@ -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++) { @@ -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++) { @@ -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')); diff --git a/packages/ui/test/README.md b/packages/ui/test/README.md index 2e0750d..2fb4c91 100644 --- a/packages/ui/test/README.md +++ b/packages/ui/test/README.md @@ -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()` diff --git a/packages/ui/test/document.ts b/packages/ui/test/document.ts new file mode 100644 index 0000000..0e898e5 --- /dev/null +++ b/packages/ui/test/document.ts @@ -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); + } + } +} diff --git a/packages/ui/test/dom.test.ts b/packages/ui/test/dom.test.ts index 7cddf6a..b5ccad1 100644 --- a/packages/ui/test/dom.test.ts +++ b/packages/ui/test/dom.test.ts @@ -2,7 +2,8 @@ * Local DOM coverage not provided by our enabled WPT cases. * These are independent tests, not adaptations of upstream WPT tests. * Sibling traversal lives here while Node-properties.html requires unsupported - * HTML/XML document fixtures. Prefer WPT coverage when its dependencies are met. + * HTML/XML document factories. + * Prefer WPT coverage when its dependencies are met. */ import { describe, expect, it } from 'vitest'; import { Document } from '../src/dom.ts'; @@ -12,7 +13,7 @@ describe('Node sibling properties outside WPT coverage', () => { '%s has no siblings when detached or an only child', (create) => { const document = new Document(() => {}); - const parent = document.documentElement; + const parent = document.body; const node = document[create]('document'); expect(node.previousSibling).toBeNull(); @@ -30,7 +31,7 @@ describe('Node sibling properties outside WPT coverage', () => { it('traverses immediate siblings including text and comments', () => { const document = new Document(() => {}); - const parent = document.documentElement; + const parent = document.body; const first = parent.appendChild(document.createElement('document')); const text = parent.appendChild(document.createTextNode('text')); const comment = parent.appendChild(document.createComment('comment')); @@ -51,7 +52,7 @@ describe('Node sibling properties outside WPT coverage', () => { it('updates both directions when existing children are reordered', () => { const document = new Document(() => {}); - const parent = document.documentElement; + const parent = document.body; const first = parent.appendChild(document.createElement('document')); const middle = parent.appendChild(document.createTextNode('middle')); const last = parent.appendChild(document.createComment('last')); @@ -95,7 +96,7 @@ describe('Node sibling properties outside WPT coverage', () => { it('closes the sibling gap on removal and clears detached relationships', () => { const document = new Document(() => {}); - const parent = document.documentElement; + const parent = document.body; const first = parent.appendChild(document.createTextNode('first')); const middle = parent.appendChild(document.createComment('middle')); const last = parent.appendChild(document.createElement('document')); diff --git a/packages/ui/test/wpt.config.ts b/packages/ui/test/wpt.config.ts index a50a1e8..13e5088 100644 --- a/packages/ui/test/wpt.config.ts +++ b/packages/ui/test/wpt.config.ts @@ -6,12 +6,15 @@ import { Document, Element, HTMLElement, + HTMLDivElement, + HTMLBodyElement, HTMLSpanElement, HTMLUnknownElement, Node, Text, } from '../src/dom.ts'; import { NamedNodeMap } from '../src/named-node-map.ts'; +import { HTMLCollection } from '../src/html-collection.ts'; const config: WPTConfig = { globals: { @@ -26,6 +29,9 @@ const config: WPTConfig = { Event: globalThis.Event, EventTarget: globalThis.EventTarget, HTMLElement, + HTMLDivElement, + HTMLBodyElement, + HTMLCollection, HTMLSpanElement, HTMLUnknownElement, NamedNodeMap, @@ -47,10 +53,55 @@ const config: WPTConfig = { // Native EventTarget reads handleEvent at registration; the getter-timing // case remains excluded until that behavior is implemented. ], + 'dom/collections/HTMLCollection-iterator.html': true, + 'dom/collections/HTMLCollection-supported-property-indices.html': true, + 'dom/collections/HTMLCollection-supported-property-names.html': [ + 'Object.getOwnPropertyNames on HTMLCollection with non-HTML namespace', + 'Object.getOwnPropertyNames on HTMLCollection with expando object', + 'Trying to set an expando that shadows a named property that gets added later', + 'Trying to set a non-configurable expando that shadows a named property that gets added later', + // The other cases require named own properties and their descriptors. + ], 'dom/nodes/Document-createTextNode.html': true, 'dom/nodes/Document-createElement.html': true, 'dom/nodes/Document-createElementNS.html': true, 'dom/nodes/Document-createComment.html': true, + 'dom/nodes/Document-getElementById.html': [ + 'Calling document.getElementById with an empty string argument.', + 'Calling document.getElementById with a null argument.', + 'Calling document.getElementById with an undefined argument.', + 'on static page', + 'Document.getElementById with a script-inserted element', + 'update `id` attribute via setAttribute/removeAttribute', + 'Ensure that the id attribute only affects elements present in a document', + "in tree order, within the context object's tree", + '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`.', + "changing attribute's value via `Attr` gotten from `Element.attribute`.", + 'update `id` attribute via element.id', + "where insertion order and tree order don't match", + 'Inserting an id by inserting its parent node', + 'Document.getElementById must not return nodes not present in document', + // Four other cases require innerHTML or outerHTML mutation. + ], + 'html/dom/documents/dom-tree-accessors/Document.body.html': true, + 'dom/nodes/Document-getElementsByTagName.html': [ + 'Caching is allowed', + "Shouldn't be able to set unsigned properties on a HTMLCollection (non-strict mode)", + "Shouldn't be able to set unsigned properties on a HTMLCollection (strict mode)", + 'Should be able to set expando shadowing a proto prop (item)', + 'Should be able to set expando shadowing a proto prop (namedItem)', + 'HTML element with uppercase tagName never matches in HTML Documents', + 'Element in non-HTML namespace, no prefix, lowercase name', + 'Element in non-HTML namespace, no prefix, uppercase name', + 'Element in non-HTML namespace, prefix, lowercase name', + 'Element in non-HTML namespace, prefix, uppercase name', + 'Element in HTML namespace, no prefix, non-ascii characters in name', + 'Element in non-HTML namespace, non-ascii characters in name', + 'Element in HTML namespace, prefix, non-ascii characters in name', + 'Element in non-HTML namespace, prefix, non-ascii characters in name', + 'getElementsByTagName() should be a live collection', + // Remaining cases need NodeList, Document.childNodes, or named own properties. + ], // XML factory cases require DOMImplementation.createDocument. 'dom/nodes/Document-createAttribute.html': [/^HTML document\.createAttribute\(/], 'dom/nodes/CharacterData-data.html': true, @@ -61,13 +112,9 @@ const config: WPTConfig = { 'dom/nodes/Element-removeAttribute.html': true, 'dom/nodes/Element-removeAttributeNS.html': true, 'dom/nodes/Element-setAttribute-crbug-1138487.html': true, - 'dom/nodes/Element-hasAttribute.html': [ - // The other case requires a parsed HTML fixture. - 'hasAttribute should check for attribute presence, irrespective of namespace', - ], + 'dom/nodes/Element-hasAttribute.html': true, 'dom/nodes/attributes-namednodemap.html': true, - // Excludes cases requiring XML documents, CSS style reflection, document - // fragments, parsed fixtures, or attachment to document.body. + // Excludes cases requiring XML documents, CSS style reflection, or document fragments. 'dom/nodes/attributes.html': [ 'Attribute loses its owner when removed', 'Basic functionality of getAttributeNode/getAttributeNodeNS', @@ -119,11 +166,14 @@ const config: WPTConfig = { 'Setting the same attribute with another prefix should not change the prefix', 'setAttribute should not throw even if a load is not allowed', 'Attribute values should not be parsed.', + 'Specified attributes should be accessible.', + 'Entities in attributes should have been expanded while parsing.', 'Unset attributes return null', 'First set attribute is returned by getAttribute', 'Style attributes are not normalized', 'Only lowercase attributes are returned on HTML elements (upper case attribute)', 'Only lowercase attributes are returned on HTML elements (mixed case attribute)', + 'First set attribute is returned with mapped attribute set first', 'First set attribute is returned with mapped attribute set later', 'Non-HTML element with upper-case attribute', 'Attribute with prefix in local name', diff --git a/packages/web-platform-tests/docs/omissions.md b/packages/web-platform-tests/docs/omissions.md index 770039e..d6ccbba 100644 --- a/packages/web-platform-tests/docs/omissions.md +++ b/packages/web-platform-tests/docs/omissions.md @@ -13,6 +13,7 @@ the upstream WPT root. Consumer exclusions in `wpt.config.ts` are separate. | `dom/nodes/attributes.html` | `setAttributeNode, if it fires mutation events, should fire one with the new node when resetting an existing attribute`, and its ` (outer shell)` companion. | Legacy `DOMAttrModified` coverage is outside the current event scope; both the listener assertions and their outer-shell setup remain omitted. | | `dom/events/EventListener-handleEvent.html` | `` rethrows errors when getting `handleEvent` ``, ``throws if `handleEvent` is falsy and not callable``, and ``throws if `handleEvent` is thruthy and not callable``. | Require asynchronous window error reporting and the upstream `EventWatcher` harness. | | `domparsing/createContextualFragment.html` | `