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/.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/.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/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 4833873..59f2cb0 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, @@ -21,6 +22,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 +31,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; @@ -151,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); } @@ -194,6 +207,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; } @@ -316,6 +336,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'); @@ -355,6 +405,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 +426,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 +520,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); } @@ -720,6 +806,7 @@ export class HTMLDocument extends Document { ['title', HTMLTitleElement], ['body', HTMLBodyElement], ['span', HTMLSpanElement], + ['div', HTMLDivElement], ]); constructor(notify: Node['notify']) { super(notify, (owner, localName, notifyElement, namespace) => { @@ -766,8 +853,36 @@ export class HTMLBodyElement extends HTMLElement {} export class HTMLSpanElement extends HTMLElement {} +export class HTMLDivElement extends HTMLElement {} + 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/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 1193847..01aba53 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -5,9 +5,11 @@ import { CharacterData, Comment, Document, + DocumentFragment, DocumentType, Element, HTMLBodyElement, + HTMLDivElement, HTMLElement, HTMLHeadElement, HTMLHtmlElement, @@ -19,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(() => {}), @@ -29,12 +32,15 @@ const config: WPTConfig = { Comment, CustomEvent: globalThis.CustomEvent, Document, + DocumentFragment, DocumentType, DOMException: globalThis.DOMException, Element, Event: globalThis.Event, EventTarget: globalThis.EventTarget, HTMLBodyElement, + HTMLDivElement, + HTMLCollection, HTMLElement, HTMLHeadElement, HTMLHtmlElement, @@ -47,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, @@ -60,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': [ @@ -96,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', @@ -161,8 +218,20 @@ const config: WPTConfig = { 'Attribute with prefix in local name', 'getAttributeNames tests', ], - 'dom/nodes/Node-nodeValue.html': ['Text.nodeValue', 'Comment.nodeValue'], + 'dom/nodes/Node-isConnected.html': ['Test with ordinary child nodes'], + '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 +246,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)', ],