Skip to content

Commit 2304ce2

Browse files
committed
Add HTMLElement.dataset backed by DOMStringMap
1 parent db84ffe commit 2304ce2

4 files changed

Lines changed: 173 additions & 0 deletions

File tree

‎.changeset/dom-dataset.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clack/ui': minor
3+
---
4+
5+
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.

‎packages/ui/src/dom-string-map.ts‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
import type { Attr, Element } from './dom.ts';
2+
import { validateAttributeName } from './validation.ts';
3+
4+
/**
5+
* A live view of an element's data-* attributes.
6+
* https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap
7+
*/
8+
export class DOMStringMap {
9+
[name: string]: string | undefined;
10+
11+
constructor(element: Element) {
12+
const map: DOMStringMap = new Proxy(this, {
13+
get(target, key, receiver) {
14+
if (typeof key === 'string') {
15+
const attribute = getNamedAttributes(element).get(key);
16+
if (attribute) {
17+
return attribute.value;
18+
}
19+
}
20+
return Reflect.get(target, key, receiver);
21+
},
22+
23+
has(target, key) {
24+
return (
25+
(typeof key === 'string' && getNamedAttributes(element).has(key)) ||
26+
Reflect.has(target, key)
27+
);
28+
},
29+
30+
set(target, key, value, receiver) {
31+
if (typeof key === 'string' && receiver === map) {
32+
setNamedValue(element, { name: key, value });
33+
return true;
34+
}
35+
return Reflect.set(target, key, value, receiver);
36+
},
37+
38+
deleteProperty(target, key) {
39+
if (typeof key === 'string') {
40+
const attribute = getNamedAttributes(element).get(key);
41+
if (attribute) element.removeAttributeNode(attribute);
42+
return true;
43+
}
44+
return Reflect.deleteProperty(target, key);
45+
},
46+
47+
ownKeys(target) {
48+
return [...getNamedAttributes(element).keys(), ...Reflect.ownKeys(target)];
49+
},
50+
51+
getOwnPropertyDescriptor(target, key) {
52+
if (typeof key === 'string') {
53+
const attribute = getNamedAttributes(element).get(key);
54+
if (attribute) {
55+
return {
56+
value: attribute.value,
57+
writable: true,
58+
enumerable: true,
59+
configurable: true,
60+
};
61+
}
62+
}
63+
return Reflect.getOwnPropertyDescriptor(target, key);
64+
},
65+
66+
defineProperty(target, key, descriptor) {
67+
if (typeof key === 'symbol') {
68+
return Reflect.defineProperty(target, key, descriptor);
69+
}
70+
if (!('value' in descriptor || 'writable' in descriptor)) {
71+
return false;
72+
}
73+
74+
// A Proxy cannot expose a virtual, non-configurable property. Unlike
75+
// native DOMStringMap, reject this request before changing attributes.
76+
if (descriptor.configurable === false) return false;
77+
setNamedValue(element, { name: key, value: descriptor.value });
78+
return true;
79+
},
80+
81+
// Attribute changes can always introduce new properties.
82+
preventExtensions() {
83+
return false;
84+
},
85+
});
86+
return map;
87+
}
88+
}
89+
90+
Object.defineProperty(DOMStringMap.prototype, Symbol.toStringTag, {
91+
value: 'DOMStringMap',
92+
configurable: true,
93+
});
94+
95+
function getNamedAttributes(element: Element): Map<string, Attr> {
96+
const named = new Map<string, Attr>();
97+
const attributes = element.attributes;
98+
for (let index = 0; index < attributes.length; index++) {
99+
const attribute = attributes[index]!;
100+
101+
if (!attribute.name.startsWith('data-')) {
102+
continue;
103+
}
104+
105+
const suffix = attribute.name.slice(5);
106+
if (/[A-Z]/.test(suffix)) {
107+
continue;
108+
}
109+
110+
const name = suffix.replace(/-[a-z]/g, (match) => match[1]!.toUpperCase());
111+
112+
if (!named.has(name)) {
113+
named.set(name, attribute);
114+
}
115+
}
116+
return named;
117+
}
118+
119+
function setNamedValue(element: Element, { name, value }: { name: string; value: unknown }): void {
120+
// Web IDL converts the value before the named setter validates the key.
121+
const stringValue = `${value}`;
122+
if (/-[a-z]/.test(name)) {
123+
throw new DOMException(
124+
'Dataset names cannot contain a dash followed by a lowercase letter',
125+
'SyntaxError',
126+
);
127+
}
128+
const attributeName = `data-${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
129+
validateAttributeName(attributeName);
130+
const attribute = element.getAttributeNodeNS(null, attributeName);
131+
if (attribute) {
132+
attribute.value = stringValue;
133+
} else {
134+
// Dataset writes use the null namespace. Creating an Attr directly also
135+
// permits colons in names without treating them as namespace prefixes.
136+
const created = element.ownerDocument.createAttribute(attributeName);
137+
created.value = stringValue;
138+
element.setAttributeNodeNS(created);
139+
}
140+
}

‎packages/ui/src/dom.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
validateAttributeNamespace,
1111
validateDocumentTypeName,
1212
} from './validation.ts';
13+
import { DOMStringMap } from './dom-string-map.ts';
1314

1415
const HTML_NS = 'http://www.w3.org/1999/xhtml';
1516

@@ -798,6 +799,12 @@ export class HTMLElement extends Element {
798799
#onfocus: EventListener | undefined = undefined;
799800
#onblur: EventListener | undefined = undefined;
800801

802+
#dataset = new DOMStringMap(this);
803+
804+
get dataset(): DOMStringMap {
805+
return this.#dataset;
806+
}
807+
801808
get inert(): boolean {
802809
return this.hasAttributeNS(null, 'inert');
803810
}

‎packages/ui/wpt.config.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
XMLDocument,
2020
} from './src/dom.ts';
2121
import { NamedNodeMap } from './src/named-node-map.ts';
22+
import { DOMStringMap } from './src/dom-string-map.ts';
2223

2324
const config: WPTConfig = {
2425
createDocument: () => createHTMLDocument(() => {}),
@@ -31,6 +32,7 @@ const config: WPTConfig = {
3132
Document,
3233
DocumentType,
3334
DOMException: globalThis.DOMException,
35+
DOMStringMap,
3436
Element,
3537
Event: globalThis.Event,
3638
EventTarget: globalThis.EventTarget,
@@ -47,6 +49,25 @@ const config: WPTConfig = {
4749
XMLDocument,
4850
},
4951
include: {
52+
'html/dom/elements/global-attributes/dataset.html': [
53+
'HTML elements should have a .dataset',
54+
"Should return 'undefined' before setting an attribute",
55+
"Should return 'value' if that's the value",
56+
"Should return the empty string if that's the value",
57+
"Should return 'undefined' after removing an attribute",
58+
'Should not have a .dataset on random elements',
59+
// SVG and MathML coverage awaits their element interfaces.
60+
],
61+
'html/dom/elements/global-attributes/dataset-get.html': true,
62+
'html/dom/elements/global-attributes/dataset-get-invalid-names.html': true,
63+
'html/dom/elements/global-attributes/dataset-set.html': true,
64+
'html/dom/elements/global-attributes/dataset-delete.html': true,
65+
'html/dom/elements/global-attributes/dataset-enumeration.html': true,
66+
'html/dom/elements/global-attributes/dataset-prototype.html': true,
67+
'html/dom/elements/global-attributes/dataset-binding.window.js': true,
68+
'html/dom/elements/global-attributes/custom-attrs.html': true,
69+
'html/dom/elements/global-attributes/data_unicode_attr.html': true,
70+
'dom/collections/domstringmap-supported-property-names.html': true,
5071
'html/dom/elements/global-attributes/id-name.html': true,
5172
'html/dom/elements/global-attributes/id-attribute.html': [
5273
'After setting id via id attribute, getElementById find the element by the new id.',

0 commit comments

Comments
 (0)