-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiple-select.js
55 lines (53 loc) · 1.66 KB
/
multiple-select.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
class MultipleSelect {
constructor({ el, options, selectedOptions, dispatch }) {
this.el = el;
this.options = options;
this.selectedOptions = selectedOptions;
this.dispatch = dispatch;
this.init();
}
init() {
const vis = this;
vis.select = d3
.select(vis.el)
.attr("size", vis.options.length + 1)
.on("change", function (event) {
const selectAll = !this.value;
if (selectAll) {
vis.selectedOptions = vis.options.slice();
} else {
vis.selectedOptions = Array.from(this.selectedOptions)
.filter((d) => d.value)
.map((d) => d.value);
}
vis.dispatch.call("change", null, vis.selectedOptions);
vis.updateVis();
});
vis.option = vis.select
.selectAll("option")
.data(["Select All", ...vis.options])
.join("option")
.attr("value", (d, i) => (i > 0 ? d : ""))
.attr("selected", (d) => (vis.selectedOptions.includes(d) ? "" : null))
.text((d) => d);
vis.selectAllEl = vis.option.filter((d, i) => i === 0).node();
vis.valueOptionsEls = vis.option.filter((d, i) => i > 0).nodes();
vis.updateVis();
}
updateVis() {
const vis = this;
const allSelected = vis.selectedOptions.length === vis.options.length;
vis.selectAllEl.selected = false;
if (allSelected) {
vis.selectAllEl.disabled = true;
vis.valueOptionsEls.forEach((optionEl) => {
optionEl.selected = true;
});
} else {
vis.selectAllEl.disabled = false;
vis.valueOptionsEls.forEach((optionEl) => {
optionEl.selected = vis.selectedOptions.includes(optionEl.value);
});
}
}
}