/
choices.js
6925 lines (6272 loc) · 203 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
/*! choices.js v10.2.0 | © 2022 Josh Johnson | https://github.com/jshjohnson/Choices#readme */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Choices"] = factory();
else
root["Choices"] = factory();
})(window, function() {
return /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 282:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.clearChoices = exports.activateChoices = exports.filterChoices = exports.addChoice = void 0;
var constants_1 = __webpack_require__(883);
var addChoice = function (_a) {
var value = _a.value,
label = _a.label,
id = _a.id,
groupId = _a.groupId,
disabled = _a.disabled,
elementId = _a.elementId,
customProperties = _a.customProperties,
placeholder = _a.placeholder,
keyCode = _a.keyCode;
return {
type: constants_1.ACTION_TYPES.ADD_CHOICE,
value: value,
label: label,
id: id,
groupId: groupId,
disabled: disabled,
elementId: elementId,
customProperties: customProperties,
placeholder: placeholder,
keyCode: keyCode
};
};
exports.addChoice = addChoice;
var filterChoices = function (results) {
return {
type: constants_1.ACTION_TYPES.FILTER_CHOICES,
results: results
};
};
exports.filterChoices = filterChoices;
var activateChoices = function (active) {
if (active === void 0) {
active = true;
}
return {
type: constants_1.ACTION_TYPES.ACTIVATE_CHOICES,
active: active
};
};
exports.activateChoices = activateChoices;
var clearChoices = function () {
return {
type: constants_1.ACTION_TYPES.CLEAR_CHOICES
};
};
exports.clearChoices = clearChoices;
/***/ }),
/***/ 783:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.addGroup = void 0;
var constants_1 = __webpack_require__(883);
var addGroup = function (_a) {
var value = _a.value,
id = _a.id,
active = _a.active,
disabled = _a.disabled;
return {
type: constants_1.ACTION_TYPES.ADD_GROUP,
value: value,
id: id,
active: active,
disabled: disabled
};
};
exports.addGroup = addGroup;
/***/ }),
/***/ 464:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.highlightItem = exports.removeItem = exports.addItem = void 0;
var constants_1 = __webpack_require__(883);
var addItem = function (_a) {
var value = _a.value,
label = _a.label,
id = _a.id,
choiceId = _a.choiceId,
groupId = _a.groupId,
customProperties = _a.customProperties,
placeholder = _a.placeholder,
keyCode = _a.keyCode;
return {
type: constants_1.ACTION_TYPES.ADD_ITEM,
value: value,
label: label,
id: id,
choiceId: choiceId,
groupId: groupId,
customProperties: customProperties,
placeholder: placeholder,
keyCode: keyCode
};
};
exports.addItem = addItem;
var removeItem = function (id, choiceId) {
return {
type: constants_1.ACTION_TYPES.REMOVE_ITEM,
id: id,
choiceId: choiceId
};
};
exports.removeItem = removeItem;
var highlightItem = function (id, highlighted) {
return {
type: constants_1.ACTION_TYPES.HIGHLIGHT_ITEM,
id: id,
highlighted: highlighted
};
};
exports.highlightItem = highlightItem;
/***/ }),
/***/ 137:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.setIsLoading = exports.resetTo = exports.clearAll = void 0;
var constants_1 = __webpack_require__(883);
var clearAll = function () {
return {
type: constants_1.ACTION_TYPES.CLEAR_ALL
};
};
exports.clearAll = clearAll;
var resetTo = function (state) {
return {
type: constants_1.ACTION_TYPES.RESET_TO,
state: state
};
};
exports.resetTo = resetTo;
var setIsLoading = function (isLoading) {
return {
type: constants_1.ACTION_TYPES.SET_IS_LOADING,
isLoading: isLoading
};
};
exports.setIsLoading = setIsLoading;
/***/ }),
/***/ 373:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var __spreadArray = this && this.__spreadArray || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = this && this.__importDefault || function (mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", ({
value: true
}));
var deepmerge_1 = __importDefault(__webpack_require__(996));
/* eslint-disable @typescript-eslint/no-explicit-any */
var fuse_js_1 = __importDefault(__webpack_require__(221));
var choices_1 = __webpack_require__(282);
var groups_1 = __webpack_require__(783);
var items_1 = __webpack_require__(464);
var misc_1 = __webpack_require__(137);
var components_1 = __webpack_require__(520);
var constants_1 = __webpack_require__(883);
var defaults_1 = __webpack_require__(789);
var utils_1 = __webpack_require__(799);
var reducers_1 = __webpack_require__(655);
var store_1 = __importDefault(__webpack_require__(744));
var templates_1 = __importDefault(__webpack_require__(686));
/** @see {@link http://browserhacks.com/#hack-acea075d0ac6954f275a70023906050c} */
var IS_IE11 = '-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style;
var USER_DEFAULTS = {};
/**
* Choices
* @author Josh Johnson<josh@joshuajohnson.co.uk>
*/
var Choices = /** @class */function () {
function Choices(element, userConfig) {
if (element === void 0) {
element = '[data-choice]';
}
if (userConfig === void 0) {
userConfig = {};
}
var _this = this;
if (userConfig.allowHTML === undefined) {
console.warn('Deprecation warning: allowHTML will default to false in a future release. To render HTML in Choices, you will need to set it to true. Setting allowHTML will suppress this message.');
}
this.config = deepmerge_1.default.all([defaults_1.DEFAULT_CONFIG, Choices.defaults.options, userConfig],
// When merging array configs, replace with a copy of the userConfig array,
// instead of concatenating with the default array
{
arrayMerge: function (_, sourceArray) {
return __spreadArray([], sourceArray, true);
}
});
var invalidConfigOptions = (0, utils_1.diff)(this.config, defaults_1.DEFAULT_CONFIG);
if (invalidConfigOptions.length) {
console.warn('Unknown config option(s) passed', invalidConfigOptions.join(', '));
}
var passedElement = typeof element === 'string' ? document.querySelector(element) : element;
if (!(passedElement instanceof HTMLInputElement || passedElement instanceof HTMLSelectElement)) {
throw TypeError('Expected one of the following types text|select-one|select-multiple');
}
this._isTextElement = passedElement.type === constants_1.TEXT_TYPE;
this._isSelectOneElement = passedElement.type === constants_1.SELECT_ONE_TYPE;
this._isSelectMultipleElement = passedElement.type === constants_1.SELECT_MULTIPLE_TYPE;
this._isSelectElement = this._isSelectOneElement || this._isSelectMultipleElement;
this.config.searchEnabled = this._isSelectMultipleElement || this.config.searchEnabled;
if (!['auto', 'always'].includes("".concat(this.config.renderSelectedChoices))) {
this.config.renderSelectedChoices = 'auto';
}
if (userConfig.addItemFilter && typeof userConfig.addItemFilter !== 'function') {
var re = userConfig.addItemFilter instanceof RegExp ? userConfig.addItemFilter : new RegExp(userConfig.addItemFilter);
this.config.addItemFilter = re.test.bind(re);
}
if (this._isTextElement) {
this.passedElement = new components_1.WrappedInput({
element: passedElement,
classNames: this.config.classNames,
delimiter: this.config.delimiter
});
} else {
this.passedElement = new components_1.WrappedSelect({
element: passedElement,
classNames: this.config.classNames,
template: function (data) {
return _this._templates.option(data);
}
});
}
this.initialised = false;
this._store = new store_1.default();
this._initialState = reducers_1.defaultState;
this._currentState = reducers_1.defaultState;
this._prevState = reducers_1.defaultState;
this._currentValue = '';
this._canSearch = !!this.config.searchEnabled;
this._isScrollingOnIe = false;
this._highlightPosition = 0;
this._wasTap = true;
this._placeholderValue = this._generatePlaceholderValue();
this._baseId = (0, utils_1.generateId)(this.passedElement.element, 'choices-');
/**
* setting direction in cases where it's explicitly set on passedElement
* or when calculated direction is different from the document
*/
this._direction = this.passedElement.dir;
if (!this._direction) {
var elementDirection = window.getComputedStyle(this.passedElement.element).direction;
var documentDirection = window.getComputedStyle(document.documentElement).direction;
if (elementDirection !== documentDirection) {
this._direction = elementDirection;
}
}
this._idNames = {
itemChoice: 'item-choice'
};
if (this._isSelectElement) {
// Assign preset groups from passed element
this._presetGroups = this.passedElement.optionGroups;
// Assign preset options from passed element
this._presetOptions = this.passedElement.options;
}
// Assign preset choices from passed object
this._presetChoices = this.config.choices;
// Assign preset items from passed object first
this._presetItems = this.config.items;
// Add any values passed from attribute
if (this.passedElement.value && this._isTextElement) {
var splitValues = this.passedElement.value.split(this.config.delimiter);
this._presetItems = this._presetItems.concat(splitValues);
}
// Create array of choices from option elements
if (this.passedElement.options) {
this.passedElement.options.forEach(function (option) {
_this._presetChoices.push({
value: option.value,
label: option.innerHTML,
selected: !!option.selected,
disabled: option.disabled || option.parentNode.disabled,
placeholder: option.value === '' || option.hasAttribute('placeholder'),
customProperties: (0, utils_1.parseCustomProperties)(option.dataset.customProperties)
});
});
}
this._render = this._render.bind(this);
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._onFormReset = this._onFormReset.bind(this);
this._onSelectKey = this._onSelectKey.bind(this);
this._onEnterKey = this._onEnterKey.bind(this);
this._onEscapeKey = this._onEscapeKey.bind(this);
this._onDirectionKey = this._onDirectionKey.bind(this);
this._onDeleteKey = this._onDeleteKey.bind(this);
// If element has already been initialised with Choices, fail silently
if (this.passedElement.isActive) {
if (!this.config.silent) {
console.warn('Trying to initialise Choices on element already initialised', {
element: element
});
}
this.initialised = true;
return;
}
// Let's go
this.init();
}
Object.defineProperty(Choices, "defaults", {
get: function () {
return Object.preventExtensions({
get options() {
return USER_DEFAULTS;
},
get templates() {
return templates_1.default;
}
});
},
enumerable: false,
configurable: true
});
Choices.prototype.init = function () {
if (this.initialised) {
return;
}
this._createTemplates();
this._createElements();
this._createStructure();
this._store.subscribe(this._render);
this._render();
this._addEventListeners();
var shouldDisable = !this.config.addItems || this.passedElement.element.hasAttribute('disabled');
if (shouldDisable) {
this.disable();
}
this.initialised = true;
var callbackOnInit = this.config.callbackOnInit;
// Run callback if it is a function
if (callbackOnInit && typeof callbackOnInit === 'function') {
callbackOnInit.call(this);
}
};
Choices.prototype.destroy = function () {
if (!this.initialised) {
return;
}
this._removeEventListeners();
this.passedElement.reveal();
this.containerOuter.unwrap(this.passedElement.element);
this.clearStore();
if (this._isSelectElement) {
this.passedElement.options = this._presetOptions;
}
this._templates = templates_1.default;
this.initialised = false;
};
Choices.prototype.enable = function () {
if (this.passedElement.isDisabled) {
this.passedElement.enable();
}
if (this.containerOuter.isDisabled) {
this._addEventListeners();
this.input.enable();
this.containerOuter.enable();
}
return this;
};
Choices.prototype.disable = function () {
if (!this.passedElement.isDisabled) {
this.passedElement.disable();
}
if (!this.containerOuter.isDisabled) {
this._removeEventListeners();
this.input.disable();
this.containerOuter.disable();
}
return this;
};
Choices.prototype.highlightItem = function (item, runEvent) {
if (runEvent === void 0) {
runEvent = true;
}
if (!item || !item.id) {
return this;
}
var id = item.id,
_a = item.groupId,
groupId = _a === void 0 ? -1 : _a,
_b = item.value,
value = _b === void 0 ? '' : _b,
_c = item.label,
label = _c === void 0 ? '' : _c;
var group = groupId >= 0 ? this._store.getGroupById(groupId) : null;
this._store.dispatch((0, items_1.highlightItem)(id, true));
if (runEvent) {
this.passedElement.triggerEvent(constants_1.EVENTS.highlightItem, {
id: id,
value: value,
label: label,
groupValue: group && group.value ? group.value : null
});
}
return this;
};
Choices.prototype.unhighlightItem = function (item) {
if (!item || !item.id) {
return this;
}
var id = item.id,
_a = item.groupId,
groupId = _a === void 0 ? -1 : _a,
_b = item.value,
value = _b === void 0 ? '' : _b,
_c = item.label,
label = _c === void 0 ? '' : _c;
var group = groupId >= 0 ? this._store.getGroupById(groupId) : null;
this._store.dispatch((0, items_1.highlightItem)(id, false));
this.passedElement.triggerEvent(constants_1.EVENTS.highlightItem, {
id: id,
value: value,
label: label,
groupValue: group && group.value ? group.value : null
});
return this;
};
Choices.prototype.highlightAll = function () {
var _this = this;
this._store.items.forEach(function (item) {
return _this.highlightItem(item);
});
return this;
};
Choices.prototype.unhighlightAll = function () {
var _this = this;
this._store.items.forEach(function (item) {
return _this.unhighlightItem(item);
});
return this;
};
Choices.prototype.removeActiveItemsByValue = function (value) {
var _this = this;
this._store.activeItems.filter(function (item) {
return item.value === value;
}).forEach(function (item) {
return _this._removeItem(item);
});
return this;
};
Choices.prototype.removeActiveItems = function (excludedId) {
var _this = this;
this._store.activeItems.filter(function (_a) {
var id = _a.id;
return id !== excludedId;
}).forEach(function (item) {
return _this._removeItem(item);
});
return this;
};
Choices.prototype.removeHighlightedItems = function (runEvent) {
var _this = this;
if (runEvent === void 0) {
runEvent = false;
}
this._store.highlightedActiveItems.forEach(function (item) {
_this._removeItem(item);
// If this action was performed by the user
// trigger the event
if (runEvent) {
_this._triggerChange(item.value);
}
});
return this;
};
Choices.prototype.showDropdown = function (preventInputFocus) {
var _this = this;
if (this.dropdown.isActive) {
return this;
}
requestAnimationFrame(function () {
_this.dropdown.show();
_this.containerOuter.open(_this.dropdown.distanceFromTopWindow);
if (!preventInputFocus && _this._canSearch) {
_this.input.focus();
}
_this.passedElement.triggerEvent(constants_1.EVENTS.showDropdown, {});
});
return this;
};
Choices.prototype.hideDropdown = function (preventInputBlur) {
var _this = this;
if (!this.dropdown.isActive) {
return this;
}
requestAnimationFrame(function () {
_this.dropdown.hide();
_this.containerOuter.close();
if (!preventInputBlur && _this._canSearch) {
_this.input.removeActiveDescendant();
_this.input.blur();
}
_this.passedElement.triggerEvent(constants_1.EVENTS.hideDropdown, {});
});
return this;
};
Choices.prototype.getValue = function (valueOnly) {
if (valueOnly === void 0) {
valueOnly = false;
}
var values = this._store.activeItems.reduce(function (selectedItems, item) {
var itemValue = valueOnly ? item.value : item;
selectedItems.push(itemValue);
return selectedItems;
}, []);
return this._isSelectOneElement ? values[0] : values;
};
Choices.prototype.setValue = function (items) {
var _this = this;
if (!this.initialised) {
return this;
}
items.forEach(function (value) {
return _this._setChoiceOrItem(value);
});
return this;
};
Choices.prototype.setChoiceByValue = function (value) {
var _this = this;
if (!this.initialised || this._isTextElement) {
return this;
}
// If only one value has been passed, convert to array
var choiceValue = Array.isArray(value) ? value : [value];
// Loop through each value and
choiceValue.forEach(function (val) {
return _this._findAndSelectChoiceByValue(val);
});
return this;
};
/**
* Set choices of select input via an array of objects (or function that returns array of object or promise of it),
* a value field name and a label field name.
* This behaves the same as passing items via the choices option but can be called after initialising Choices.
* This can also be used to add groups of choices (see example 2); Optionally pass a true `replaceChoices` value to remove any existing choices.
* Optionally pass a `customProperties` object to add additional data to your choices (useful when searching/filtering etc).
*
* **Input types affected:** select-one, select-multiple
*
* @example
* ```js
* const example = new Choices(element);
*
* example.setChoices([
* {value: 'One', label: 'Label One', disabled: true},
* {value: 'Two', label: 'Label Two', selected: true},
* {value: 'Three', label: 'Label Three'},
* ], 'value', 'label', false);
* ```
*
* @example
* ```js
* const example = new Choices(element);
*
* example.setChoices(async () => {
* try {
* const items = await fetch('/items');
* return items.json()
* } catch(err) {
* console.error(err)
* }
* });
* ```
*
* @example
* ```js
* const example = new Choices(element);
*
* example.setChoices([{
* label: 'Group one',
* id: 1,
* disabled: false,
* choices: [
* {value: 'Child One', label: 'Child One', selected: true},
* {value: 'Child Two', label: 'Child Two', disabled: true},
* {value: 'Child Three', label: 'Child Three'},
* ]
* },
* {
* label: 'Group two',
* id: 2,
* disabled: false,
* choices: [
* {value: 'Child Four', label: 'Child Four', disabled: true},
* {value: 'Child Five', label: 'Child Five'},
* {value: 'Child Six', label: 'Child Six', customProperties: {
* description: 'Custom description about child six',
* random: 'Another random custom property'
* }},
* ]
* }], 'value', 'label', false);
* ```
*/
Choices.prototype.setChoices = function (choicesArrayOrFetcher, value, label, replaceChoices) {
var _this = this;
if (choicesArrayOrFetcher === void 0) {
choicesArrayOrFetcher = [];
}
if (value === void 0) {
value = 'value';
}
if (label === void 0) {
label = 'label';
}
if (replaceChoices === void 0) {
replaceChoices = false;
}
if (!this.initialised) {
throw new ReferenceError("setChoices was called on a non-initialized instance of Choices");
}
if (!this._isSelectElement) {
throw new TypeError("setChoices can't be used with INPUT based Choices");
}
if (typeof value !== 'string' || !value) {
throw new TypeError("value parameter must be a name of 'value' field in passed objects");
}
// Clear choices if needed
if (replaceChoices) {
this.clearChoices();
}
if (typeof choicesArrayOrFetcher === 'function') {
// it's a choices fetcher function
var fetcher_1 = choicesArrayOrFetcher(this);
if (typeof Promise === 'function' && fetcher_1 instanceof Promise) {
// that's a promise
// eslint-disable-next-line no-promise-executor-return
return new Promise(function (resolve) {
return requestAnimationFrame(resolve);
}).then(function () {
return _this._handleLoadingState(true);
}).then(function () {
return fetcher_1;
}).then(function (data) {
return _this.setChoices(data, value, label, replaceChoices);
}).catch(function (err) {
if (!_this.config.silent) {
console.error(err);
}
}).then(function () {
return _this._handleLoadingState(false);
}).then(function () {
return _this;
});
}
// function returned something else than promise, let's check if it's an array of choices
if (!Array.isArray(fetcher_1)) {
throw new TypeError(".setChoices first argument function must return either array of choices or Promise, got: ".concat(typeof fetcher_1));
}
// recursion with results, it's sync and choices were cleared already
return this.setChoices(fetcher_1, value, label, false);
}
if (!Array.isArray(choicesArrayOrFetcher)) {
throw new TypeError(".setChoices must be called either with array of choices with a function resulting into Promise of array of choices");
}
this.containerOuter.removeLoadingState();
this._startLoading();
choicesArrayOrFetcher.forEach(function (groupOrChoice) {
if (groupOrChoice.choices) {
_this._addGroup({
id: groupOrChoice.id ? parseInt("".concat(groupOrChoice.id), 10) : null,
group: groupOrChoice,
valueKey: value,
labelKey: label
});
} else {
var choice = groupOrChoice;
_this._addChoice({
value: choice[value],
label: choice[label],
isSelected: !!choice.selected,
isDisabled: !!choice.disabled,
placeholder: !!choice.placeholder,
customProperties: choice.customProperties
});
}
});
this._stopLoading();
return this;
};
Choices.prototype.clearChoices = function () {
this._store.dispatch((0, choices_1.clearChoices)());
return this;
};
Choices.prototype.clearStore = function () {
this._store.dispatch((0, misc_1.clearAll)());
return this;
};
Choices.prototype.clearInput = function () {
var shouldSetInputWidth = !this._isSelectOneElement;
this.input.clear(shouldSetInputWidth);
if (!this._isTextElement && this._canSearch) {
this._isSearching = false;
this._store.dispatch((0, choices_1.activateChoices)(true));
}
return this;
};
Choices.prototype._render = function () {
if (this._store.isLoading()) {
return;
}
this._currentState = this._store.state;
var stateChanged = this._currentState.choices !== this._prevState.choices || this._currentState.groups !== this._prevState.groups || this._currentState.items !== this._prevState.items;
var shouldRenderChoices = this._isSelectElement;
var shouldRenderItems = this._currentState.items !== this._prevState.items;
if (!stateChanged) {
return;
}
if (shouldRenderChoices) {
this._renderChoices();
}
if (shouldRenderItems) {
this._renderItems();
}
this._prevState = this._currentState;
};
Choices.prototype._renderChoices = function () {
var _this = this;
var _a = this._store,
activeGroups = _a.activeGroups,
activeChoices = _a.activeChoices;
var choiceListFragment = document.createDocumentFragment();
this.choiceList.clear();
if (this.config.resetScrollPosition) {
requestAnimationFrame(function () {
return _this.choiceList.scrollToTop();
});
}
// If we have grouped options
if (activeGroups.length >= 1 && !this._isSearching) {
// If we have a placeholder choice along with groups
var activePlaceholders = activeChoices.filter(function (activeChoice) {
return activeChoice.placeholder === true && activeChoice.groupId === -1;
});
if (activePlaceholders.length >= 1) {
choiceListFragment = this._createChoicesFragment(activePlaceholders, choiceListFragment);
}
choiceListFragment = this._createGroupsFragment(activeGroups, activeChoices, choiceListFragment);
} else if (activeChoices.length >= 1) {
choiceListFragment = this._createChoicesFragment(activeChoices, choiceListFragment);
}
// If we have choices to show
if (choiceListFragment.childNodes && choiceListFragment.childNodes.length > 0) {
var activeItems = this._store.activeItems;
var canAddItem = this._canAddItem(activeItems, this.input.value);
// ...and we can select them
if (canAddItem.response) {
// ...append them and highlight the first choice
this.choiceList.append(choiceListFragment);
this._highlightChoice();
} else {
var notice = this._getTemplate('notice', canAddItem.notice);
this.choiceList.append(notice);
}
} else {
// Otherwise show a notice
var dropdownItem = void 0;
var notice = void 0;
if (this._isSearching) {
notice = typeof this.config.noResultsText === 'function' ? this.config.noResultsText() : this.config.noResultsText;
dropdownItem = this._getTemplate('notice', notice, 'no-results');
} else {
notice = typeof this.config.noChoicesText === 'function' ? this.config.noChoicesText() : this.config.noChoicesText;
dropdownItem = this._getTemplate('notice', notice, 'no-choices');
}
this.choiceList.append(dropdownItem);
}
};
Choices.prototype._renderItems = function () {
var activeItems = this._store.activeItems || [];
this.itemList.clear();
// Create a fragment to store our list items
// (so we don't have to update the DOM for each item)
var itemListFragment = this._createItemsFragment(activeItems);
// If we have items to add, append them
if (itemListFragment.childNodes) {
this.itemList.append(itemListFragment);
}
};
Choices.prototype._createGroupsFragment = function (groups, choices, fragment) {
var _this = this;
if (fragment === void 0) {
fragment = document.createDocumentFragment();
}
var getGroupChoices = function (group) {
return choices.filter(function (choice) {
if (_this._isSelectOneElement) {
return choice.groupId === group.id;
}
return choice.groupId === group.id && (_this.config.renderSelectedChoices === 'always' || !choice.selected);
});
};
// If sorting is enabled, filter groups
if (this.config.shouldSort) {
groups.sort(this.config.sorter);
}
groups.forEach(function (group) {
var groupChoices = getGroupChoices(group);
if (groupChoices.length >= 1) {
var dropdownGroup = _this._getTemplate('choiceGroup', group);
fragment.appendChild(dropdownGroup);
_this._createChoicesFragment(groupChoices, fragment, true);
}
});
return fragment;
};
Choices.prototype._createChoicesFragment = function (choices, fragment, withinGroup) {
var _this = this;
if (fragment === void 0) {
fragment = document.createDocumentFragment();
}
if (withinGroup === void 0) {
withinGroup = false;
}
// Create a fragment to store our list items (so we don't have to update the DOM for each item)
var _a = this.config,
renderSelectedChoices = _a.renderSelectedChoices,
searchResultLimit = _a.searchResultLimit,
renderChoiceLimit = _a.renderChoiceLimit;
var filter = this._isSearching ? utils_1.sortByScore : this.config.sorter;
var appendChoice = function (choice) {
var shouldRender = renderSelectedChoices === 'auto' ? _this._isSelectOneElement || !choice.selected : true;
if (shouldRender) {
var dropdownItem = _this._getTemplate('choice', choice, _this.config.itemSelectText);
fragment.appendChild(dropdownItem);
}
};
var rendererableChoices = choices;
if (renderSelectedChoices === 'auto' && !this._isSelectOneElement) {
rendererableChoices = choices.filter(function (choice) {
return !choice.selected;
});
}
// Split array into placeholders and "normal" choices
var _b = rendererableChoices.reduce(function (acc, choice) {
if (choice.placeholder) {
acc.placeholderChoices.push(choice);
} else {
acc.normalChoices.push(choice);
}
return acc;
}, {
placeholderChoices: [],
normalChoices: []
}),
placeholderChoices = _b.placeholderChoices,
normalChoices = _b.normalChoices;
// If sorting is enabled or the user is searching, filter choices
if (this.config.shouldSort || this._isSearching) {
normalChoices.sort(filter);
}
var choiceLimit = rendererableChoices.length;
// Prepend placeholeder
var sortedChoices = this._isSelectOneElement ? __spreadArray(__spreadArray([], placeholderChoices, true), normalChoices, true) : normalChoices;
if (this._isSearching) {
choiceLimit = searchResultLimit;
} else if (renderChoiceLimit && renderChoiceLimit > 0 && !withinGroup) {
choiceLimit = renderChoiceLimit;
}
// Add each choice to dropdown within range
for (var i = 0; i < choiceLimit; i += 1) {
if (sortedChoices[i]) {
appendChoice(sortedChoices[i]);
}
}
return fragment;
};
Choices.prototype._createItemsFragment = function (items, fragment) {
var _this = this;
if (fragment === void 0) {
fragment = document.createDocumentFragment();
}
// Create fragment to add elements to
var _a = this.config,
shouldSortItems = _a.shouldSortItems,
sorter = _a.sorter,
removeItemButton = _a.removeItemButton;
// If sorting is enabled, filter items
if (shouldSortItems && !this._isSelectOneElement) {
items.sort(sorter);
}
if (this._isTextElement) {
// Update the value of the hidden input
this.passedElement.value = items.map(function (_a) {
var value = _a.value;
return value;
}).join(this.config.delimiter);
} else {
// Update the options of the hidden input
this.passedElement.options = items;
}
var addItemToFragment = function (item) {
// Create new list element
var listItem = _this._getTemplate('item', item, removeItemButton);
// Append it to list
fragment.appendChild(listItem);
};
// Add each list item to list
items.forEach(addItemToFragment);
return fragment;
};
Choices.prototype._triggerChange = function (value) {
if (value === undefined || value === null) {
return;
}
this.passedElement.triggerEvent(constants_1.EVENTS.change, {
value: value
});
};
Choices.prototype._selectPlaceholderChoice = function (placeholderChoice) {
this._addItem({
value: placeholderChoice.value,
label: placeholderChoice.label,
choiceId: placeholderChoice.id,
groupId: placeholderChoice.groupId,
placeholder: placeholderChoice.placeholder
});
this._triggerChange(placeholderChoice.value);
};
Choices.prototype._handleButtonAction = function (activeItems, element) {
if (!activeItems || !element || !this.config.removeItems || !this.config.removeItemButton) {
return;
}
var itemId = element.parentNode && element.parentNode.dataset.id;
var itemToRemove = itemId && activeItems.find(function (item) {
return item.id === parseInt(itemId, 10);
});
if (!itemToRemove) {
return;
}
// Remove item associated with button
this._removeItem(itemToRemove);