diff --git a/.changeset/dom-attributes.md b/.changeset/dom-attributes.md new file mode 100644 index 0000000..a96d607 --- /dev/null +++ b/.changeset/dom-attributes.md @@ -0,0 +1,6 @@ +--- +'@clack/ui': minor +'@bomb.sh/web-platform-tests': patch +--- + +Add attribute factories and Element attribute operations backed by an ordered NamedNodeMap. diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 8b4d75b..785590a 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -1,5 +1,13 @@ +/* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */ + import { asciiUppercase, asciiLowercase } from './ascii.ts'; -import { validateElementName, validateElementNamespace } from './validation.ts'; +import { NamedNodeMap } from './named-node-map.ts'; +import { + validateElementName, + validateElementNamespace, + validateAttributeName, + validateAttributeNamespace, +} from './validation.ts'; const HTML_NS = 'http://www.w3.org/1999/xhtml'; @@ -16,7 +24,6 @@ export class Document { createElement(tagName: string): Element { if (arguments.length === 0) { - // oxlint-disable-next-line bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. throw new TypeError('createElement requires a tag name'); } const localName = `${tagName}`; @@ -26,7 +33,6 @@ export class Document { createElementNS(namespace: string | null, qualifiedName: string): Element { if (arguments.length < 2) { - // oxlint-disable-next-line bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. throw new TypeError('createElementNS requires a namespace and qualified name'); } const namespaceURI = namespace == null ? null : `${namespace}` || null; @@ -35,6 +41,22 @@ export class Document { return this.#createElement(localName, { namespaceURI, prefix }); } + createAttribute(localName: string): Attr { + const name = `${localName}`; + validateAttributeName(name); + return new Attr(this, asciiLowercase(name), this.notify); + } + + createAttributeNS(namespace: string | null, qualifiedName: string): Attr { + if (arguments.length < 2) { + throw new TypeError('createAttributeNS requires a namespace and qualified name'); + } + const namespaceURI = namespace == null ? null : `${namespace}` || null; + const name = `${qualifiedName}`; + const { prefix, localName } = validateAttributeNamespace(namespaceURI, name); + return new Attr(this, localName, this.notify, { namespaceURI, prefix }); + } + createTextNode(data: string): Text { return new Text(this, String(data), this.notify); } @@ -183,6 +205,8 @@ export class Element extends Node { readonly namespaceURI: string | null; readonly prefix: string | null; + readonly #attributes: NamedNodeMap; + constructor( owner: Document, localName: string, @@ -195,6 +219,11 @@ export class Element extends Node { this.prefix = prefix; const qualifiedName = prefix === null ? localName : `${prefix}:${localName}`; this.nodeName = namespaceURI === HTML_NS ? asciiUppercase(qualifiedName) : qualifiedName; + this.#attributes = new NamedNodeMap({ + ownerElement: this, + createAttribute: (name, namespace) => new Attr(owner, name, notify, namespace), + notify, + }); } get nodeType(): number { @@ -208,6 +237,87 @@ export class Element extends Node { get children(): Element[] { return this.childNodes.filter((node) => node instanceof Element); } + + get attributes(): NamedNodeMap { + return this.#attributes; + } + + getAttribute(name: string): string | null { + return this.#attributes.getNamedItem(name)?.value ?? null; + } + + hasAttribute(name: string): boolean { + if (arguments.length === 0) { + throw new TypeError('hasAttribute requires an attribute name'); + } + return this.#attributes.getNamedItem(name) !== null; + } + + setAttribute(name: string, value: string): void { + this.#attributes.setAttribute(name, value); + } + + getAttributeNS(namespace: string | null, localName: string): string | null { + if (arguments.length < 2) { + throw new TypeError('getAttributeNS requires a namespace and local name'); + } + return this.#attributes.getNamedItemNS(namespace, localName)?.value ?? null; + } + + setAttributeNS(namespace: string | null, qualifiedName: string, value: string): void { + if (arguments.length < 3) { + throw new TypeError('setAttributeNS requires a namespace, qualified name, and value'); + } + this.#attributes.setAttributeNS(namespace, qualifiedName, value); + } + + hasAttributeNS(namespace: string | null, localName: string): boolean { + return this.#attributes.getNamedItemNS(namespace, localName) !== null; + } + + getAttributeNode(name: string): Attr | null { + return this.#attributes.getNamedItem(name); + } + + getAttributeNodeNS(namespace: string | null, localName: string): Attr | null { + return this.#attributes.getNamedItemNS(namespace, localName); + } + + setAttributeNode(attribute: Attr): Attr | null { + return this.#attributes.setNamedItem(attribute); + } + + setAttributeNodeNS(attribute: Attr): Attr | null { + return this.#attributes.setNamedItemNS(attribute); + } + + removeAttribute(name: string): void { + this.#attributes.removeAttribute(name); + } + + removeAttributeNS(namespace: string | null, localName: string): void { + this.#attributes.removeAttributeNS(namespace, localName); + } + + removeAttributeNode(attribute: Attr): Attr { + return this.#attributes.removeAttributeNode(attribute); + } + + getAttributeNames(): string[] { + return this.#attributes.getAttributeNames(); + } + + toggleAttribute(name: string, force?: boolean): boolean { + return this.#attributes.toggleAttribute(name, force); + } + + get id(): string { + return this.#attributes.getNamedItemNS(null, 'id')?.value ?? ''; + } + + set id(value: string) { + this.#attributes.setAttributeNS(null, 'id', value); + } } export class HTMLElement extends Element {} @@ -216,6 +326,67 @@ export class HTMLSpanElement extends HTMLElement {} export class HTMLUnknownElement extends HTMLElement {} +export class Attr extends Node { + readonly localName: string; + readonly namespaceURI: string | null; + readonly prefix: string | null; + ownerElement: Element | null; + readonly specified = true; + + #value: string; + + constructor( + owner: Document, + localName: string, + notify: Node['notify'], + { + namespaceURI = null, + prefix = null, + ownerElement = null, + value = '', + }: Partial & { ownerElement?: Element | null; value?: string } = {}, + ) { + super(owner, notify); + this.localName = localName; + this.namespaceURI = namespaceURI; + this.prefix = prefix; + this.ownerElement = ownerElement; + this.#value = value; + } + + get nodeType(): number { + return Node.ATTRIBUTE_NODE; + } + + get nodeName(): string { + return this.name; + } + + get name(): string { + return this.prefix === null ? this.localName : `${this.prefix}:${this.localName}`; + } + + get value(): string { + return this.#value; + } + + set value(value: string) { + const normal = `${value}`; + if (this.#value !== normal) { + this.#value = normal; + this.ownerDocument?.notify(); + } + } + + override get nodeValue(): string { + return this.value; + } + + get textContent(): string { + return this.value; + } +} + export abstract class CharacterData extends Node { #data: string; constructor(owner: Document, data: string, notify: Node['notify']) { diff --git a/packages/ui/src/named-node-map.ts b/packages/ui/src/named-node-map.ts new file mode 100644 index 0000000..549d8ad --- /dev/null +++ b/packages/ui/src/named-node-map.ts @@ -0,0 +1,196 @@ +import { asciiLowercase } from './ascii.ts'; +import type { Attr, Element } from './dom.ts'; +import { validateAttributeName, validateAttributeNamespace } from './validation.ts'; + +const HTML_NS = 'http://www.w3.org/1999/xhtml'; + +type AttributeNamespace = Pick; +type AttributeFactory = (localName: string, namespace: AttributeNamespace) => Attr; + +/** + * Holds Element attributes: https://dom.spec.whatwg.org/#interface-namednodemap + * + * Full NamedNodeMap Web IDL behavior (such as intercepting property deletion + * and redefinition) is not supported + */ +export class NamedNodeMap { + readonly [index: number]: Attr; + readonly #ownerElement: Element; + readonly #createAttribute: AttributeFactory; + readonly #notify: () => void; + readonly #attributes: Attr[] = []; + #properties: string[] = []; + + constructor({ + ownerElement, + createAttribute, + notify, + }: { + ownerElement: Element; + createAttribute: AttributeFactory; + notify: () => void; + }) { + this.#ownerElement = ownerElement; + this.#createAttribute = createAttribute; + this.#notify = notify; + } + + get length(): number { + return this.#attributes.length; + } + + item(index: number): Attr | null { + return this.#attributes[index] ?? null; + } + + getNamedItem(name: string): Attr | null { + const normal = this.#normalizeName(name); + return this.#attributes.find((attr) => attr.name === normal) ?? null; + } + + getNamedItemNS(namespace: string | null, localName: string): Attr | null { + const namespaceURI = namespace == null ? null : `${namespace}` || null; + const name = `${localName}`; + return ( + this.#attributes.find( + (attr) => attr.namespaceURI === namespaceURI && attr.localName === name, + ) ?? null + ); + } + + setNamedItem(attr: Attr): Attr | null { + if (attr.ownerElement !== null && attr.ownerElement !== this.#ownerElement) { + throw new DOMException( + 'Attribute is already attached to another element', + 'InUseAttributeError', + ); + } + const previous = this.getNamedItemNS(attr.namespaceURI, attr.localName); + if (previous === attr) { + return attr; + } + if (previous) { + this.#attributes[this.#attributes.indexOf(previous)] = attr; + previous.ownerElement = null; + } else { + this.#attributes.push(attr); + } + attr.ownerElement = this.#ownerElement; + this.#changed(); + return previous; + } + + setNamedItemNS(attr: Attr): Attr | null { + return this.setNamedItem(attr); + } + + removeNamedItem(name: string): Attr { + const attr = this.getNamedItem(name); + if (!attr) { + throw new DOMException('Attribute is not attached to this element', 'NotFoundError'); + } + return this.removeAttributeNode(attr); + } + + removeAttributeNode(attr: Attr): Attr { + const index = this.#attributes.indexOf(attr); + if (index === -1) { + throw new DOMException('Attribute is not attached to this element', 'NotFoundError'); + } + this.#attributes.splice(index, 1); + attr.ownerElement = null; + this.#changed(); + return attr; + } + + setAttribute(name: string, value: string): void { + const normal = this.#normalizeName(name); + const normalValue = `${value}`; + validateAttributeName(normal); + const attr = this.getNamedItem(normal); + if (attr) { + attr.value = normalValue; + } else { + const created = this.#createAttribute(normal, { namespaceURI: null, prefix: null }); + created.value = normalValue; + this.setNamedItem(created); + } + } + + // oxlint-disable-next-line bombshell-dev/max-params -- Mirrors Element.setAttributeNS for delegation. + setAttributeNS(namespace: string | null, qualifiedName: string, value: string): void { + const namespaceURI = namespace == null ? null : `${namespace}` || null; + const name = `${qualifiedName}`; + const normalValue = `${value}`; + const { prefix, localName } = validateAttributeNamespace(namespaceURI, name); + const attr = this.getNamedItemNS(namespaceURI, localName); + if (attr) { + attr.value = normalValue; + } else { + const created = this.#createAttribute(localName, { namespaceURI, prefix }); + created.value = normalValue; + this.setNamedItem(created); + } + } + + removeAttribute(name: string): void { + const attr = this.getNamedItem(name); + if (attr) { + this.removeAttributeNode(attr); + } + } + + removeAttributeNS(namespace: string | null, localName: string): void { + const attr = this.getNamedItemNS(namespace, localName); + if (attr) { + this.removeAttributeNode(attr); + } + } + + toggleAttribute(name: string, force?: boolean): boolean { + const normal = this.#normalizeName(name); + validateAttributeName(normal); + const attr = this.getNamedItem(normal); + if (attr) { + if (force !== undefined && force) { + return true; + } else { + this.removeAttributeNode(attr); + return false; + } + } + if (force !== undefined && !force) { + return false; + } + this.setAttribute(normal, ''); + return true; + } + + getAttributeNames(): string[] { + return this.#attributes.map((attr) => attr.name); + } + + #normalizeName(name: string): string { + return this.#ownerElement.namespaceURI === HTML_NS ? asciiLowercase(`${name}`) : `${name}`; + } + + #changed(): void { + // Rebuild the indexed and named views when the ordered list changes. + for (const key of this.#properties) Reflect.deleteProperty(this, key); + this.#properties = []; + for (const [index, attr] of this.#attributes.entries()) { + const key = `${index}`; + Object.defineProperty(this, key, { value: attr, enumerable: true, configurable: true }); + this.#properties.push(key); + } + for (const attr of this.#attributes) { + const name = attr.name; + if (name in this || this.#normalizeName(name) !== name || /^(0|[1-9][0-9]*)$/.test(name)) { + continue; + } + Object.defineProperty(this, name, { value: attr, configurable: true }); + this.#properties.push(name); + } + this.#notify(); + } +} diff --git a/packages/ui/src/validation.ts b/packages/ui/src/validation.ts index f4d6c4f..e7ed5c3 100644 --- a/packages/ui/src/validation.ts +++ b/packages/ui/src/validation.ts @@ -14,6 +14,32 @@ export function validateElementName(localName: string): void { export function validateElementNamespace( namespaceURI: string | null, qualifiedName: string, +): { prefix: string | null; localName: string } { + return validateNamespace(namespaceURI, { qualifiedName, validateLocalName: validateElementName }); +} + +export function validateAttributeName(localName: string): void { + if (!/^[^\0\t\n\f\r\u0020/=>]+$/u.test(localName)) { + throw new DOMException('Invalid attribute name', 'InvalidCharacterError'); + } +} + +export function validateAttributeNamespace( + namespaceURI: string | null, + qualifiedName: string, +): { prefix: string | null; localName: string } { + return validateNamespace(namespaceURI, { + qualifiedName, + validateLocalName: validateAttributeName, + }); +} + +function validateNamespace( + namespaceURI: string | null, + { + qualifiedName, + validateLocalName, + }: { qualifiedName: string; validateLocalName: (localName: string) => void }, ): { prefix: string | null; localName: string } { const colonIndex = qualifiedName.indexOf(':'); const prefix = colonIndex < 0 ? null : qualifiedName.slice(0, colonIndex); @@ -22,7 +48,7 @@ export function validateElementNamespace( if (prefix !== null && !/^[^\0\t\n\f\r\u0020/>]+$/u.test(prefix)) { throw new DOMException('Invalid namespace prefix', 'InvalidCharacterError'); } - validateElementName(localName); + validateLocalName(localName); if ( (prefix !== null && namespaceURI === null) || (prefix === 'xml' && namespaceURI !== XML_NS) || diff --git a/packages/ui/test/wpt.config.ts b/packages/ui/test/wpt.config.ts index ab047bc..1e38750 100644 --- a/packages/ui/test/wpt.config.ts +++ b/packages/ui/test/wpt.config.ts @@ -1,5 +1,6 @@ import type { WPTConfig } from '@bomb.sh/web-platform-tests'; import { + Attr, CharacterData, Comment, Document, @@ -10,9 +11,11 @@ import { Node, Text, } from '../src/dom.ts'; +import { NamedNodeMap } from '../src/named-node-map.ts'; export default { globals: { + Attr, CharacterData, Comment, Document, @@ -21,6 +24,7 @@ export default { HTMLElement, HTMLSpanElement, HTMLUnknownElement, + NamedNodeMap, Node, Text, }, @@ -29,9 +33,84 @@ export default { 'dom/nodes/Document-createElement.html': true, 'dom/nodes/Document-createElementNS.html': true, 'dom/nodes/Document-createComment.html': true, + // XML factory cases require DOMImplementation.createDocument. + 'dom/nodes/Document-createAttribute.html': [/^HTML document\.createAttribute\(/], 'dom/nodes/CharacterData-data.html': true, 'dom/nodes/CharacterData-remove.html': true, 'dom/nodes/Element-remove.html': true, + 'dom/nodes/Element-setAttribute.html': true, + 'dom/nodes/Element-setAttributeNodeNS.html': true, + '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/attributes-namednodemap.html': true, + // Excludes cases requiring XML documents, CSS style reflection, document + // fragments, parsed fixtures, or attachment to document.body. + 'dom/nodes/attributes.html': [ + 'Attribute loses its owner when removed', + 'Basic functionality of getAttributeNode/getAttributeNodeNS', + 'Basic functionality of setAttributeNode', + 'setAttributeNode should distinguish attributes with same local name and different namespaces', + "setAttributeNode doesn't have case-insensitivity even with an HTMLElement 1", + "setAttributeNode doesn't have case-insensitivity even with an HTMLElement 2", + "setAttributeNode doesn't have case-insensitivity even with an HTMLElement 3", + 'Basic functionality of setAttributeNodeNS', + 'If attr’s element is neither null nor element, throw an InUseAttributeError.', + 'Replacing an attr by itself', + 'Basic functionality of removeAttributeNode', + 'setAttributeNode on bound attribute should throw InUseAttributeError', + 'setAttributeNode called with an Attr that has the same name as an existing one should not change attribute order', + 'Own property correctness with basic attributes', + 'Own property correctness with non-namespaced attribute before same-name namespaced one', + 'Own property correctness with namespaced attribute before same-name non-namespaced one', + 'Own property correctness with two namespaced attributes with the same name-with-prefix', + 'Own property names should only include all-lowercase qualified names for an HTML element in an HTML document', + 'Own property names should include all qualified names for a non-HTML element in an HTML document', + 'When qualifiedName does not match the Name production, an INVALID_CHARACTER_ERR exception is to be thrown. (toggleAttribute)', + 'toggleAttribute should lowercase its name argument (upper case attribute)', + 'toggleAttribute should lowercase its name argument (mixed case attribute)', + "toggleAttribute should not throw even when qualifiedName starts with 'xmlns'", + 'Basic functionality should be intact. (toggleAttribute)', + 'toggleAttribute should not change the order of previously set attributes.', + 'toggleAttribute should set the first attribute with the given name', + 'toggleAttribute should set the attribute with the given qualified name', + 'When qualifiedName does not match the Name production, an INVALID_CHARACTER_ERR exception is to be thrown. (setAttribute)', + 'setAttribute should lowercase its name argument (upper case attribute)', + 'setAttribute should lowercase its name argument (mixed case attribute)', + "setAttribute should not throw even when qualifiedName starts with 'xmlns'", + 'Basic functionality should be intact.', + 'setAttribute should not change the order of previously set attributes.', + 'setAttribute should set the first attribute with the given name', + 'setAttribute should set the attribute with the given qualified name', + 'When qualifiedName does not match the Name production, an INVALID_CHARACTER_ERR exception is to be thrown. (setAttributeNS)', + 'When qualifiedName does not match the QName production, an INVALID_CHARACTER_ERR exception is to be thrown.', + 'null and the empty string should result in a null namespace.', + 'A namespace is required to use a prefix.', + 'The xml prefix should not be allowed for arbitrary namespaces', + "XML-namespaced attributes don't need an xml prefix", + 'The xmlns prefix should not be allowed for arbitrary namespaces', + 'The xmlns qualified name should not be allowed for arbitrary namespaces', + 'xmlns should be allowed as local name', + 'The XMLNS namespace should require xmlns as prefix or qualified name', + 'xmlns should be allowed as prefix in the XMLNS namespace', + 'xmlns should be allowed as qualified name in the XMLNS namespace', + '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.', + '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 later', + 'Non-HTML element with upper-case attribute', + 'Attribute with prefix in local name', + 'getAttributeNames tests', + ], 'dom/nodes/Node-nodeValue.html': ['Text.nodeValue', 'Comment.nodeValue'], 'dom/nodes/Node-textContent.html': [ 'For an empty Text, textContent should be the empty string', diff --git a/packages/web-platform-tests/docs/omissions.md b/packages/web-platform-tests/docs/omissions.md index e2694aa..77c63bc 100644 --- a/packages/web-platform-tests/docs/omissions.md +++ b/packages/web-platform-tests/docs/omissions.md @@ -10,6 +10,7 @@ the upstream WPT root. Consumer exclusions in `wpt.config.ts` are separate. | `dom/nodes/Element-webkitMatchesSelector.html` | Entire file. | Vendor-prefixed alias; coverage targets standard `matches`. | | `dom/nodes/Element-matches-namespaced-elements.html` | The `webkitMatchesSelector` rows. | Vendor-prefixed alias. | | `dom/nodes/ParentNode-querySelector-All.html`, `dom/nodes/ParentNode-querySelector-All-xht.xht`, `dom/nodes/Element-matches.html` | Unnamed iframe-loader cases. | The consumer's document factory replaces upstream fixture loading; behavioral subtests remain. | +| `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. | | `domparsing/createContextualFragment.html` | `