-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
518 lines (447 loc) · 14.9 KB
/
index.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
'use strict';
import Classlist from 'classlist';
import Emitter from 'component-emitter';
import LiveRegion from 'live-region';
import scrollToElement from 'scrollto-element';
import inView from './lib/utils/is-scrolled-in-view';
import viewportStatus from './lib/utils/viewport-status';
import filters from './lib/filters';
import keyvent from './lib/utils/keyvent';
import isWithin from './lib/utils/is-within';
import elHandler from './lib/utils/element-handler';
import getCurrentGroup from './lib/current-group';
import noResultsHandler from './lib/no-results';
import attrs from './lib/attributes';
import wrapMatch from './lib/utils/wrap-match';
import configuration from './lib/config';
import announceActive from './lib/announce-active';
/**
* /////////////////////////
* //////// COMBOBO ////////
* /////////////////////////
*
* ."`".
* .-./ _=_ \.-.
* { (,(oYo),) }}
* {{ | " |} }
* { { \(---)/ }}
* {{ }'-=-'{ } }
* { { }._:_.{ }}
* {{ } -:- { } }
* {_{ }`===`{ _}
* ((((\) (/))))
*/
module.exports = class Combobo {
constructor(config) {
config = config || {};
// merge user config with default config
this.config = configuration(config);
this.input = elHandler(this.config.input);
this.list = elHandler(this.config.list);
this.cachedOpts = this.currentOpts = elHandler((this.config.options), true, this.list);
// initial state
this.isOpen = false;
this.currentOption = null;
this.selected = [];
this.groups = [];
this.isHovering = false;
this.autoFilter = this.config.autoFilter;
this.optionsWithEventHandlers = new Set();
this.optionsWithKeyEventHandlers = new Set();
// option groups
if (this.config.groups) {
const groupEls = elHandler(this.config.groups, true, this.list);
this.groups = groupEls.map((groupEl) => {
return {
element: groupEl,
options: this.cachedOpts.filter((opt) => groupEl.contains(opt))
};
});
}
if (!this.input || !this.list) {
throw new Error('Unable to find required elements (list/input)');
}
attrs(this.input, this.list, this.cachedOpts);
if (this.config.useLiveRegion) {
this.liveRegion = new LiveRegion({ ariaLive: 'assertive' });
}
this.initEvents();
}
initEvents() {
Emitter(this);
if (!this.optionsWithKeyEventHandlers.has(this.input)) {
this.input.addEventListener('click', () => {
this.openList().goTo(this.getOptIndex() || 0); // ensure its open
});
this.input.addEventListener('blur', () => {
if (!this.isHovering) { this.closeList(); }
});
this.input.addEventListener('focus', () => {
if (this.selected.length) {
this.input.value = this.selected.length >= 2 ? '' : this.config.selectionValue(this.selected);
}
this.input.select();
});
// listen for clicks outside of combobox
document.addEventListener('click', (e) => {
const isOrWithin = isWithin(e.target, [this.input, this.list], true);
if (!isOrWithin && this.isOpen) { this.closeList(); }
});
}
this.optionEvents();
this.initKeys();
}
getOptIndex() {
return this.currentOption && this.currentOpts.indexOf(this.currentOption);
}
optionEvents() {
this.cachedOpts.forEach((option) => {
// The event should not be added again for already selected options and existing options
if (!this.optionsWithEventHandlers.has(option.id) && !this.selected.includes(option)) {
option.addEventListener('click', () => {
this
.goTo(this.currentOpts.indexOf(option))
.select();
});
option.addEventListener('mouseover', () => {
// clean up
const prev = this.currentOption;
if (prev) { Classlist(prev).remove(this.config.activeClass); }
Classlist(option).add(this.config.activeClass);
this.isHovering = true;
});
option.addEventListener('mouseout', () => {
Classlist(option).remove(this.config.activeClass);
this.isHovering = false;
});
this.optionsWithEventHandlers.add(option.id);
}
});
}
openList() {
Classlist(this.list).add(this.config.openClass);
this.input.setAttribute('aria-expanded', 'true');
if (!this.isOpen) {
// announcing count
this.announceCount();
}
this.isOpen = true;
this.emit('list:open');
const status = viewportStatus(this.list);
if (!status.visible) {
const offset = status.position === 'bottom' ?
0 - (window.innerHeight - (this.input.clientHeight + this.list.clientHeight)) :
0;
scrollToElement({
element: this.input,
offset: offset,
bezier: [0.19, 1, 0.22, 1],
duration: 100
});
}
return this;
}
closeList(focus, selectText) {
Classlist(this.list).remove(this.config.openClass);
this.input.setAttribute('aria-expanded', 'false');
this.isOpen = false;
if (focus) { this.input.focus(); }
// Set the value back to what it was
if (!this.multiselect && this.selected.length) {
this.input.value = this.config.selectionValue(this.selected);
}
if (selectText) { this.input.select(); }
this.emit('list:close');
return this;
}
initKeys() {
// keydown listener
if (this.optionsWithKeyEventHandlers.has(this.input)) {
return;
} else {
this.optionsWithKeyEventHandlers.add(this.input);
}
keyvent.down(this.input, [{
keys: ['up', 'down'],
callback: (e, k) => {
if (this.isOpen) {
// if typing filtered out the pseudo-current option
if (this.currentOpts.indexOf(this.currentOption) === -1) {
return this.goTo(0, true);
}
return this.goTo(k === 'down' ? 'next' : 'prev', true);
}
const idx = this.selected.length
? this.currentOpts.indexOf(this.selected[this.selected.length - 1])
: 0
this
.goTo(idx, true)
.openList();
},
preventDefault: true
}, {
keys: ['enter'],
callback: (e) => {
if (this.isOpen) {
e.preventDefault();
e.stopPropagation();
this.select();
}
}
}, {
keys: ['escape'],
callback: (e) => {
if (this.isOpen) {
e.stopPropagation();
this.closeList(true, true);
}
}
}, {
keys: ['backspace'],
callback: () => {
if (this.selected.length >= 2) {
this.input.value = '';
}
}
}]);
// ignore tab, enter, escape and shift
const ignores = [9, 13, 27, 16];
// filter keyup listener
keyvent.up(this.input, (e) => {
// If autoFilter is false, key up filter not required
if (!this.autoFilter) {
return;
}
const filter = this.config.filter;
const cachedVal = this.cachedInputValue;
if (ignores.indexOf(e.which) > -1 || !filter) { return; }
// Handles if there is a fresh selection
if (this.freshSelection) {
this.clearFilters();
if (cachedVal && (cachedVal.trim() !== this.input.value.trim())) { // if the value has changed...
this.filter().openList();
this.freshSelection = false;
}
} else {
this.filter().openList();
}
// handle empty results
noResultsHandler(this.list, this.currentOpts, this.config.noResultsText);
});
}
clearFilters() {
this.cachedOpts.forEach((o) => o.style.display = '');
this.groups.forEach((g) => g.element.style.display = '');
// show all opts
this.currentOpts = this.cachedOpts;
return this;
}
filter(supress) {
const filter = this.config.filter;
const befores = this.currentOpts;
this.currentOpts = typeof filter === 'function' ?
filter(this.input.value.trim(), this.cachedOpts) :
filters[filter](this.input.value.trim(), this.cachedOpts);
// don't let user's functions break stuff
this.currentOpts = this.currentOpts || [];
this.updateOpts();
// announce count only if it has changed
if (!befores.every((b) => this.currentOpts.indexOf(b) > -1) && !supress) {
this.announceCount();
}
return this;
}
announceCount() {
const count = this.config.announcement && this.config.announcement.count;
if (count && this.liveRegion) {
this.liveRegion.announce(count(this.currentOpts.length), 500);
}
return this;
}
updateOpts() {
const optVal = this.config.optionValue;
this.cachedOpts.forEach((opt) => {
// configure display of options based on filtering
opt.style.display = this.currentOpts.indexOf(opt) === -1 ? 'none' : '';
// configure the innerHTML of each option
opt.innerHTML = typeof optVal === 'string' ?
wrapMatch(opt, this.input, optVal) :
optVal(opt);
});
this.updateGroups();
return this;
}
updateGroups() {
this.groups.forEach((groupData) => {
const visibleOpts = groupData.options.filter((opt) => opt.style.display === '');
groupData.element.style.display = visibleOpts.length ? '' : 'none';
});
return this;
}
select() {
const currentOpt = this.currentOption;
if (!currentOpt) { return; }
if (!this.config.multiselect && this.selected.length) { // clean up previously selected
Classlist(this.selected[0]).remove(this.config.selectedClass)
}
const idx = this.selected.indexOf(currentOpt);
const wasSelected = idx > -1;
// Multiselect option
if (this.config.multiselect) {
// If option is in array and gets clicked, remove it
if (wasSelected) {
this.selected.splice(idx, 1);
} else {
this.selected.push(currentOpt);
}
} else {
this.selected = this.config.allowEmpty && wasSelected
? []
: [currentOpt]
}
// manage aria-selected
this.cachedOpts.forEach((o) => {
o.setAttribute('aria-selected', this.selected.indexOf(o) > -1 ? 'true' : 'false');
});
if (wasSelected) {
currentOpt.classList.remove(this.config.selectedClass);
this.emit('deselection', { text: this.input.value, option: currentOpt });
} else {
currentOpt.classList.add(this.config.selectedClass)
this.emit('selection', { text: this.input.value, option: currentOpt });
}
this.freshSelection = true;
this.input.value = this.selected.length
? this.config.selectionValue(this.selected)
: '';
this.cachedInputValue = this.input.value;
this.filter(true).clearFilters()
// close the list for single select
// (leave it open for multiselect)
if (!this.config.multiselect) {
this.closeList();
this.input.select();
}
return this;
}
reset() {
this.clearFilters();
this.input.value = '';
this.updateOpts();
this.input.removeAttribute('aria-activedescendant');
this.input.removeAttribute('data-active-option');
this.currentOption = null;
this.selected = [];
this.cachedOpts.forEach((optEl) => {
Classlist(optEl).remove(this.config.selectedClass);
Classlist(optEl).remove(this.config.activeClass);
optEl.setAttribute('aria-selected', 'false');
});
return this;
}
goTo(option, fromKey) {
if (typeof option === 'string') { // 'prev' or 'next'
const optIndex = this.getOptIndex();
return this.goTo(option === 'next' ? optIndex + 1 : optIndex - 1, fromKey);
}
const newOpt = this.currentOpts[option];
let groupChange = false;
if (!this.currentOpts[option]) {
// end of the line so allow scroll up for visibility of potential group labels
if (this.getOptIndex() === 0) { this.list.scrollTop = 0; }
return this;
} else if (this.groups.length) {
const newGroup = getCurrentGroup(this.groups, newOpt);
groupChange = newGroup && newGroup !== this.currentGroup;
this.currentGroup = newGroup;
}
// update current option
this.currentOption = newOpt;
// show pseudo focus styles
this.pseudoFocus(groupChange);
// Dectecting if element is inView and scroll to it.
this.currentOpts.forEach((opt) => {
if (opt.classList.contains(this.config.activeClass) && !inView(this.list, opt)) {
scrollToElement(opt);
}
});
return this;
}
pseudoFocus(groupChanged) {
const option = this.currentOption;
const activeClass = this.config.activeClass;
const prevId = this.input.getAttribute('data-active-option');
const prev = prevId && document.getElementById(prevId);
// clean up
if (prev && activeClass) {
Classlist(prev).remove(activeClass);
}
if (option) {
this.input.setAttribute('data-active-option', option.id);
if (activeClass) { Classlist(option).add(activeClass); }
if (this.liveRegion) {
announceActive(
option,
this.config,
this.liveRegion.announce.bind(this.liveRegion),
groupChanged,
this.currentGroup && this.currentGroup.element
);
}
this.input.setAttribute('aria-activedescendant', option.id);
this.currentOption = option;
this.emit('change');
}
return this;
}
setOptions(option) {
// The below code adds the new option to current Dropdown list
if (typeof option === 'object') { // This needs to be check for passing unit test
this.config.list.append(option);
}
this.cachedOpts.push(option);
if (this.currentOpts.indexOf(option) === -1) {
this.currentOpts.push(option);
}
return this;
}
setCurrentOptions() {
this.currentOption = this.currentOpts[0]; // Sets the current option index
return this;
}
updateSelectedOptions() {
const list = document.getElementById(this.config.list.id);
const selectedList = this.selected;
this.emptyDropdownList();
// The below code will remove all child elements in the dropdown list
while (list.hasChildNodes()) {
list.removeChild(list.firstChild);
}
// The below code will append the selected options to the dropdown list if any
if (selectedList.length > 0) {
selectedList.forEach(item => {
this.setOptions(item);
});
}
return this;
}
emptyDropdownList() {
// empty the cachedOpts and currentOpts of dropdown list
this.currentOpts = [];
this.cachedOpts = [];
this.optionsWithEventHandlers.clear();
return this;
}
setNoResultFound() {
// handle empty results whenever user perform search and if no relevant records found
noResultsHandler(this.list, this.currentOpts, this.config.noResultsText);
}
};
/**
* NOTE:
* - https://www.w3.org/TR/2016/WD-wai-aria-practices-1.1-20160317/#combobox
* - "For each combobox pattern the button need not be in the tab order if there
* is an appropriate keystroke associated with the input element such that when
* focus is on the input, the keystroke triggers display of the associated drop
* down list."
*/