generated from mirisuzanne/web-component-template
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
toggle-control-raw.js
96 lines (76 loc) · 2.05 KB
/
toggle-control-raw.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class ToggleControl extends GroundControl {
static register(tagName) {
if ('customElements' in window) {
customElements.define(
tagName || 'toggle-control',
ToggleControl
);
}
};
toggles = [];
set pressed(target) {
this.toggles.forEach((btn) => {
btn.setAttribute(
'aria-pressed',
target === btn ? 'true' : 'false'
);
});
};
get pressed() {
return this.toggles.find(
(btn) => btn.getAttribute('aria-pressed') === 'true'
);
};
get pressedValue() {
return this.pressed?.dataset.value;
};
constructor() {
super();
GroundControl.blockDisplay(this);
this.addEventListener('click', this.onTogglePress);
};
connectedCallback() {
super.connectedCallback();
if (this.id) this.inputId = this.id;
this.toggles = this.#findToggles();
if (!this.toggles) {
console.error('No toggle buttons found for toggle-control');
return;
}
this.hasInput = true;
this.toggles.forEach((btn) => {
btn.setAttribute('type', 'button');
if (!btn.dataset.value) {
btn.dataset.value = btn.innerText;
}
});
this.pressed = this.pressed;
this.initialValue = this.pressedValue || this.dataset.off;
this.value = this.storedValue || this.initialValue;
};
onTogglePress = (event) => {
this.doPress(event.target);
this.value = this.pressedValue;
};
onValueChange = () => {
if (this.value === this.pressedValue) return;
this.pressed = this.#toggleFromValue();
};
doPress = (target) => {
if (!this.toggles.includes(target)) return;
const isUnPress = this.pressed === target;
const allowUnPress = this.dataset.off || this.toggles.length === 1;
if (isUnPress && allowUnPress) {
this.pressed = undefined;
} else {
this.pressed = target;
}
};
#toggleFromValue = () => this.toggles.find(
(btn) => btn.dataset.value === this.usedValue
);
#findToggles = () => [
...this.querySelectorAll('button:not([for-reset])')
];
}
ToggleControl.register();