-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistbox.js
108 lines (83 loc) · 2.47 KB
/
listbox.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
104
105
106
107
108
const listbox = (() => {
let list, option;
const options = [];
const toggle = toggle => {
const current = list.hidden;
list.hidden = typeof toggle !== 'undefined' ? !toggle : !current;
dispatch('display', { hidden: list.hidden });
};
const filter = term => {
clear();
if( term ) {
options
.filter(option => !option.textContent.toLowerCase().startsWith(term.toLowerCase()))
.forEach(option => option.hidden = true);
}
};
const select = down => {
if( typeof down === 'undefined' ) {
dispatch('change', { id: option.id, value: option.textContent });
return;
}
const sibling = down ? 'nextElementSibling' : 'previousElementSibling';
const startEl = down ? 'firstElementChild' : 'lastElementChild';
let nextElement;
if( option ) {
nextElement = option[sibling];
while( nextElement && nextElement.hidden ) {
nextElement = nextElement[sibling] || null;
}
}
else {
nextElement = list[startEl];
while( nextElement && nextElement.hidden ) {
nextElement = nextElement[sibling] || null;
}
}
if( nextElement) {
option && option.removeAttribute('aria-selected');
option = nextElement;
option.setAttribute('aria-selected', true);
}
dispatch('change', { id: option.id });
};
const hidden = () => list.hidden;
const clear = () => {
if ( option ) {
option.removeAttribute('aria-selected');
option = null;
}
options.forEach(option => option.hidden = false);
};
const click = event => {
if( options.indexOf(event.target) > -1 ) {
option && option.removeAttribute('aria-selected');
option = event.target;
option.setAttribute('aria-selected', true);
dispatch('change', { id: option.id, value: option.textContent });
}
};
const dispatch = (type, detail) => {
const event = new CustomEvent(type, { detail });
list.parentNode.dispatchEvent(event);
};
const init = ({datalist, label, parent}) => {
list = document.createElement('ul');
list.setAttribute('role', 'listbox');
Array.from(datalist.children).forEach((option, index) => {
const li = document.createElement('li');
li.textContent = option.value;
li.id = `option-${datalist.id}-${index}`;
li.setAttribute('role', 'option');
options.push(li);
list.appendChild(li);
});
list.id = datalist.id;
list.hidden = true;
list.setAttribute('aria-labelledby', label.id);
parent.appendChild(list);
list.addEventListener('click', click);
return { filter, toggle, hidden, select, clear };
};
return { init }
})();