From 9e5e01a2d2e0d597bd0925a7ef5fe079038eb6f7 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Wed, 18 Nov 2026 10:59:18 -0600 Subject: [PATCH] Add HTMLElement.dataset backed by DOMStringMap --- .changeset/dom-dataset.md | 5 ++ packages/ui/src/dom-string-map.ts | 140 ++++++++++++++++++++++++++++++ packages/ui/src/dom.ts | 7 ++ packages/ui/wpt.config.ts | 21 +++++ 4 files changed, 173 insertions(+) create mode 100644 .changeset/dom-dataset.md create mode 100644 packages/ui/src/dom-string-map.ts diff --git a/.changeset/dom-dataset.md b/.changeset/dom-dataset.md new file mode 100644 index 0000000..91b5ee2 --- /dev/null +++ b/.changeset/dom-dataset.md @@ -0,0 +1,5 @@ +--- +'@clack/ui': minor +--- + +Add [HTMLElement.dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) as a live [DOMStringMap](https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap) backed by the element's data attributes. diff --git a/packages/ui/src/dom-string-map.ts b/packages/ui/src/dom-string-map.ts new file mode 100644 index 0000000..8d7eae7 --- /dev/null +++ b/packages/ui/src/dom-string-map.ts @@ -0,0 +1,140 @@ +import type { Attr, Element } from './dom.ts'; +import { validateAttributeName } from './validation.ts'; + +/** + * A live view of an element's data-* attributes. + * https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap + */ +export class DOMStringMap { + [name: string]: string | undefined; + + constructor(element: Element) { + const map: DOMStringMap = new Proxy(this, { + get(target, key, receiver) { + if (typeof key === 'string') { + const attribute = getNamedAttributes(element).get(key); + if (attribute) { + return attribute.value; + } + } + return Reflect.get(target, key, receiver); + }, + + has(target, key) { + return ( + (typeof key === 'string' && getNamedAttributes(element).has(key)) || + Reflect.has(target, key) + ); + }, + + set(target, key, value, receiver) { + if (typeof key === 'string' && receiver === map) { + setNamedValue(element, { name: key, value }); + return true; + } + return Reflect.set(target, key, value, receiver); + }, + + deleteProperty(target, key) { + if (typeof key === 'string') { + const attribute = getNamedAttributes(element).get(key); + if (attribute) element.removeAttributeNode(attribute); + return true; + } + return Reflect.deleteProperty(target, key); + }, + + ownKeys(target) { + return [...getNamedAttributes(element).keys(), ...Reflect.ownKeys(target)]; + }, + + getOwnPropertyDescriptor(target, key) { + if (typeof key === 'string') { + const attribute = getNamedAttributes(element).get(key); + if (attribute) { + return { + value: attribute.value, + writable: true, + enumerable: true, + configurable: true, + }; + } + } + return Reflect.getOwnPropertyDescriptor(target, key); + }, + + defineProperty(target, key, descriptor) { + if (typeof key === 'symbol') { + return Reflect.defineProperty(target, key, descriptor); + } + if (!('value' in descriptor || 'writable' in descriptor)) { + return false; + } + + // A Proxy cannot expose a virtual, non-configurable property. Unlike + // native DOMStringMap, reject this request before changing attributes. + if (descriptor.configurable === false) return false; + setNamedValue(element, { name: key, value: descriptor.value }); + return true; + }, + + // Attribute changes can always introduce new properties. + preventExtensions() { + return false; + }, + }); + return map; + } +} + +Object.defineProperty(DOMStringMap.prototype, Symbol.toStringTag, { + value: 'DOMStringMap', + configurable: true, +}); + +function getNamedAttributes(element: Element): Map { + const named = new Map(); + const attributes = element.attributes; + for (let index = 0; index < attributes.length; index++) { + const attribute = attributes[index]!; + + if (!attribute.name.startsWith('data-')) { + continue; + } + + const suffix = attribute.name.slice(5); + if (/[A-Z]/.test(suffix)) { + continue; + } + + const name = suffix.replace(/-[a-z]/g, (match) => match[1]!.toUpperCase()); + + if (!named.has(name)) { + named.set(name, attribute); + } + } + return named; +} + +function setNamedValue(element: Element, { name, value }: { name: string; value: unknown }): void { + // Web IDL converts the value before the named setter validates the key. + const stringValue = `${value}`; + if (/-[a-z]/.test(name)) { + throw new DOMException( + 'Dataset names cannot contain a dash followed by a lowercase letter', + 'SyntaxError', + ); + } + const attributeName = `data-${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`; + validateAttributeName(attributeName); + const attribute = element.getAttributeNodeNS(null, attributeName); + if (attribute) { + attribute.value = stringValue; + } else { + // Dataset writes use the null namespace. Creating an Attr directly also + // permits colons in names without treating them as namespace prefixes. + const created = element.ownerDocument.createAttribute(attributeName); + created.value = stringValue; + element.setAttributeNodeNS(created); + } +} diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 91a12cd..19750e0 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -11,6 +11,7 @@ import { validateAttributeNamespace, validateDocumentTypeName, } from './validation.ts'; +import { DOMStringMap } from './dom-string-map.ts'; const HTML_NS = 'http://www.w3.org/1999/xhtml'; @@ -863,6 +864,12 @@ export class HTMLElement extends Element { #onfocus: EventListener | undefined = undefined; #onblur: EventListener | undefined = undefined; + #dataset = new DOMStringMap(this); + + get dataset(): DOMStringMap { + return this.#dataset; + } + get inert(): boolean { return this.hasAttributeNS(null, 'inert'); } diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index dd084f8..7816cb6 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -22,6 +22,7 @@ import { } from './src/dom.ts'; import { NamedNodeMap } from './src/named-node-map.ts'; import { HTMLCollection } from './src/html-collection.ts'; +import { DOMStringMap } from './src/dom-string-map.ts'; const config: WPTConfig = { createDocument: () => createHTMLDocument(() => {}), @@ -35,6 +36,7 @@ const config: WPTConfig = { DocumentFragment, DocumentType, DOMException: globalThis.DOMException, + DOMStringMap, Element, Event: globalThis.Event, EventTarget: globalThis.EventTarget, @@ -53,6 +55,25 @@ const config: WPTConfig = { XMLDocument, }, include: { + 'html/dom/elements/global-attributes/dataset.html': [ + 'HTML elements should have a .dataset', + "Should return 'undefined' before setting an attribute", + "Should return 'value' if that's the value", + "Should return the empty string if that's the value", + "Should return 'undefined' after removing an attribute", + 'Should not have a .dataset on random elements', + // SVG and MathML coverage awaits their element interfaces. + ], + 'html/dom/elements/global-attributes/dataset-get.html': true, + 'html/dom/elements/global-attributes/dataset-get-invalid-names.html': true, + 'html/dom/elements/global-attributes/dataset-set.html': true, + 'html/dom/elements/global-attributes/dataset-delete.html': true, + 'html/dom/elements/global-attributes/dataset-enumeration.html': true, + 'html/dom/elements/global-attributes/dataset-prototype.html': true, + 'html/dom/elements/global-attributes/dataset-binding.window.js': true, + 'html/dom/elements/global-attributes/custom-attrs.html': true, + 'html/dom/elements/global-attributes/data_unicode_attr.html': true, + 'dom/collections/domstringmap-supported-property-names.html': true, '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.',