-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathToggleTree.js
95 lines (72 loc) · 2.61 KB
/
ToggleTree.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
export class ToggleTree {
constructor(parent, options) {
this.parent = parent;
this.listItems = [];
this.options = options;
this.useIcon = false;
if (this.options !== undefined && (this.options.iconSelector !== undefined || this.options.iconVisible !== undefined || this.options.iconCollapsed !== undefined)) {
if (this.options.iconSelector === undefined || this.options.iconVisible === undefined || this.options.iconCollapsed === undefined) {
console.warn('It seems you want to use an icon, please make sure that you provide all of the following options: options.iconSelector, options.iconVisible and options.iconCollapsed');
}
this.useIcon = true;
}
this.init();
}
init() {
const listItems = this.parent.querySelectorAll(':scope li');
listItems.forEach(listItem => {
const childList = listItem.querySelector(':scope ul');
if (childList !== null) {
this.listItems.push(listItem);
listItem.querySelector('a').onclick = event => {
event.preventDefault();
this.toggle(listItem);
}
}
});
}
isCollapsed(listItem) {
let display = window.getComputedStyle(listItem.querySelector('ul')).display;
if (listItem.querySelector('ul').style.display !== '') {
display = listItem.querySelector('ul').style.display;
}
if (display === 'none') {
return true;
}
return false;
}
toggle(listItem) {
if (this.isCollapsed(listItem)) {
this.show(listItem);
}
else {
this.collapse(listItem);
}
}
show(listItem) {
const list = listItem.querySelector('ul');
list.style.display = 'block';
listItem.classList.add('active');
if (this.useIcon) {
listItem.querySelector(this.options.iconSelector).innerHTML = this.options.iconVisible;
}
}
showAll() {
this.listItems.forEach(listItem => {
this.show(listItem);
});
}
collapse(listItem) {
const list = listItem.querySelector('ul');
list.style.display = 'none';
listItem.classList.remove('active');
if (this.useIcon) {
listItem.querySelector(this.options.iconSelector).innerHTML = this.options.iconCollapsed;
}
}
collapseAll() {
this.listItems.forEach(listItem => {
this.collapse(listItem);
});
}
}