Skip to content
Closed
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-document-fragment.md
Original file line number Diff line number Diff line change
@@ -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.
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
---

Add document ID lookup in tree order and live tag-name collections with indexed own properties, covered by original upstream Web Platform Tests.
5 changes: 5 additions & 0 deletions .changeset/dom-is-connected.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/ui': patch
---

Add Node.isConnected by walking the node's ancestry to a document.
11 changes: 11 additions & 0 deletions packages/ui/src/css-select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
117 changes: 116 additions & 1 deletion packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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);
}
Expand All @@ -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;

Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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));
}
}
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
);
}
Loading