Repository: sveltejs/svelte (JavaScript) — Refactoring

Issue:
Use el.dataset.foo = bar instead of setAttribute(el, 'data-foo', bar)
[REPL](https://svelte.technology/repl?version=1.39.3&gist=c9f289fc5bd3af71d2137b3a8315b320). `dataset` is supported in all current browsers — we should probably generate this code...

```js
div.dataset.foo = "bar";
```

...instead of this...

```js
setAttribute(div, "data-foo", "bar");
```

...unless the `legacy` option is set.


Discussion:

Resolving patch:
diff --git a/src/generators/dom/visitors/Element/Attribute.ts b/src/generators/dom/visitors/Element/Attribute.ts
--- a/src/generators/dom/visitors/Element/Attribute.ts
+++ b/src/generators/dom/visitors/Element/Attribute.ts
@@ -3,7 +3,6 @@ import deindent from '../../../../utils/deindent';
 import visitStyleAttribute, { optimizeStyle } from './StyleAttribute';
 import { stringify } from '../../../../utils/stringify';
 import getExpressionPrecedence from '../../../../utils/getExpressionPrecedence';
-import getStaticAttributeValue from '../../../../utils/getStaticAttributeValue';
 import { DomGenerator } from '../../index';
 import Block from '../../Block';
 import { Node } from '../../../../interfaces';
@@ -56,6 +55,11 @@ export default function visitAttribute(
 
 	const isLegacyInputType = generator.legacy && name === 'type' && node.name === 'input';
 
+	const isDataSet = /^data-/.test(name) && !generator.legacy;
+	const camelCaseName = isDataSet ? name.replace('data-', '').replace(/(-\w)/g, function (m) {
+		return m[1].toUpperCase();
+	}) : name;
+
 	if (isDynamic) {
 		let value;
 
@@ -163,6 +167,11 @@ export default function visitAttribute(
 				`${state.parentNode}.${propertyName} = ${init};`
 			);
 			updater = `${state.parentNode}.${propertyName} = ${shouldCache || isSelectValueAttribute ? last : value};`;
+		} else if (isDataSet) {
+			block.builders.hydrate.addLine(
+				`${state.parentNode}.dataset.${camelCaseName} = ${init};`
+			);
+			updater = `${state.parentNode}.dataset.${camelCaseName} = ${shouldCache || isSelectValueAttribute ? last : value};`;
 		} else {
 			block.builders.hydrate.addLine(
 				`${method}(${state.parentNode}, "${name}", ${init});`
@@ -198,6 +207,7 @@ export default function visitAttribute(
 		const statement = (
 			isLegacyInputType ? `@setInputType(${state.parentNode}, ${value});` :
 			propertyName ? `${state.parentNode}.${propertyName} = ${value};` :
+				isDataSet ? `${state.parentNode}.dataset.${camelCaseName} = ${value};` :
 			`${method}(${state.parentNode}, "${name}", ${value});`
 		);
 
@@ -221,4 +231,4 @@ export default function visitAttribute(
 		block.builders.hydrate.addLine(updateValue);
 		if (isDynamic) block.builders.update.addLine(updateValue);
 	}
-}
\ No newline at end of file
+}


Test patch:
diff --git a/test/js/samples/do-use-dataset/expected-bundle.js b/test/js/samples/do-use-dataset/expected-bundle.js
new file mode 100644
--- /dev/null
+++ b/test/js/samples/do-use-dataset/expected-bundle.js
@@ -0,0 +1,236 @@
+function noop() {}
+
+function assign(target) {
+	var k,
+		source,
+		i = 1,
+		len = arguments.length;
+	for (; i < len; i++) {
+		source = arguments[i];
+		for (k in source) target[k] = source[k];
+	}
+
+	return target;
+}
+
+function insertNode(node, target, anchor) {
+	target.insertBefore(node, anchor);
+}
+
+function detachNode(node) {
+	node.parentNode.removeChild(node);
+}
+
+function createElement(name) {
+	return document.createElement(name);
+}
+
+function createText(data) {
+	return document.createTextNode(data);
+}
+
+function blankObject() {
+	return Object.create(null);
+}
+
+function destroy(detach) {
+	this.destroy = noop;
+	this.fire('destroy');
+	this.set = this.get = noop;
+
+	if (detach !== false) this._fragment.u();
+	this._fragment.d();
+	this._fragment = this._state = null;
+}
+
+function differs(a, b) {
+	return a !== b || ((a && typeof a === 'object') || typeof a === 'function');
+}
+
+function dispatchObservers(component, group, changed, newState, oldState) {
+	for (var key in group) {
+		if (!changed[key]) continue;
+
+		var newValue = newState[key];
+		var oldValue = oldState[key];
+
+		var callbacks = group[key];
+		if (!callbacks) continue;
+
+		for (var i = 0; i < callbacks.length; i += 1) {
+			var callback = callbacks[i];
+			if (callback.__calling) continue;
+
+			callback.__calling = true;
+			callback.call(component, newValue, oldValue);
+			callback.__calling = false;
+		}
+	}
+}
+
+function fire(eventName, data) {
+	var handlers =
+		eventName in this._handlers && this._handlers[eventName].slice();
+	if (!handlers) return;
+
+	for (var i = 0; i < handlers.length; i += 1) {
+		handlers[i].call(this, data);
+	}
+}
+
+function get(key) {
+	return key ? this._state[key] : this._state;
+}
+
+function init(component, options) {
+	component.options = options;
+
+	component._observers = { pre: blankObject(), post: blankObject() };
+	component._handlers = blankObject();
+	component._root = options._root || component;
+	component._bind = options._bind;
+}
+
+function observe(key, callback, options) {
+	var group = options && options.defer
+		? this._observers.post
+		: this._observers.pre;
+
+	(group[key] || (group[key] = [])).push(callback);
+
+	if (!options || options.init !== false) {
+		callback.__calling = true;
+		callback.call(this, this._state[key]);
+		callback.__calling = false;
+	}
+
+	return {
+		cancel: function() {
+			var index = group[key].indexOf(callback);
+			if (~index) group[key].splice(index, 1);
+		}
+	};
+}
+
+function on(eventName, handler) {
+	if (eventName === 'teardown') return this.on('destroy', handler);
+
+	var handlers = this._handlers[eventName] || (this._handlers[eventName] = []);
+	handlers.push(handler);
+
+	return {
+		cancel: function() {
+			var index = handlers.indexOf(handler);
+			if (~index) handlers.splice(index, 1);
+		}
+	};
+}
+
+function set(newState) {
+	this._set(assign({}, newState));
+	if (this._root._lock) return;
+	this._root._lock = true;
+	callAll(this._root._beforecreate);
+	callAll(this._root._oncreate);
+	callAll(this._root._aftercreate);
+	this._root._lock = false;
+}
+
+function _set(newState) {
+	var oldState = this._state,
+		changed = {},
+		dirty = false;
+
+	for (var key in newState) {
+		if (differs(newState[key], oldState[key])) changed[key] = dirty = true;
+	}
+	if (!dirty) return;
+
+	this._state = assign({}, oldState, newState);
+	this._recompute(changed, this._state);
+	if (this._bind) this._bind(changed, this._state);
+	dispatchObservers(this, this._observers.pre, changed, this._state, oldState);
+	this._fragment.p(changed, this._state);
+	dispatchObservers(this, this._observers.post, changed, this._state, oldState);
+}
+
+function callAll(fns) {
+	while (fns && fns.length) fns.pop()();
+}
+
+function _mount(target, anchor) {
+	this._fragment.m(target, anchor);
+}
+
+function _unmount() {
+	this._fragment.u();
+}
+
+var proto = {
+	destroy: destroy,
+	get: get,
+	fire: fire,
+	observe: observe,
+	on: on,
+	set: set,
+	teardown: destroy,
+	_recompute: noop,
+	_set: _set,
+	_mount: _mount,
+	_unmount: _unmount
+};
+
+/* generated by Svelte vX.Y.Z */
+function create_main_fragment(state, component) {
+	var div, text, div_1;
+
+	return {
+		c: function create() {
+			div = createElement("div");
+			text = createText("\n");
+			div_1 = createElement("div");
+			this.h();
+		},
+
+		h: function hydrate() {
+			div.dataset.foo = "bar";
+			div_1.dataset.foo = state.bar;
+		},
+
+		m: function mount(target, anchor) {
+			insertNode(div, target, anchor);
+			insertNode(text, target, anchor);
+			insertNode(div_1, target, anchor);
+		},
+
+		p: function update(changed, state) {
+			if (changed.bar) {
+				div_1.dataset.foo = state.bar;
+			}
+		},
+
+		u: function unmount() {
+			detachNode(div);
+			detachNode(text);
+			detachNode(div_1);
+		},
+
+		d: noop
+	};
+}
+
+function SvelteComponent(options) {
+	init(this, options);
+	this._state = assign({}, options.data);
+
+	this._fragment = create_main_fragment(this._state, this);
+
+	if (options.target) {
+		this._fragment.c();
+		this._fragment.m(options.target, options.anchor || null);
+	}
+}
+
+assign(SvelteComponent.prototype, proto);
+
+export default SvelteComponent;
diff --git a/test/js/samples/do-use-dataset/expected.js b/test/js/samples/do-use-dataset/expected.js
new file mode 100644
--- /dev/null
+++ b/test/js/samples/do-use-dataset/expected.js
@@ -0,0 +1,55 @@
+/* generated by Svelte vX.Y.Z */
+import { assign, createElement, createText, detachNode, init, insertNode, noop, proto } from "svelte/shared.js";
+
+function create_main_fragment(state, component) {
+	var div, text, div_1;
+
+	return {
+		c: function create() {
+			div = createElement("div");
+			text = createText("\n");
+			div_1 = createElement("div");
+			this.h();
+		},
+
+		h: function hydrate() {
+			div.dataset.foo = "bar";
+			div_1.dataset.foo = state.bar;
+		},
+
+		m: function mount(target, anchor) {
+			insertNode(div, target, anchor);
+			insertNode(text, target, anchor);
+			insertNode(div_1, target, anchor);
+		},
+
+		p: function update(changed, state) {
+			if (changed.bar) {
+				div_1.dataset.foo = state.bar;
+			}
+		},
+
+		u: function unmount() {
+			detachNode(div);
+			detachNode(text);
+			detachNode(div_1);
+		},
+
+		d: noop
+	};
+}
+
+function SvelteComponent(options) {
+	init(this, options);
+	this._state = assign({}, options.data);
+
+	this._fragment = create_main_fragment(this._state, this);
+
+	if (options.target) {
+		this._fragment.c();
+		this._fragment.m(options.target, options.anchor || null);
+	}
+}
+
+assign(SvelteComponent.prototype, proto);
+export default SvelteComponent;
diff --git a/test/js/samples/do-use-dataset/input.html b/test/js/samples/do-use-dataset/input.html
new file mode 100644
--- /dev/null
+++ b/test/js/samples/do-use-dataset/input.html
@@ -0,0 +1,2 @@
+<div data-foo='bar'/>
+<div data-foo='{{bar}}'/>
diff --git a/test/js/samples/dont-use-dataset-in-legacy/_config.js b/test/js/samples/dont-use-dataset-in-legacy/_config.js
new file mode 100644
--- /dev/null
+++ b/test/js/samples/dont-use-dataset-in-legacy/_config.js
@@ -0,0 +1,5 @@
+export default {
+	options: {
+		legacy: true
+	}
+};
diff --git a/test/js/samples/dont-use-dataset-in-legacy/expected-bundle.js b/test/js/samples/dont-use-dataset-in-legacy/expected-bundle.js
new file mode 100644
--- /dev/null
+++ b/test/js/samples/dont-use-dataset-in-legacy/expected-bundle.js
@@ -0,0 +1,240 @@
+function noop() {}
+
+function assign(target) {
+	var k,
+		source,
+		i = 1,
+		len = arguments.length;
+	for (; i < len; i++) {
+		source = arguments[i];
+		for (k in source) target[k] = source[k];
+	}
+
+	return target;
+}
+
+function insertNode(node, target, anchor) {
+	target.insertBefore(node, anchor);
+}
+
+function detachNode(node) {
+	node.parentNode.removeChild(node);
+}
+
+function createElement(name) {
+	return document.createElement(name);
+}
+
+function createText(data) {
+	return document.createTextNode(data);
+}
+
+function setAttribute(node, attribute, value) {
+	node.setAttribute(attribute, value);
+}
+
+function blankObject() {
+	return Object.create(null);
+}
+
+function destroy(detach) {
+	this.destroy = noop;
+	this.fire('destroy');
+	this.set = this.get = noop;
+
+	if (detach !== false) this._fragment.u();
+	this._fragment.d();
+	this._fragment = this._state = null;
+}
+
+function differs(a, b) {
+	return a !== b || ((a && typeof a === 'object') || typeof a === 'function');
+}
+
+function dispatchObservers(component, group, changed, newState, oldState) {
+	for (var key in group) {
+		if (!changed[key]) continue;
+
+		var newValue = newState[key];
+		var oldValue = oldState[key];
+
+		var callbacks = group[key];
+		if (!callbacks) continue;
+
+		for (var i = 0; i < callbacks.length; i += 1) {
+			var callback = callbacks[i];
+			if (callback.__calling) continue;
+
+			callback.__calling = true;
+			callback.call(component, newValue, oldValue);
+			callback.__calling = false;
+		}
+	}
+}
+
+function fire(eventName, data) {
+	var handlers =
+		eventName in this._handlers && this._handlers[eventName].slice();
+	if (!handlers) return;
+
+	for (var i = 0; i < handlers.length; i += 1) {
+		handlers[i].call(this, data);
+	}
+}
+
+function get(key) {
+	return key ? this._state[key] : this._state;
+}
+
+function init(component, options) {
+	component.options = options;
+
+	component._observers = { pre: blankObject(), post: blankObject() };
+	component._handlers = blankObject();
+	component._root = options._root || component;
+	component._bind = options._bind;
+}
+
+function observe(key, callback, options) {
+	var group = options && options.defer
+		? this._observers.post
+		: this._observers.pre;
+
+	(group[key] || (group[key] = [])).push(callback);
+
+	if (!options || options.init !== false) {
+		callback.__calling = true;
+		callback.call(this, this._state[key]);
+		callback.__calling = false;
+	}
+
+	return {
+		cancel: function() {
+			var index = group[key].indexOf(callback);
+			if (~index) group[key].splice(index, 1);
+		}
+	};
+}
+
+function on(eventName, handler) {
+	if (eventName === 'teardown') return this.on('destroy', handler);
+
+	var handlers = this._handlers[eventName] || (this._handlers[eventName] = []);
+	handlers.push(handler);
+
+	return {
+		cancel: function() {
+			var index = handlers.indexOf(handler);
+			if (~index) handlers.splice(index, 1);
+		}
+	};
+}
+
+function set(newState) {
+	this._set(assign({}, newState));
+	if (this._root._lock) return;
+	this._root._lock = true;
+	callAll(this._root._beforecreate);
+	callAll(this._root._oncreate);
+	callAll(this._root._aftercreate);
+	this._root._lock = false;
+}
+
+function _set(newState) {
+	var oldState = this._state,
+		changed = {},
+		dirty = false;
+
+	for (var key in newState) {
+		if (differs(newState[key], oldState[key])) changed[key] = dirty = true;
+	}
+	if (!dirty) return;
+
+	this._state = assign({}, oldState, newState);
+	this._recompute(changed, this._state);
+	if (this._bind) this._bind(changed, this._state);
+	dispatchObservers(this, this._observers.pre, changed, this._state, oldState);
+	this._fragment.p(changed, this._state);
+	dispatchObservers(this, this._observers.post, changed, this._state, oldState);
+}
+
+function callAll(fns) {
+	while (fns && fns.length) fns.pop()();
+}
+
+function _mount(target, anchor) {
+	this._fragment.m(target, anchor);
+}
+
+function _unmount() {
+	this._fragment.u();
+}
+
+var proto = {
+	destroy: destroy,
+	get: get,
+	fire: fire,
+	observe: observe,
+	on: on,
+	set: set,
+	teardown: destroy,
+	_recompute: noop,
+	_set: _set,
+	_mount: _mount,
+	_unmount: _unmount
+};
+
+/* generated by Svelte vX.Y.Z */
+function create_main_fragment(state, component) {
+	var div, text, div_1;
+
+	return {
+		c: function create() {
+			div = createElement("div");
+			text = createText("\n");
+			div_1 = createElement("div");
+			this.h();
+		},
+
+		h: function hydrate() {
+			setAttribute(div, "data-foo", "bar");
+			setAttribute(div_1, "data-foo", state.bar);
+		},
+
+		m: function mount(target, anchor) {
+			insertNode(div, target, anchor);
+			insertNode(text, target, anchor);
+			insertNode(div_1, target, anchor);
+		},
+
+		p: function update(changed, state) {
+			if (changed.bar) {
+				setAttribute(div_1, "data-foo", state.bar);
+			}
+		},
+
+		u: function unmount() {
+			detachNode(div);
+			detachNode(text);
+			detachNode(div_1);
+		},
+
+		d: noop
+	};
+}
+
+function SvelteComponent(options) {
+	init(this, options);
+	this._state = assign({}, options.data);
+
+	this._fragment = create_main_fragment(this._state, this);
+
+	if (options.target) {
+		this._fragment.c();
+		this._fragment.m(options.target, options.anchor || null);
+	}
+}
+
+assign(SvelteComponent.prototype, proto);
+
+export default SvelteComponent;
diff --git a/test/js/samples/dont-use-dataset-in-legacy/expected.js b/test/js/samples/dont-use-dataset-in-legacy/expected.js
new file mode 100644
--- /dev/null
+++ b/test/js/samples/dont-use-dataset-in-legacy/expected.js
@@ -0,0 +1,55 @@
+/* generated by Svelte vX.Y.Z */
+import { assign, createElement, createText, detachNode, init, insertNode, noop, proto, setAttribute } from "svelte/shared.js";
+
+function create_main_fragment(state, component) {
+	var div, text, div_1;
+
+	return {
+		c: function create() {
+			div = createElement("div");
+			text = createText("\n");
+			div_1 = createElement("div");
+			this.h();
+		},
+
+		h: function hydrate() {
+			setAttribute(div, "data-foo", "bar");
+			setAttribute(div_1, "data-foo", state.bar);
+		},
+
+		m: function mount(target, anchor) {
+			insertNode(div, target, anchor);
+			insertNode(text, target, anchor);
+			insertNode(div_1, target, anchor);
+		},
+
+		p: function update(changed, state) {
+			if (changed.bar) {
+				setAttribute(div_1, "data-foo", state.bar);
+			}
+		},
+
+		u: function unmount() {
+			detachNode(div);
+			detachNode(text);
+			detachNode(div_1);
+		},
+
+		d: noop
+	};
+}
+
+function SvelteComponent(options) {
+	init(this, options);
+	this._state = assign({}, options.data);
+
+	this._fragment = create_main_fragment(this._state, this);
+
+	if (options.target) {
+		this._fragment.c();
+		this._fragment.m(options.target, options.anchor || null);
+	}
+}
+
+assign(SvelteComponent.prototype, proto);
+export default SvelteComponent;
diff --git a/test/js/samples/dont-use-dataset-in-legacy/input.html b/test/js/samples/dont-use-dataset-in-legacy/input.html
new file mode 100644
--- /dev/null
+++ b/test/js/samples/dont-use-dataset-in-legacy/input.html
@@ -0,0 +1,2 @@
+<div data-foo='bar'/>
+<div data-foo='{{bar}}'/>