generated from daviddarnes/component-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage-form.js
60 lines (53 loc) · 1.46 KB
/
storage-form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class StorageForm extends HTMLElement {
static register(tagName) {
if ("customElements" in window) {
customElements.define(tagName || "storage-form", StorageForm);
}
}
connectedCallback() {
this.forms.forEach((form) => {
this.updateForm(form);
const eventType = this.getSubmitter(form) ? "submit" : "change";
form.addEventListener(eventType, (event) => {
event.preventDefault();
this.updateStorage(new FormData(event.target.closest("form")));
window.dispatchEvent(new StorageEvent("storage"));
});
});
}
updateForm(form) {
this.getNamedInputs(form).forEach((input) => {
const storedValue = window.localStorage[input.name];
if (!storedValue) return;
switch (input.type) {
case "hidden":
break;
case "checkbox":
case "radio":
input.checked = input.value == storedValue;
break;
default:
input.value = storedValue;
}
});
}
updateStorage(data) {
for (const item of data.entries()) {
if (!item[1]) {
window.localStorage.removeItem(item[0]);
} else {
window.localStorage.setItem(item[0], item[1]);
}
}
}
get forms() {
return this.querySelectorAll("form");
}
getNamedInputs(form) {
return form.querySelectorAll("[name]");
}
getSubmitter(form) {
return form.querySelector("[type='submit'], button:not([type])");
}
}
StorageForm.register();