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-dataset.md
Original file line number Diff line number Diff line change
@@ -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.
140 changes: 140 additions & 0 deletions packages/ui/src/dom-string-map.ts
Original file line number Diff line number Diff line change
@@ -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<string, Attr> {
const named = new Map<string, Attr>();
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);
}
}
7 changes: 7 additions & 0 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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');
}
Expand Down
21 changes: 21 additions & 0 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {}),
Expand All @@ -35,6 +36,7 @@ const config: WPTConfig = {
DocumentFragment,
DocumentType,
DOMException: globalThis.DOMException,
DOMStringMap,
Element,
Event: globalThis.Event,
EventTarget: globalThis.EventTarget,
Expand All @@ -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.',
Expand Down