-
Notifications
You must be signed in to change notification settings - Fork 613
/
choices.js
2207 lines (1951 loc) · 69.7 KB
/
choices.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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Fuse from 'fuse.js';
import Store from './store/index.js';
import {
addItem,
removeItem,
highlightItem,
addChoice,
filterChoices,
activateChoices,
addGroup,
clearAll,
clearChoices,
}
from './actions/index';
import {
isScrolledIntoView,
getAdjacentEl,
wrap,
isType,
isElement,
strToEl,
extend,
getWidthOfInput,
sortByAlpha,
sortByScore,
}
from './lib/utils.js';
import './lib/polyfills.js';
/**
* Choices
*/
class Choices {
constructor(element = '[data-choice]', userConfig = {}) {
// If there are multiple elements, create a new instance
// for each element besides the first one (as that already has an instance)
if (isType('String', element)) {
const elements = document.querySelectorAll(element);
if (elements.length > 1) {
for (let i = 1; i < elements.length; i++) {
const el = elements[i];
new Choices(el, userConfig);
}
}
}
const defaultConfig = {
items: [],
choices: [],
maxItemCount: -1,
addItems: true,
removeItems: true,
removeItemButton: false,
editItems: false,
duplicateItems: true,
delimiter: ',',
paste: true,
search: true,
searchFloor: 1,
flip: true,
regexFilter: null,
shouldSort: true,
sortFilter: sortByAlpha,
sortFields: ['label', 'value'],
placeholder: true,
placeholderValue: null,
prependValue: null,
appendValue: null,
loadingText: 'Loading...',
noResultsText: 'No results round',
noChoicesText: 'No choices to choose from',
itemSelectText: 'Press to select',
classNames: {
containerOuter: 'choices',
containerInner: 'choices__inner',
input: 'choices__input',
inputCloned: 'choices__input--cloned',
list: 'choices__list',
listItems: 'choices__list--multiple',
listSingle: 'choices__list--single',
listDropdown: 'choices__list--dropdown',
item: 'choices__item',
itemSelectable: 'choices__item--selectable',
itemDisabled: 'choices__item--disabled',
itemChoice: 'choices__item--choice',
placeholder: 'choices__placeholder',
group: 'choices__group',
groupHeading: 'choices__heading',
button: 'choices__button',
activeState: 'is-active',
focusState: 'is-focused',
openState: 'is-open',
disabledState: 'is-disabled',
highlightedState: 'is-highlighted',
hiddenState: 'is-hidden',
flippedState: 'is-flipped',
loadingState: 'is-loading',
},
callbackOnInit: null,
callbackOnAddItem: null,
callbackOnRemoveItem: null,
callbackOnHighlightItem: null,
callbackOnUnhighlightItem: null,
callbackOnCreateTemplates: null,
callbackOnChange: null,
callbackOnSearch: null,
};
// Merge options with user options
this.config = extend(defaultConfig, userConfig);
// Create data store
this.store = new Store(this.render);
// State tracking
this.initialised = false;
this.currentState = {};
this.prevState = {};
this.currentValue = '';
// Retrieve triggering element (i.e. element with 'data-choice' trigger)
this.passedElement = isType('String', element) ? document.querySelector(element) : element;
if (!this.passedElement) {
console.error('Passed element not found');
return;
}
this.highlightPosition = 0;
this.canSearch = this.config.search;
// Assing preset choices from passed object
this.presetChoices = this.config.choices;
// Assign preset items from passed object first
this.presetItems = this.config.items;
// Then add any values passed from attribute
if (this.passedElement.value) {
this.presetItems = this.presetItems.concat(this.passedElement.value.split(this.config.delimiter));
}
// Bind methods
this.init = this.init.bind(this);
this.render = this.render.bind(this);
this.destroy = this.destroy.bind(this);
this.disable = this.disable.bind(this);
// Bind event handlers
this._onFocus = this._onFocus.bind(this);
this._onBlur = this._onBlur.bind(this);
this._onKeyUp = this._onKeyUp.bind(this);
this._onKeyDown = this._onKeyDown.bind(this);
this._onClick = this._onClick.bind(this);
this._onTouchMove = this._onTouchMove.bind(this);
this._onTouchEnd = this._onTouchEnd.bind(this);
this._onMouseDown = this._onMouseDown.bind(this);
this._onMouseOver = this._onMouseOver.bind(this);
this._onPaste = this._onPaste.bind(this);
this._onInput = this._onInput.bind(this);
// Monitor touch taps/scrolls
this.wasTap = true;
// Cutting the mustard
const cuttingTheMustard = 'querySelector' in document && 'addEventListener' in document
&& 'classList' in document.createElement('div');
if (!cuttingTheMustard) console.error('Choices: Your browser doesn\'t support Choices');
// Input type check
const isValidType = ['select-one', 'select-multiple', 'text'].some(type => type === this.passedElement.type);
const canInit = isElement(this.passedElement) && isValidType;
if (canInit) {
// If element has already been initalised with Choices
if (this.passedElement.getAttribute('data-choice') === 'active') return;
// Let's go
this.init();
} else {
console.error('Incompatible input passed');
}
}
/*========================================
= Public functions =
========================================*/
/**
* Initialise Choices
* @return
* @public
*/
init() {
if (this.initialised === true) return;
const callback = this.config.callbackOnInit;
// Set initialise flag
this.initialised = true;
// Create required elements
this._createTemplates();
// Generate input markup
this._createInput();
// Subscribe store to render method
this.store.subscribe(this.render);
// Render any items
this.render();
// Trigger event listeners
this._addEventListeners();
// Run callback if it is a function
if (callback) {
if (isType('Function', callback)) {
callback();
} else {
console.error('callbackOnInit: Callback is not a function');
}
}
}
/**
* Destroy Choices and nullify values
* @return
* @public
*/
destroy() {
if (this.initialised === false) return;
// Remove all event listeners
this._removeEventListeners();
// Reinstate passed element
this.passedElement.classList.remove(this.config.classNames.input, this.config.classNames.hiddenState);
this.passedElement.tabIndex = '';
this.passedElement.removeAttribute('style', 'display:none;');
this.passedElement.removeAttribute('aria-hidden');
this.containerOuter.outerHTML = this.passedElement.outerHTML;
// Nullify stores
this.passedElement = null;
this.userConfig = null;
this.config = null;
this.store = null;
// Uninitialise
this.initialised = false;
}
/**
* Render group choices into a DOM fragment and append to choice list
* @param {Array} groups Groups to add to list
* @param {Array} choices Choices to add to groups
* @param {DocumentFragment} fragment Fragment to add groups and options to (optional)
* @return {DocumentFragment} Populated options fragment
* @private
*/
renderGroups(groups, choices, fragment) {
const groupFragment = fragment || document.createDocumentFragment();
const filter = this.config.sortFilter;
// If sorting is enabled, filter groups
if (this.config.shouldSort) {
groups.sort(filter);
}
groups.forEach((group) => {
// Grab options that are children of this group
const groupChoices = choices.filter((choice) => {
if (this.passedElement.type === 'select-one') {
return choice.groupId === group.id;
}
return choice.groupId === group.id && !choice.selected;
});
if (groupChoices.length >= 1) {
const dropdownGroup = this._getTemplate('choiceGroup', group);
groupFragment.appendChild(dropdownGroup);
this.renderChoices(groupChoices, groupFragment);
}
});
return groupFragment;
}
/**
* Render choices into a DOM fragment and append to choice list
* @param {Array} choices Choices to add to list
* @param {DocumentFragment} fragment Fragment to add choices to (optional)
* @return {DocumentFragment} Populated choices fragment
* @private
*/
renderChoices(choices, fragment) {
// Create a fragment to store our list items (so we don't have to update the DOM for each item)
const choicesFragment = fragment || document.createDocumentFragment();
const filter = this.isSearching ? sortByScore : this.config.sortFilter;
// If sorting is enabled or the user is searching, filter choices
if (this.config.shouldSort || this.isSearching) {
choices.sort(filter);
}
choices.forEach((choice) => {
const dropdownItem = this._getTemplate('choice', choice);
const shouldRender = this.passedElement.type === 'select-one' || !choice.selected;
if (shouldRender) {
choicesFragment.appendChild(dropdownItem);
}
});
return choicesFragment;
}
/**
* Render items into a DOM fragment and append to items list
* @param {Array} items Items to add to list
* @param {DocumentFragment} fragment Fragrment to add items to (optional)
* @return
* @private
*/
renderItems(items, fragment) {
// Create fragment to add elements to
const itemListFragment = fragment || document.createDocumentFragment();
// Simplify store data to just values
const itemsFiltered = this.store.getItemsReducedToValues(items);
if (this.passedElement.type === 'text') {
// Assign hidden input array of values
this.passedElement.setAttribute('value', itemsFiltered.join(this.config.delimiter));
} else {
const selectedOptionsFragment = document.createDocumentFragment();
// Add each list item to list
items.forEach((item) => {
// Create a standard select option
const option = this._getTemplate('option', item);
// Append it to fragment
selectedOptionsFragment.appendChild(option);
});
// Update selected choices
this.passedElement.innerHTML = '';
this.passedElement.appendChild(selectedOptionsFragment);
}
// Add each list item to list
items.forEach((item) => {
// Create new list element
const listItem = this._getTemplate('item', item);
// Append it to list
itemListFragment.appendChild(listItem);
});
return itemListFragment;
}
/**
* Render DOM with values
* @return
* @private
*/
render() {
this.currentState = this.store.getState();
// Only render if our state has actually changed
if (this.currentState !== this.prevState) {
// Choices
if (this.currentState.choices !== this.prevState.choices || this.currentState.groups !== this.prevState.groups) {
if (this.passedElement.type === 'select-multiple' || this.passedElement.type === 'select-one') {
// Get active groups/choices
const activeGroups = this.store.getGroupsFilteredByActive();
const activeChoices = this.store.getChoicesFilteredByActive();
let choiceListFragment = document.createDocumentFragment();
// Clear choices
this.choiceList.innerHTML = '';
// Scroll back to top of choices list
this.choiceList.scrollTop = 0;
// If we have grouped options
if (activeGroups.length >= 1 && this.isSearching !== true) {
choiceListFragment = this.renderGroups(activeGroups, activeChoices, choiceListFragment);
} else if (activeChoices.length >= 1) {
choiceListFragment = this.renderChoices(activeChoices, choiceListFragment);
}
if (choiceListFragment.childNodes && choiceListFragment.childNodes.length > 0) {
// If we actually have anything to add to our dropdown
// append it and highlight the first choice
this.choiceList.appendChild(choiceListFragment);
this._highlightChoice();
} else {
// Otherwise show a notice
const dropdownItem = this.isSearching ?
this._getTemplate('notice', this.config.noResultsText) :
this._getTemplate('notice', this.config.noChoicesText);
this.choiceList.appendChild(dropdownItem);
}
}
}
// Items
if (this.currentState.items !== this.prevState.items) {
const activeItems = this.store.getItemsFilteredByActive();
if (activeItems) {
// Create a fragment to store our list items
// (so we don't have to update the DOM for each item)
const itemListFragment = this.renderItems(activeItems);
// Clear list
this.itemList.innerHTML = '';
// If we have items to add
if (itemListFragment.childNodes) {
// Update list
this.itemList.appendChild(itemListFragment);
}
}
}
this.prevState = this.currentState;
}
}
/**
* Select item (a selected item can be deleted)
* @param {Element} item Element to select
* @return {Object} Class instance
* @public
*/
highlightItem(item) {
if (!item) return;
const id = item.id;
const groupId = item.groupId;
const callback = this.config.callbackOnHighlightItem;
this.store.dispatch(highlightItem(id, true));
// Run callback if it is a function
if (callback) {
if (isType('Function', callback)) {
const group = groupId >= 0 ? this.store.getGroupById(groupId) : null;
if(group && group.value) {
callback(id, item.value, group.value);
} else {
callback(id, item.value)
}
} else {
console.error('callbackOnHighlightItem: Callback is not a function');
}
}
return this;
}
/**
* Deselect item
* @param {Element} item Element to de-select
* @return {Object} Class instance
* @public
*/
unhighlightItem(item) {
if (!item) return;
const id = item.id;
const groupId = item.groupId;
const callback = this.config.callbackOnUnhighlightItem;
this.store.dispatch(highlightItem(id, false));
// Run callback if it is a function
if (callback) {
if (isType('Function', callback)) {
const group = groupId >= 0 ? this.store.getGroupById(groupId) : null;
if(group && group.value) {
callback(id, item.value, group.value);
} else {
callback(id, item.value)
}
} else {
console.error('callbackOnUnhighlightItem: Callback is not a function');
}
}
return this;
}
/**
* Highlight items within store
* @return {Object} Class instance
* @public
*/
highlightAll() {
const items = this.store.getItems();
items.forEach((item) => {
this.highlightItem(item);
});
return this;
}
/**
* Deselect items within store
* @return {Object} Class instance
* @public
*/
unhighlightAll() {
const items = this.store.getItems();
items.forEach((item) => {
this.unhighlightItem(item);
});
return this;
}
/**
* Remove an item from the store by its value
* @param {String} value Value to search for
* @return {Object} Class instance
* @public
*/
removeItemsByValue(value) {
if (!value || !isType('String', value)) {
console.error('removeItemsByValue: No value was passed to be removed');
return;
}
const items = this.store.getItemsFilteredByActive();
items.forEach((item) => {
if (item.value === value) {
this._removeItem(item);
}
});
return this;
}
/**
* Remove all items from store array
* @note Removed items are soft deleted
* @param {Number} excludedId Optionally exclude item by ID
* @return {Object} Class instance
* @public
*/
removeActiveItems(excludedId) {
const items = this.store.getItemsFilteredByActive();
items.forEach((item) => {
if (item.active && excludedId !== item.id) {
this._removeItem(item);
}
});
return this;
}
/**
* Remove all selected items from store
* @note Removed items are soft deleted
* @return {Object} Class instance
* @public
*/
removeHighlightedItems(runCallback = false) {
const items = this.store.getItemsFilteredByActive();
items.forEach((item) => {
if (item.highlighted && item.active) {
this._removeItem(item);
// If this action was performed by the user
// run the callback
if (runCallback) {
this._triggerChange(item.value);
}
}
});
return this;
}
/**
* Show dropdown to user by adding active state class
* @return {Object} Class instance
* @public
*/
showDropdown(focusInput = false) {
const body = document.body;
const html = document.documentElement;
const winHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight,
html.scrollHeight, html.offsetHeight);
this.containerOuter.classList.add(this.config.classNames.openState);
this.containerOuter.setAttribute('aria-expanded', 'true');
this.dropdown.classList.add(this.config.classNames.activeState);
const dimensions = this.dropdown.getBoundingClientRect();
const dropdownPos = Math.ceil(dimensions.top + window.scrollY + dimensions.height);
// If flip is enabled and the dropdown bottom position is greater than the window height flip the dropdown.
const shouldFlip = this.config.flip ? dropdownPos >= winHeight : false;
if (shouldFlip) {
this.containerOuter.classList.add(this.config.classNames.flippedState);
} else {
this.containerOuter.classList.remove(this.config.classNames.flippedState);
}
// Optionally focus the input if we have a search input
if (focusInput && this.canSearch && document.activeElement !== this.input) {
this.input.focus();
}
return this;
}
/**
* Hide dropdown from user
* @return {Object} Class instance
* @public
*/
hideDropdown(blurInput = false) {
// A dropdown flips if it does not have space within the page
const isFlipped = this.containerOuter.classList.contains(this.config.classNames.flippedState);
this.containerOuter.classList.remove(this.config.classNames.openState);
this.containerOuter.setAttribute('aria-expanded', 'false');
this.dropdown.classList.remove(this.config.classNames.activeState);
if (isFlipped) {
this.containerOuter.classList.remove(this.config.classNames.flippedState);
}
// Optionally blur the input if we have a search input
if (blurInput && this.canSearch && document.activeElement === this.input) {
this.input.blur();
}
return this;
}
/**
* Determine whether to hide or show dropdown based on its current state
* @return {Object} Class instance
* @public
*/
toggleDropdown() {
const hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState);
if (hasActiveDropdown) {
this.hideDropdown();
} else {
this.showDropdown(true);
}
return this;
}
/**
* Get value(s) of input (i.e. inputted items (text) or selected choices (select))
* @param {Boolean} valueOnly Get only values of selected items, otherwise return selected items
* @return {Array/String} selected value (select-one) or array of selected items (inputs & select-multiple)
* @public
*/
getValue(valueOnly = false) {
const items = this.store.getItemsFilteredByActive();
const selectedItems = [];
items.forEach((item) => {
if (this.passedElement.type === 'text') {
selectedItems.push(valueOnly ? item.value : item);
} else if (item.active) {
selectedItems.push(valueOnly ? item.value : item);
}
});
if (this.passedElement.type === 'select-one') {
return selectedItems[0];
}
return selectedItems;
}
/**
* Set value of input. If the input is a select box, a choice will be created and selected otherwise
* an item will created directly.
* @param {Array} args Array of value objects or value strings
* @return {Object} Class instance
* @public
*/
setValue(args) {
if (this.initialised === true) {
// Convert args to an itterable array
const values = [...args];
values.forEach((item) => {
if (isType('Object', item)) {
if (!item.value) return;
// If we are dealing with a select input, we need to create an option first
// that is then selected. For text inputs we can just add items normally.
if (this.passedElement.type !== 'text') {
this._addChoice(true, false, item.value, item.label, -1);
} else {
this._addItem(item.value, item.label, item.id);
}
} else if (isType('String', item)) {
if (this.passedElement.type !== 'text') {
this._addChoice(true, false, item, item, -1);
} else {
this._addItem(item);
}
}
});
}
return this;
}
/**
* Select value of select box via the value of an existing choice
* @param {Array/String} value An array of strings of a single string
* @return {Object} Class instance
* @public
*/
setValueByChoice(value) {
if (this.passedElement.type !== 'text') {
const choices = this.store.getChoices();
// If only one value has been passed, convert to array
const choiceValue = isType('Array', value) ? value : [value];
// Loop through each value and
choiceValue.forEach((val) => {
const foundChoice = choices.find((choice) => {
// Check 'value' property exists and the choice isn't already selected
return choice.value === val;
});
if (foundChoice) {
if (!foundChoice.selected) {
this._addItem(foundChoice.value, foundChoice.label, foundChoice.id, foundChoice.groupId);
} else {
console.warn('Attempting to select choice already selected');
}
} else {
console.warn('Attempting to select choice that does not exist');
}
});
}
return this;
}
/**
* Direct populate choices
* @param {Array} choices - Choices to insert
* @param {String} value - Name of 'value' property
* @param {String} label - Name of 'label' property
* @param {Boolean} replaceChoices Whether existing choices should be removed
* @return {Object} Class instance
* @public
*/
setChoices(choices, value, label, replaceChoices = false) {
if (this.initialised === true) {
if (this.passedElement.type === 'select-one' || this.passedElement.type === 'select-multiple') {
if (!isType('Array', choices) || !value) return;
// Clear choices if needed
if(replaceChoices) {
this._clearChoices();
}
// Add choices if passed
if (choices && choices.length) {
this.containerOuter.classList.remove(this.config.classNames.loadingState);
choices.forEach((result, index) => {
const isSelected = result.selected ? result.selected : false;
const isDisabled = result.disabled ? result.disabled : false;
if (result.choices) {
this._addGroup(result, index, value, label);
} else {
this._addChoice(isSelected, isDisabled, result[value], result[label]);
}
});
}
}
}
return this;
}
/**
* Clear items,choices and groups
* @note Hard delete
* @return {Object} Class instance
* @public
*/
clearStore() {
this.store.dispatch(clearAll());
return this;
}
/**
* Set value of input to blank
* @return {Object} Class instance
* @public
*/
clearInput() {
if (this.input.value) this.input.value = '';
if (this.passedElement.type !== 'select-one') {
this.input.style.width = getWidthOfInput(this.input);
}
if (this.passedElement.type !== 'text' && this.config.search) {
this.isSearching = false;
this.store.dispatch(activateChoices(true));
}
return this;
}
/**
* Enable interaction with Choices
* @return {Object} Class instance
*/
enable() {
this.passedElement.disabled = false;
const isDisabled = this.containerOuter.classList.contains(this.config.classNames.disabledState);
if (this.initialised && isDisabled) {
this._addEventListeners();
this.passedElement.removeAttribute('disabled');
this.input.removeAttribute('disabled');
this.containerOuter.classList.remove(this.config.classNames.disabledState);
this.containerOuter.removeAttribute('aria-disabled');
}
return this;
}
/**
* Disable interaction with Choices
* @return {Object} Class instance
* @public
*/
disable() {
this.passedElement.disabled = true;
const isEnabled = !this.containerOuter.classList.contains(this.config.classNames.disabledState);
if (this.initialised && isEnabled) {
this._removeEventListeners();
this.passedElement.setAttribute('disabled', '');
this.input.setAttribute('disabled', '');
this.containerOuter.classList.add(this.config.classNames.disabledState);
this.containerOuter.setAttribute('aria-disabled', 'true');
}
return this;
}
/**
* Populate options via ajax callback
* @param {Function} fn Passed
* @return {Object} Class instance
* @public
*/
ajax(fn) {
if (this.initialised === true) {
if (this.passedElement.type === 'select-one' || this.passedElement.type === 'select-multiple') {
// Show loading text
this._handleLoadingState(true);
// Run callback
fn(this._ajaxCallback());
}
}
return this;
}
/*===== End of Public functions ======*/
/*=============================================
= Private functions =
=============================================*/
/**
* Call change callback
* @param {String} value - last added/deleted/selected value
* @return
* @private
*/
_triggerChange(value) {
if (!value) return;
const callback = this.config.callbackOnChange;
// Run callback if it is a function
if (callback) {
if (isType('Function', callback)) {
callback(value);
} else {
console.error('callbackOnChange: Callback is not a function');
}
}
}
/**
* Process enter/click of an item button
* @param {Array} activeItems The currently active items
* @param {Element} element Button being interacted with
* @return
* @private
*/
_handleButtonAction(activeItems, element) {
if (!activeItems || !element) return;
// If we are clicking on a button
if (this.config.removeItems && this.config.removeItemButton) {
const itemId = element.parentNode.getAttribute('data-id');
const itemToRemove = activeItems.find((item) => item.id === parseInt(itemId, 10));
// Remove item associated with button
this._removeItem(itemToRemove);
this._triggerChange(itemToRemove.value);
if (this.passedElement.type === 'select-one') {
const placeholder = this.config.placeholder ? this.config.placeholderValue || this.passedElement.getAttribute('placeholder') :
false;
if (placeholder) {
const placeholderItem = this._getTemplate('placeholder', placeholder);
this.itemList.appendChild(placeholderItem);
}
}
}
}
/**
* Process click of an item
* @param {Array} activeItems The currently active items
* @param {Element} element Item being interacted with
* @param {Boolean} hasShiftKey Whether the user has the shift key active
* @return
* @private
*/
_handleItemAction(activeItems, element, hasShiftKey = false) {
if (!activeItems || !element) return;
// If we are clicking on an item
if (this.config.removeItems && this.passedElement.type !== 'select-one') {
const passedId = element.getAttribute('data-id');
// We only want to select one item with a click
// so we deselect any items that aren't the target
// unless shift is being pressed
activeItems.forEach((item) => {
if (item.id === parseInt(passedId, 10) && !item.highlighted) {
this.highlightItem(item);
} else if (!hasShiftKey) {
if (item.highlighted) {
this.unhighlightItem(item);
}
}
});
// Focus input as without focus, a user cannot do anything with a
// highlighted item
if (document.activeElement !== this.input) this.input.focus();
}
}
/**
* Process click of a choice
* @param {Array} activeItems The currently active items
* @param {Element} element Choice being interacted with
* @return {[type]} [description]
*/
_handleChoiceAction(activeItems, element) {
if (!activeItems || !element) return;
// If we are clicking on an option
const id = element.getAttribute('data-id');
const choice = this.store.getChoiceById(id);
const hasActiveDropdown = this.dropdown.classList.contains(this.config.classNames.activeState);
if (choice && !choice.selected && !choice.disabled) {
const canAddItem = this._canAddItem(activeItems, choice.value);
if (canAddItem.response) {
this._addItem(choice.value, choice.label, choice.id, choice.groupId);
this._triggerChange(choice.value);
}
}
this.clearInput(this.passedElement);
// We wont to close the dropdown if we are dealing with a single select box
if (hasActiveDropdown && this.passedElement.type === 'select-one') {
this.hideDropdown();
this.containerOuter.focus();
}
}
/**
* Process back space event
* @param {Array} activeItems items
* @return
* @private
*/
_handleBackspace(activeItems) {
if (this.config.removeItems && activeItems) {
const lastItem = activeItems[activeItems.length - 1];
const hasHighlightedItems = activeItems.some((item) => item.highlighted === true);
// If editing the last item is allowed and there are not other selected items,
// we can edit the item value. Otherwise if we can remove items, remove all selected items
if (this.config.editItems && !hasHighlightedItems && lastItem) {