From 8ce47b652b87cc31abce6c00b5e26ba41d03d552 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Tue, 17 Nov 2026 15:30:32 -0600 Subject: [PATCH 1/3] Add document fragments for native WPT setup --- .changeset/dom-document-fragment.md | 5 ++ packages/ui/src/dom.ts | 71 +++++++++++++++++++++++++++++ packages/ui/wpt.config.ts | 19 +++++++- 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 .changeset/dom-document-fragment.md diff --git a/.changeset/dom-document-fragment.md b/.changeset/dom-document-fragment.md new file mode 100644 index 0000000..8812f1f --- /dev/null +++ b/.changeset/dom-document-fragment.md @@ -0,0 +1,5 @@ +--- +'@clack/ui': patch +--- + +Add document fragment creation and child transfer during insertion, and support reading and replacing text content on elements and fragments. diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 4833873..43ed638 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -21,6 +21,7 @@ export abstract class Node extends EventTarget { static readonly COMMENT_NODE = 8; static readonly DOCUMENT_NODE = 9; static readonly DOCUMENT_TYPE_NODE = 10; + static readonly DOCUMENT_FRAGMENT_NODE = 11; readonly ELEMENT_NODE = Node.ELEMENT_NODE; readonly ATTRIBUTE_NODE = Node.ATTRIBUTE_NODE; @@ -29,6 +30,7 @@ export abstract class Node extends EventTarget { readonly COMMENT_NODE = Node.COMMENT_NODE; readonly DOCUMENT_NODE = Node.DOCUMENT_NODE; readonly DOCUMENT_TYPE_NODE = Node.DOCUMENT_TYPE_NODE; + readonly DOCUMENT_FRAGMENT_NODE = Node.DOCUMENT_FRAGMENT_NODE; readonly #childNodes: Node[] = []; readonly ownerDocument: Document | null; @@ -194,6 +196,13 @@ export abstract class Node extends EventTarget { throw new DOMException('cannot make a Node a child of itself', 'HierarchyRequestError'); } + if (node instanceof DocumentFragment) { + for (const child of node.childNodes.slice()) { + this.insertBefore(child, anchor); + } + return node; + } + if (node === anchor) { return node; } @@ -355,6 +364,10 @@ export class Document extends Node { return new Text(this, String(data), this.notify); } + createDocumentFragment(): DocumentFragment { + return new DocumentFragment(this, this.notify); + } + createComment(data: string): Text { return new Comment(this, String(data), this.notify); } @@ -372,6 +385,30 @@ export class Document extends Node { } } +export class DocumentFragment extends Node { + declare readonly ownerDocument: Document; + + constructor(owner: Document, notify: Node['notify']) { + super(owner, notify); + } + + get nodeType(): number { + return Node.DOCUMENT_FRAGMENT_NODE; + } + + get nodeName(): string { + return '#document-fragment'; + } + + override get textContent(): string { + return getTextContent(this); + } + + override set textContent(value: string | null) { + setTextContent(this, value == null ? '' : `${value}`); + } +} + export class DocumentType extends Node { declare readonly ownerDocument: Document; @@ -442,6 +479,14 @@ export class Element extends Node { return this.nodeName; } + override get textContent(): string { + return getTextContent(this); + } + + override set textContent(value: string | null) { + setTextContent(this, value == null ? '' : `${value}`); + } + get children(): Element[] { return this.childNodes.filter((node) => node instanceof Element); } @@ -771,3 +816,29 @@ export class HTMLUnknownElement extends HTMLElement {} /** XML */ export class XMLDocument extends Document {} + +/** internal helpers **/ + +function getTextContent(node: Element | DocumentFragment): string { + const parts: string[] = []; + const stack = node.childNodes.toReversed(); + while (stack.length > 0) { + const descendant = stack.pop()!; + if (descendant instanceof Text) { + parts.push(descendant.data); + } + for (let index = descendant.childNodes.length - 1; index >= 0; index--) { + stack.push(descendant.childNodes[index]!); + } + } + return parts.join(''); +} + +function setTextContent(node: Element | DocumentFragment, content: string): void { + while (node.firstChild) { + node.removeChild(node.firstChild); + } + if (content !== '') { + node.appendChild(node.ownerDocument.createTextNode(content)); + } +} diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index 1193847..3aae9e5 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -5,6 +5,7 @@ import { CharacterData, Comment, Document, + DocumentFragment, DocumentType, Element, HTMLBodyElement, @@ -29,6 +30,7 @@ const config: WPTConfig = { Comment, CustomEvent: globalThis.CustomEvent, Document, + DocumentFragment, DocumentType, DOMException: globalThis.DOMException, Element, @@ -161,8 +163,19 @@ const config: WPTConfig = { 'Attribute with prefix in local name', 'getAttributeNames tests', ], - 'dom/nodes/Node-nodeValue.html': ['Text.nodeValue', 'Comment.nodeValue'], + 'dom/nodes/Node-nodeName.html': [ + 'For DocumentFragment nodes, nodeName should return "#document-fragment".', + ], + 'dom/nodes/Node-nodeValue.html': [ + 'Text.nodeValue', + 'Comment.nodeValue', + 'DocumentFragment.nodeValue', + ], 'dom/nodes/Node-textContent.html': [ + 'For an empty Element, textContent should be the empty string', + /^Element with(?:out)? /, + 'For an empty DocumentFragment, textContent should be the empty string', + /^DocumentFragment with(?:out)? /, 'For an empty Text, textContent should be the empty string', 'For an empty Comment, textContent should be the empty string', 'For a Text with data, textContent should be that data', @@ -177,6 +190,10 @@ const config: WPTConfig = { 'When the parent is null, parentElement should be null', 'When the parent is a document, parentElement should be null (element)', 'When the parent is a document, parentElement should be null (comment)', + 'parentElement should return null for children of DocumentFragments (element)', + 'parentElement should return null for children of DocumentFragments (text)', + 'parentElement should work correctly with DocumentFragments (element)', + 'parentElement should work correctly with DocumentFragments (text)', 'parentElement should work correctly in disconnected subtrees (element)', 'parentElement should work correctly in disconnected subtrees (text)', ], From 6c779042b9ca830ea16385dd35a37db1b88fcbf5 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Tue, 17 Nov 2026 11:50:57 -0600 Subject: [PATCH 2/3] Support shared DOM lookup and live collections --- .changeset/dom-get-element-by-id.md | 5 ++ packages/ui/src/css-select.ts | 11 +++ packages/ui/src/dom.ts | 36 +++++++++- packages/ui/src/html-collection.ts | 102 ++++++++++++++++++++++++++++ packages/ui/wpt.config.ts | 61 ++++++++++++++++- 5 files changed, 211 insertions(+), 4 deletions(-) create mode 100644 .changeset/dom-get-element-by-id.md create mode 100644 packages/ui/src/html-collection.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..6295d3f --- /dev/null +++ b/.changeset/dom-get-element-by-id.md @@ -0,0 +1,5 @@ +--- +'@clack/ui': patch +--- + +Add document ID lookup in tree order and live tag-name collections with indexed own properties, covered by original upstream Web Platform Tests. diff --git a/packages/ui/src/css-select.ts b/packages/ui/src/css-select.ts index cc4b451..d393a9d 100644 --- a/packages/ui/src/css-select.ts +++ b/packages/ui/src/css-select.ts @@ -72,6 +72,17 @@ export function compile(selector: string): (node: Node) => boolean { } } +export function findElement( + nodes: Node[], + predicate: (element: Element) => boolean, +): Element | null { + return selectOne(predicate, nodes, { adapter, xmlMode: true }); +} + +export function findElements(nodes: Node[], predicate: (element: Element) => boolean): Element[] { + return selectAll(predicate, nodes, { adapter, xmlMode: true }); +} + export function querySelector(nodes: Node[], selector: string): Element | null { const query = compile(selector); return selectOne(query, nodes, { adapter }); diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 43ed638..2b5f096 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -1,8 +1,9 @@ /* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */ -import { querySelector } from './css-select.ts'; +import { findElement, findElements, querySelector } from './css-select.ts'; import { asciiUppercase, asciiLowercase } from './ascii.ts'; import { NamedNodeMap } from './named-node-map.ts'; +import { HTMLCollection } from './html-collection.ts'; import { validateElementName, validateElementNamespace, @@ -325,6 +326,36 @@ export class Document extends Node { return querySelector(Array.from(this.childNodes), selector); } + 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(() => + findElements(Array.from(this.childNodes), (element) => { + const elementName = + element.prefix === null ? element.localName : `${element.prefix}:${element.localName}`; + return ( + name === '*' || + elementName === + (this instanceof HTMLDocument && element.namespaceURI === HTML_NS ? lowerName : name) + ); + }), + ); + } + + getElementById(id: string): Element | null { + if (arguments.length === 0) { + throw new TypeError('getElementById requires an ID'); + } + const name = `${id}`; + if (name === '') { + return null; + } + return findElement(Array.from(this.childNodes), (element) => element.id === name); + } + createElement(tagName: string): Element { if (arguments.length === 0) { throw new TypeError('createElement requires a tag name'); @@ -765,6 +796,7 @@ export class HTMLDocument extends Document { ['title', HTMLTitleElement], ['body', HTMLBodyElement], ['span', HTMLSpanElement], + ['div', HTMLDivElement], ]); constructor(notify: Node['notify']) { super(notify, (owner, localName, notifyElement, namespace) => { @@ -811,6 +843,8 @@ export class HTMLBodyElement extends HTMLElement {} export class HTMLSpanElement extends HTMLElement {} +export class HTMLDivElement extends HTMLElement {} + export class HTMLUnknownElement extends HTMLElement {} /** XML */ 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/wpt.config.ts b/packages/ui/wpt.config.ts index 3aae9e5..5281e1f 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -9,6 +9,7 @@ import { DocumentType, Element, HTMLBodyElement, + HTMLDivElement, HTMLElement, HTMLHeadElement, HTMLHtmlElement, @@ -20,6 +21,7 @@ import { XMLDocument, } from './src/dom.ts'; import { NamedNodeMap } from './src/named-node-map.ts'; +import { HTMLCollection } from './src/html-collection.ts'; const config: WPTConfig = { createDocument: () => createHTMLDocument(() => {}), @@ -37,6 +39,8 @@ const config: WPTConfig = { Event: globalThis.Event, EventTarget: globalThis.EventTarget, HTMLBodyElement, + HTMLDivElement, + HTMLCollection, HTMLElement, HTMLHeadElement, HTMLHtmlElement, @@ -49,6 +53,14 @@ const config: WPTConfig = { XMLDocument, }, include: { + 'html/dom/elements/global-attributes/id-name.html': true, + 'html/dom/elements/global-attributes/id-attribute.html': [ + 'After setting id via id attribute, getElementById find the element by the new id.', + "After setting id via id attribute, getElementById doesn't find the element by the old id.", + 'After setting id via setAttribute attribute, getElementById find the element by the new id.', + "After setting id via setAttribute attribute, getElementById doesn't find the element by the old id.", + // Preserve the existing ID selection; CSS association requires getComputedStyle(). + ], 'dom/events/Event-constructors.any.js': true, 'dom/events/EventTarget-addEventListener.any.js': true, 'dom/events/EventTarget-add-remove-listener.any.js': true, @@ -62,6 +74,51 @@ 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-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': ["existing document's body"], + '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', + // Preserve the existing selection; interface and named own-property coverage remains deferred. + ], 'dom/nodes/Document-createTextNode.html': true, 'dom/nodes/Document-createElement.html': [/^createElement\(.*\) in HTML document$/], 'dom/nodes/Document-createElementNS.html': [ @@ -98,9 +155,7 @@ 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': [ - 'hasAttribute should check for attribute presence, irrespective of namespace', - ], + 'dom/nodes/Element-hasAttribute.html': true, 'dom/nodes/attributes-namednodemap.html': true, 'dom/nodes/attributes.html': [ 'Attribute loses its owner when removed', From 72ad2c3c1c3e00965f466fcfa929e4a52cb48fed Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Tue, 17 Nov 2026 11:55:10 -0600 Subject: [PATCH 3/3] Add Node.isConnected with native WPT coverage --- .changeset/dom-is-connected.md | 5 +++++ packages/ui/src/dom.ts | 10 ++++++++++ packages/ui/wpt.config.ts | 1 + 3 files changed, 16 insertions(+) create mode 100644 .changeset/dom-is-connected.md diff --git a/.changeset/dom-is-connected.md b/.changeset/dom-is-connected.md new file mode 100644 index 0000000..d465174 --- /dev/null +++ b/.changeset/dom-is-connected.md @@ -0,0 +1,5 @@ +--- +'@clack/ui': patch +--- + +Add Node.isConnected by walking the node's ancestry to a document. diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 2b5f096..59f2cb0 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -154,6 +154,16 @@ export abstract class Node extends EventTarget { //ignore } + get isConnected(): boolean { + // oxlint-disable-next-line typescript/no-this-alias -- This cursor walks the node's ancestry. + for (let current: Node | null = this; current; current = current.parentNode) { + if (current instanceof Document) { + return true; + } + } + return false; + } + appendChild(node: Node): Node { return this.insertBefore(node, null); } diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index 5281e1f..01aba53 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -218,6 +218,7 @@ const config: WPTConfig = { 'Attribute with prefix in local name', 'getAttributeNames tests', ], + 'dom/nodes/Node-isConnected.html': ['Test with ordinary child nodes'], 'dom/nodes/Node-nodeName.html': [ 'For DocumentFragment nodes, nodeName should return "#document-fragment".', ],