-
Notifications
You must be signed in to change notification settings - Fork 0
/
hideshow.js
103 lines (83 loc) · 2.81 KB
/
hideshow.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
97
98
99
100
101
102
103
(function () {
Set.prototype.diff = function (other) {
let ret = new Set(this);
for (let elem of other) {
ret.delete(elem);
}
return ret;
};
document.addEventListener("DOMContentLoaded", function () {
let nodes = document.querySelectorAll("[--hideshow-fields]");
for (let node of nodes) {
let onChange;
let hideFields = new Set(csvParse(node.getAttribute("--hideshow-fields")));
switch (node.type) {
case "select-one":
onChange = function () {
let value = node.value;
let showOnSelected;
if (value) {
showOnSelected = csvParse(
node.getAttribute(`--show-on-${value}`)
);
}
let toShow = showOnSelected || [];
let toHide = hideFields.diff(toShow);
getFormRows(toShow).map(show);
getFormRows(toHide).map(hide);
};
break;
case "checkbox":
let showOnChecked = csvParse(node.getAttribute("--show-on-checked"));
let toShow = showOnChecked || [];
let toHide = hideFields.diff(toShow);
let showRows = getFormRows(toShow);
let hideRows = getFormRows(toHide);
onChange = function () {
let checked = node.checked;
hideRows.map(checked ? hide : show);
showRows.map(checked ? show : hide);
};
break;
}
if (onChange) {
onChange();
node.addEventListener("change", onChange);
}
}
});
function csvParse(str) {
if (!str) {
return [];
}
let arr = str.split(",");
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].trim();
}
return arr;
}
function getFormRows(fields) {
return Array.from(_getFormRows(fields));
}
function* _getFormRows(fields) {
if (!fields) {
return;
}
for (let name of fields) {
let formRow = fieldNameToFormRow(name);
if (!formRow) continue;
yield formRow;
}
}
function fieldNameToFormRow(fieldName) {
let cls = "field-" + fieldName;
let formRow = document.getElementsByClassName(cls)[0];
return formRow;
}
function hide(node) {
node.style.display = "none";
}
function show(node) {
node.style.display = "";
}
})();