Skip to content
Draft
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
---

Add document ID lookup in tree order and live tag-name collections with indexed own properties, covered by original upstream Web Platform Tests.
63 changes: 63 additions & 0 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { 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 Down Expand Up @@ -325,6 +326,65 @@ 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(() => {
const matches: Element[] = [];
const stack = this.childNodes
.filter((node): node is Element => node instanceof Element)
.toReversed();
while (stack.length > 0) {
const element = stack.pop()!;
const elementName =
element.prefix === null ? element.localName : `${element.prefix}:${element.localName}`;
if (
name === '*' ||
elementName ===
(this instanceof HTMLDocument && 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.childNodes
.filter((node): node is Element => node instanceof Element)
.toReversed();
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 {
if (arguments.length === 0) {
throw new TypeError('createElement requires a tag name');
Expand Down Expand Up @@ -774,6 +834,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 @@ -820,6 +881,8 @@ export class HTMLBodyElement extends HTMLElement {}

export class HTMLSpanElement extends HTMLElement {}

export class HTMLDivElement extends HTMLElement {}

export class HTMLUnknownElement extends HTMLElement {}

/** XML */
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
);
}
53 changes: 50 additions & 3 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
DocumentType,
Element,
HTMLBodyElement,
HTMLDivElement,
HTMLElement,
HTMLHeadElement,
HTMLHtmlElement,
Expand All @@ -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(() => {}),
Expand All @@ -37,6 +39,8 @@ const config: WPTConfig = {
Event: globalThis.Event,
EventTarget: globalThis.EventTarget,
HTMLBodyElement,
HTMLDivElement,
HTMLCollection,
HTMLElement,
HTMLHeadElement,
HTMLHtmlElement,
Expand All @@ -62,6 +66,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': [
Expand Down Expand Up @@ -98,9 +147,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',
Expand Down
Loading