-
Notifications
You must be signed in to change notification settings - Fork 376
/
Copy pathselect-only.js
365 lines (311 loc) · 10.5 KB
/
select-only.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Save a list of named combobox actions, for future readability
const SelectActions = {
Close: 0,
CloseSelect: 1,
First: 2,
Last: 3,
Next: 4,
Open: 5,
PageDown: 6,
PageUp: 7,
Previous: 8,
Select: 9,
Type: 10
}
/*
* Helper functions
*/
// filter an array of options against an input string
// returns an array of options that begin with the filter string, case-independent
function filterOptions(options = [], filter, exclude = []) {
return options.filter((option) => {
const matches = option.toLowerCase().indexOf(filter.toLowerCase()) === 0;
return matches && exclude.indexOf(option) < 0;
});
}
// map a key press to an action
function getActionFromKey(event, menuOpen) {
const { key, altKey, ctrlKey, metaKey } = event;
const openKeys = ['ArrowDown', 'ArrowUp', 'Enter', ' ']; // all keys that will do the default open action
// handle opening when closed
if (!menuOpen && openKeys.includes(key)) {
return SelectActions.Open;
}
// home and end move the selected option when open or closed
if (key === 'Home') {
return SelectActions.First;
}
if (key === 'End') {
return SelectActions.Last;
}
// handle typing characters when open or closed
if (key === 'Backspace' || key === 'Clear' || (key.length === 1 && key !== ' ' && !altKey && !ctrlKey && !metaKey)) {
return SelectActions.Type;
}
// handle keys when open
if (menuOpen) {
if (key === 'ArrowUp' && altKey) {
return SelectActions.CloseSelect;
}
else if (key === 'ArrowDown' && !altKey) {
return SelectActions.Next;
}
else if (key === 'ArrowUp') {
return SelectActions.Previous;
}
else if (key === 'PageUp') {
return SelectActions.PageUp;
}
else if (key === 'PageDown') {
return SelectActions.PageDown;
}
else if (key === 'Escape') {
return SelectActions.Close;
}
else if (key === 'Enter' || key === ' ') {
return SelectActions.CloseSelect;
}
}
}
// return the index of an option from an array of options, based on a search string
// if the filter is multiple iterations of the same letter (e.g "aaa"), then cycle through first-letter matches
function getIndexByLetter(options, filter, startIndex = 0) {
const orderedOptions = [...options.slice(startIndex), ...options.slice(0, startIndex)];
const firstMatch = filterOptions(orderedOptions, filter)[0];
const allSameLetter = (array) => array.every((letter) => letter === array[0]);
// first check if there is an exact match for the typed string
if (firstMatch) {
return options.indexOf(firstMatch);
}
// if the same letter is being repeated, cycle through first-letter matches
else if (allSameLetter(filter.split(''))) {
const matches = filterOptions(orderedOptions, filter[0]);
return options.indexOf(matches[0]);
}
// if no matches, return -1
else {
return -1;
}
}
// get an updated option index after performing an action
function getUpdatedIndex(currentIndex, maxIndex, action) {
const pageSize = 10; // used for pageup/pagedown
switch(action) {
case SelectActions.First:
return 0;
case SelectActions.Last:
return maxIndex;
case SelectActions.Previous:
return Math.max(0, currentIndex - 1);
case SelectActions.Next:
return Math.min(maxIndex, currentIndex + 1);
case SelectActions.PageUp:
return Math.max(0, currentIndex - pageSize);
case SelectActions.PageDown:
return Math.min(maxIndex, currentIndex + pageSize);
default:
return currentIndex;
}
}
// check if an element is currently scrollable
function isScrollable(element) {
return element && element.clientHeight < element.scrollHeight;
}
// ensure a given child element is within the parent's visible scroll area
// if the child is not visible, scroll the parent
function maintainScrollVisibility(activeElement, scrollParent) {
const { offsetHeight, offsetTop } = activeElement;
const { offsetHeight: parentOffsetHeight, scrollTop } = scrollParent;
const isAbove = offsetTop < scrollTop;
const isBelow = (offsetTop + offsetHeight) > (scrollTop + parentOffsetHeight);
if (isAbove) {
scrollParent.scrollTo(0, offsetTop);
}
else if (isBelow) {
scrollParent.scrollTo(0, offsetTop - parentOffsetHeight + offsetHeight);
}
}
/*
* Select Component
* Accepts a combobox element and an array of string options
*/
const Select = function(el, options = []) {
// element refs
this.el = el;
this.comboEl = el.querySelector('[role=combobox]');
this.listboxEl = el.querySelector('[role=listbox]');
// data
this.idBase = this.comboEl.id || 'combo';
this.options = options;
// state
this.activeIndex = 0;
this.open = false;
this.searchString = '';
this.searchTimeout = null;
// init
if (el && this.comboEl && this.listboxEl) {
this.init();
}
}
Select.prototype.init = function() {
// select first option by default
this.comboEl.innerHTML = this.options[0];
// add event listeners
this.comboEl.addEventListener('blur', this.onComboBlur.bind(this));
this.comboEl.addEventListener('click', this.onComboClick.bind(this));
this.comboEl.addEventListener('keydown', this.onComboKeyDown.bind(this));
// create options
this.options.map((option, index) => {
const optionEl = this.createOption(option, index);
this.listboxEl.appendChild(optionEl);
});
}
Select.prototype.createOption = function(optionText, index) {
const optionEl = document.createElement('div');
optionEl.setAttribute('role', 'option');
optionEl.id = `${this.idBase}-${index}`;
optionEl.className = index === 0 ? 'combo-option option-current' : 'combo-option';
optionEl.setAttribute('aria-selected', `${index === 0}`);
optionEl.innerText = optionText;
optionEl.addEventListener('click', (event) => {
event.stopPropagation();
this.onOptionClick(index);
});
optionEl.addEventListener('mousedown', this.onOptionMouseDown.bind(this));
return optionEl;
}
Select.prototype.getSearchString = function(char) {
// reset typing timeout and start new timeout
// this allows us to make multiple-letter matches, like a native select
if (typeof this.searchTimeout === 'number') {
window.clearTimeout(this.searchTimeout);
}
this.searchTimeout = window.setTimeout(() => {
this.searchString = '';
}, 500);
// add most recent letter to saved search string
this.searchString += char;
return this.searchString;
}
Select.prototype.onComboBlur = function() {
// do not do blur action if ignoreBlur flag has been set
if (this.ignoreBlur) {
this.ignoreBlur = false;
return;
}
// select current option and close
if (this.open) {
this.selectOption(this.activeIndex);
this.updateMenuState(false, false);
}
}
Select.prototype.onComboClick = function() {
this.updateMenuState(!this.open, false);
}
Select.prototype.onComboKeyDown = function(event) {
const { key } = event;
const max = this.options.length - 1;
const action = getActionFromKey(event, this.open);
switch(action) {
case SelectActions.Last:
case SelectActions.First:
this.updateMenuState(true);
// intentional fallthrough
case SelectActions.Next:
case SelectActions.Previous:
case SelectActions.PageUp:
case SelectActions.PageDown:
event.preventDefault();
return this.onOptionChange(getUpdatedIndex(this.activeIndex, max, action));
case SelectActions.CloseSelect:
event.preventDefault();
this.selectOption(this.activeIndex);
// intentional fallthrough
case SelectActions.Close:
event.preventDefault();
return this.updateMenuState(false);
case SelectActions.Type:
return this.onComboType(key);
case SelectActions.Open:
event.preventDefault();
return this.updateMenuState(true);
}
}
Select.prototype.onComboType = function(letter) {
// open the listbox if it is closed
this.updateMenuState(true);
// find the index of the first matching option
const searchString = this.getSearchString(letter);
const searchIndex = getIndexByLetter(this.options, searchString, this.activeIndex + 1);
// if a match was found, go to it
if (searchIndex >= 0) {
this.onOptionChange(searchIndex);
}
// if no matches, clear the timeout and search string
else {
window.clearTimeout(this.searchTimeout);
this.searchString = '';
}
}
Select.prototype.onOptionChange = function(index) {
// update state
this.activeIndex = index;
// update aria-activedescendant
this.comboEl.setAttribute('aria-activedescendant', `${this.idBase}-${index}`);
// update active option styles
const options = this.el.querySelectorAll('[role=option]');
[...options].forEach((optionEl) => {
optionEl.classList.remove('option-current');
});
options[index].classList.add('option-current');
// ensure the new option is in view
if (isScrollable(this.listboxEl)) {
maintainScrollVisibility(options[index], this.listboxEl);
}
}
Select.prototype.onOptionClick = function(index) {
this.onOptionChange(index);
this.selectOption(index);
this.updateMenuState(false);
}
Select.prototype.onOptionMouseDown = function() {
// Clicking an option will cause a blur event,
// but we don't want to perform the default keyboard blur action
this.ignoreBlur = true;
}
Select.prototype.selectOption = function(index) {
// update state
this.activeIndex = index;
// update displayed value
const selected = this.options[index];
this.comboEl.innerHTML = selected;
// update aria-selected
const options = this.el.querySelectorAll('[role=option]');
[...options].forEach((optionEl) => {
optionEl.setAttribute('aria-selected', 'false');
});
options[index].setAttribute('aria-selected', 'true');
}
Select.prototype.updateMenuState = function(open, callFocus = true) {
if (this.open === open) {
return;
}
// update state
this.open = open;
// update aria-expanded and styles
this.comboEl.setAttribute('aria-expanded', `${open}`);
open ? this.el.classList.add('open') : this.el.classList.remove('open');
// update activedescendant
const activeID = open ? `${this.idBase}-${this.activeIndex}` : '';
this.comboEl.setAttribute('aria-activedescendant', activeID);
// move focus back to the combobox, if needed
callFocus && this.comboEl.focus();
}
// init select
window.addEventListener('load', function () {
const options = ['Choose a Fruit', 'Apple', 'Banana', 'Blueberry', 'Boysenberry', 'Cherry', 'Cranberry', 'Durian', 'Eggplant', 'Fig', 'Grape', 'Guava', 'Huckleberry'];
const selectEls = document.querySelectorAll('.js-select');
selectEls.forEach((el) => {
new Select(el, options);
});
});