@danielgindi/selectbox 2.0.56 → 2.0.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/SelectBox.js CHANGED
@@ -1,3689 +1 @@
1
- import {
2
- getCssProps,
3
- getElementWidth,
4
- setElementWidth,
5
- getPseudoElementWidth,
6
- setCssProps,
7
- } from '@danielgindi/dom-utils/lib/Css';
8
- import escapeRegex from './utils/escapeRegex';
9
- import {
10
- closestUntil,
11
- createElement,
12
- next,
13
- prev,
14
- setElementAttrs,
15
- } from '@danielgindi/dom-utils/lib/Dom';
16
- import {
17
- append,
18
- getRootNode,
19
- before,
20
- remove,
21
- toggleClass,
22
- } from '@danielgindi/dom-utils/lib/DomCompat';
23
-
24
- import DomEventsSink from '@danielgindi/dom-utils/lib/DomEventsSink';
25
- import DropList, { ItemSymbol } from './DropList';
26
- import {
27
- VALUE_BACK_SPACE,
28
- VALUE_DELETE, VALUE_DOWN, VALUE_END, VALUE_ENTER,
29
- VALUE_ESCAPE, VALUE_HOME,
30
- VALUE_LEFT, VALUE_PAGE_DOWN,
31
- VALUE_PAGE_UP,
32
- VALUE_RIGHT, VALUE_SPACE,
33
- VALUE_TAB,
34
- VALUE_UP,
35
- } from 'keycode-js';
36
- import mitt from 'mitt';
37
-
38
- const DestroyedSymbol = Symbol('destroyed');
39
- const RestMultiItemsSymbol = Symbol('rest_multi_items');
40
-
41
- const hasTouchCapability = !!('ontouchstart' in window
42
- || (window.DocumentTouch && window.document instanceof window.DocumentTouch)
43
- || window.navigator.maxTouchPoints
44
- );
45
-
46
- /**
47
- * @param {Element|EventTarget} el
48
- * @param {string} className
49
- * @returns {boolean}
50
- */
51
- const hasClass = function (el, className) {
52
- if (el instanceof Element) {
53
- return el.classList.contains(className);
54
- }
55
-
56
- return false;
57
- };
58
-
59
- const inputBackbufferCssProps = [
60
- 'font-family',
61
- 'font-size',
62
- 'font-weight',
63
- 'font-size',
64
- 'letter-spacing',
65
- 'text-transform',
66
- 'word-spacing',
67
- 'text-indent',
68
- 'box-sizing',
69
- 'padding-left',
70
- 'padding-right',
71
- ];
72
-
73
- /**
74
- * @typedef {Object} SelectBox.Options
75
- * @property {DropList.Options} [listOptions] options to pass to the `DropList`
76
- * @property {Element} [el] An element to attach to, instead of creating a new one
77
- * @property {string} [baseClassName='selectbox'] class name for the menu root element
78
- * @property {string|string[]} [additionalClasses]
79
- * @property {'ltr'|'rtl'|'auto'} [direction='auto']
80
- * @property {boolean} [disabled=false] Should start as disabled?
81
- * @property {boolean} [readOnly=false] Should start as readOnly?
82
- * @property {boolean} [clearable=true] Has clear button?
83
- * @property {boolean} [hasOpenIndicator=true] has open/close indicator?
84
- * @property {string} [placeholder=''] Placeholder text
85
- * @property {boolean} [sortSelectedItems=true] Should the selected items be sorted?
86
- * @property {boolean} [sortListItems=false] Sort list items
87
- * @property {boolean} [sortListCheckedFirst=true] When sorting - put checked items first (applicable to `multi` mode only)
88
- * @property {boolean} [treatGroupSelectionAsItems=false] Treat group items as normal items
89
- * @property {*[]} [stickyValues]
90
- * @property {function(a: DropList.ItemBase, b: DropList.ItemBase):number} [sortItemComparator]
91
- * @property {boolean} [splitListCheckedGroups=true] Split groups to "checked" and "unchecked", works with `sortListCheckedFirst` only
92
- * @property {boolean|'touch'} [blurOnSingleSelection='touch']
93
- * @property {boolean} [multi=false] can multiple values be selected?
94
- * @property {boolean} [showSelection=true] show selection? if false, the placeholder will take effect
95
- * @property {boolean} [showPlaceholderInTooltip=false] show placeholder in title attribute
96
- * @property {function(items: DropList.ItemBase[]):string} [multiPlaceholderFormatter] formatter for placeholder for multi items mode
97
- * @property {string} [labelProp='label']
98
- * @property {string} [valueProp='value']
99
- * @property {string} [multiItemLabelProp='short_label']
100
- * @property {'after'|'before'|'none'} [multiItemRemovePosition='after']
101
- * @property {number} [maxMultiItems] maximum number of multi items. The rest will get a single item to represent.
102
- * @property {function(count: number, items: DropList.ItemBase[]):string} [multiItemsRestLabelProvider] label for the item representing the rest of the items.
103
- * @property {DropList.ItemBase[]|null} [items] initial items
104
- * @property {*[]|null} [selectedValues] initial selected values
105
- * @property {*|*[]|null} [value] initial selected value
106
- * @property {function(item: DropList.ItemBase, itemEl: Element):(*|false)} [renderSingleItem]
107
- * @property {function(item: DropList.ItemBase, itemEl: Element)} [unrenderSingleItem]
108
- * @property {function(item: DropList.ItemBase, itemEl: Element):(*|false)} [renderMultiItem]
109
- * @property {function(item: DropList.ItemBase, itemEl: Element)} [unrenderMultiItem]
110
- * @property {function(item: DropList.ItemBase, itemEl: Element):(*|false)} [renderRestMultiItem]
111
- * @property {function(item: DropList.ItemBase, itemEl: Element)} [unrenderRestMultiItem]
112
- * @property {boolean} [searchable=false] is it searchable?
113
- * @property {boolean} [allowTypeToSelect=true] default behavior of type to select (focus first item starting with the search term) when searchable is true
114
- * @property {string} [noResultsText='No matching results'] text for no results (empty for none)
115
- * @property {boolean} [autoSelectTextOnCheck=true] automatically select text in input when an item is checked (multi mode). Used to allow the user to quickly type multiple items.
116
- * @property {number} [filterThrottleWindow=300] throttle time (milliseconds) for filtering
117
- * @property {boolean} [filterOnEmptyTerm=false] call the filter function on empty search term too
118
- * @property {function(items: DropList.ItemBase[], term: string):(DropList.ItemBase[]|null)} [filterFn]
119
- * @property {function(name: string, ...args)} [on]
120
- * @property {boolean} [isLoadingMode]
121
- * @property {boolean} [closeListWhenLoading] whether we should close the list automatically when loading
122
- * @property {string[]} [clearInputWhen=['single_close','multi_select_single']] clear input box when closing the droplist or selecting <code>['single_close', 'multi_close', 'multi_select_single']</code>
123
- * */
124
- export const DefaultOptions = {
125
- el: null,
126
- baseClassName: 'selectbox',
127
- disabled: false,
128
- readOnly: false,
129
- clearable: true,
130
- hasOpenIndicator: true,
131
- placeholder: '',
132
- sortSelectedItems: true,
133
- sortListItems: false,
134
- sortListCheckedFirst: true,
135
- stickyValues: null,
136
- sortItemComparator: null,
137
- splitListCheckedGroups: true,
138
- treatGroupSelectionAsItems: false,
139
- blurOnSingleSelection: 'touch',
140
- multi: false,
141
- showSelection: true,
142
- showPlaceholderInTooltip: false,
143
- multiPlaceholderFormatter: null,
144
- searchable: true,
145
- noResultsText: 'No matching results',
146
- autoSelectTextOnCheck: true,
147
- filterThrottleWindow: 300,
148
- filterOnEmptyTerm: false,
149
- labelProp: 'label',
150
- valueProp: 'value',
151
- multiItemLabelProp: 'short_label',
152
- multiItemRemovePosition: 'after',
153
- maxMultiItems: null,
154
- multiItemsRestLabelProvider: null,
155
- items: [],
156
- selectedValues: undefined,
157
- value: undefined,
158
- isLoadingMode: false,
159
- closeListWhenLoading: true,
160
- clearInputWhen: ['single_close', 'multi_select_single'],
161
- };
162
-
163
- /**
164
- *
165
- * @param {DropList.ItemBase[]} items
166
- * @param {string} labelProp
167
- * @returns {string}
168
- */
169
- const defaultMultiPlaceholderFormatter = (items, labelProp) => {
170
- if (items.length === 0)
171
- return '';
172
-
173
- let title = items[0][labelProp] + '';
174
-
175
- if (items.length > 1) {
176
- title += ` (+${items.length - 1})`;
177
- }
178
-
179
- return title;
180
- };
181
-
182
-
183
- function getFocusState(element) {
184
- if (!element)
185
- return null;
186
-
187
- const state = { element };
188
-
189
- if (typeof element.selectionStart === 'number' &&
190
- typeof element.selectionEnd === 'number') {
191
- state.selectionStart = element.selectionStart;
192
- state.selectionEnd = element.selectionEnd;
193
- state.selectionDirection = element.selectionDirection;
194
- }
195
-
196
- return state;
197
- }
198
-
199
- function restoreFocusState(state) {
200
- if (!state?.element || !document.body.contains(state.element))
201
- return false;
202
-
203
- state.element.focus();
204
-
205
- if (typeof state.selectionStart === 'number' &&
206
- typeof state.selectionEnd === 'number' &&
207
- typeof state.element.setSelectionRange === 'function') {
208
- state.element.setSelectionRange(
209
- state.selectionStart,
210
- state.selectionEnd,
211
- state.selectionDirection ?? 'none',
212
- );
213
- }
214
-
215
- return true;
216
- }
217
-
218
- /*
219
- Emits the following events:
220
- ---------------------------
221
-
222
- 'clear:before' {cancel: false}: will clear the whole selection. return false to abort.
223
- 'clear': clearead the whole selection.
224
- 'open' { list: DropList }: the drop list is opening
225
- 'open:before' { list: DropList }: the drop list will open
226
- 'close': the drop list is closing
227
- 'addsel:before' {value, item, cancel: false, isCheckingGroup: bool}: an item selection is about to be added (in multi mode). return false to abort.
228
- 'removesel:before' {value, item, cancel: false, isCheckingGroup: bool}: an item selection is about to be removed (in multi mode). return false to abort.
229
- 'addsel' {value, item, isCheckingGroup: bool}: an item selection has been added (in multi mode)
230
- 'removesel' {value, item, isCheckingGroup: bool}: an item selection has been removed (in multi mode)
231
- 'groupcheck' {value, item, affectedCount: number}: an item selection has been removed (in multi mode)
232
- 'select:before' {value, item, cancel: false}: an item is about to be selected (in single mode). return false to abort.
233
- 'select' {value, item}: an item has been selected (in single mode)
234
- 'search' {value}: input box value has changed
235
- 'search:focus': input box has gained focus
236
- 'search:blur': input box has lost focus
237
- 'search:term': search term has been updated, before results were re-filtered
238
- 'input:resize': input box resized
239
- 'itemschanged' {term, mutated, count}: the current set of items has changed
240
- */
241
-
242
- // noinspection JSUnusedGlobalSymbols
243
- class SelectBox {
244
- /**
245
- * @param {SelectBox.Options} options
246
- */
247
- constructor(options) {
248
- const o = { ...DefaultOptions };
249
-
250
- for (let [key, value] of Object.entries(/**@type Object*/options))
251
- if (value !== undefined)
252
- o[key] = value;
253
-
254
- const p = this._p = {
255
- ownsEl: true,
256
-
257
- baseClassName: o.baseClassName,
258
- additionalClasses: o.additionalClasses,
259
- direction: o.direction === 'ltr' ? 'ltr' : o.direction === 'rtl' ? 'rtl' : 'auto',
260
-
261
- listOptions: o.listOptions,
262
-
263
- disabled: !!o.disabled,
264
- readOnly: !!o.readOnly,
265
- clearable: !!o.clearable,
266
- hasOpenIndicator: !!o.hasOpenIndicator,
267
- placeholder: o.placeholder,
268
- sortSelectedItems: !!o.sortSelectedItems,
269
- sortListItems: !!o.sortListItems,
270
- sortListCheckedFirst: !!o.sortListCheckedFirst,
271
- stickyValues: Array.isArray(o.stickyValues) ? new Set(o.stickyValues) : null,
272
- sortItemComparator: o.sortItemComparator,
273
- splitListCheckedGroups: !!o.splitListCheckedGroups,
274
- treatGroupSelectionAsItems: o.treatGroupSelectionAsItems,
275
- blurOnSingleSelection: o.blurOnSingleSelection,
276
- multi: o.multi,
277
- showSelection: o.showSelection,
278
- showPlaceholderInTooltip: o.showPlaceholderInTooltip,
279
- multiPlaceholderFormatter: o.multiPlaceholderFormatter,
280
- searchable: o.searchable,
281
- allowTypeToSelect: o.allowTypeToSelect,
282
- noResultsText: o.noResultsText,
283
- autoSelectTextOnCheck: o.autoSelectTextOnCheck,
284
-
285
- labelProp: o.labelProp,
286
- valueProp: o.valueProp,
287
- multiItemLabelProp: o.multiItemLabelProp,
288
- multiItemRemovePosition: o.multiItemRemovePosition,
289
-
290
- maxMultiItems: o.maxMultiItems,
291
- multiItemsRestLabelProvider: o.multiItemsRestLabelProvider,
292
-
293
- renderSingleItem: o.renderSingleItem,
294
- unrenderSingleItem: o.unrenderSingleItem,
295
- renderMultiItem: o.renderMultiItem,
296
- unrenderMultiItem: o.unrenderMultiItem,
297
- renderRestMultiItem: o.renderRestMultiItem,
298
- unrenderRestMultiItem: o.unrenderRestMultiItem,
299
-
300
- on: o.on || null,
301
- silenceEvents: true,
302
- mitt: mitt(),
303
-
304
- isLoadingMode: !!o.isLoadingMode,
305
- closeListWhenLoading: !!o.closeListWhenLoading,
306
- clearInputWhen: Array.isArray(o.clearInputWhen) ? o.clearInputWhen.slice(0) : [],
307
-
308
- items: [],
309
- itemsChanged: true,
310
-
311
- sink: new DomEventsSink(),
312
-
313
- /** @type ResizeObserver */
314
- resizeObserver: null,
315
-
316
- selectedItems: [],
317
- selectedValues: [],
318
- selectionChanged: true,
319
- resortBySelectionNeeded: false,
320
-
321
- filterThrottleWindow: o.filterThrottleWindow,
322
- filterOnEmptyTerm: o.filterOnEmptyTerm,
323
- filterFn: null,
324
- filterTerm: '',
325
- };
326
-
327
- let el = o.el;
328
- if (el instanceof Element) {
329
- p.ownsEl = false;
330
- } else {
331
- el = createElement('span');
332
- }
333
-
334
- setElementAttrs(el, {
335
- role: 'combobox',
336
- 'aria-haspopup': 'true',
337
- 'aria-expanded': 'false',
338
- });
339
- p.el = el;
340
-
341
- this._syncBaseClasses();
342
- this._renderBase();
343
-
344
- /** @type Element[] */
345
- p.multiItemEls = [];
346
-
347
- this.enable(!p.disabled);
348
- this.setReadOnly(p.readOnly);
349
-
350
- this._setupDropdownMenu();
351
-
352
- // --- Hook click
353
- p.sink
354
- .add(el, 'click', (evt) => {
355
- if (p.clearButtonWrapper && p.clearButtonWrapper.contains(evt.target)) {
356
- return;
357
- }
358
-
359
- if (!el.contains(document.activeElement)) {
360
- p.input.focus();
361
- // Go to end of input
362
- p.input.selectionStart = p.input.selectionEnd = p.input.value.length;
363
- }
364
- });
365
-
366
- // --- Handle default focus directly to search box
367
- p.sink.add(el, 'focus', evt => {
368
- const target = (/**Element*/evt.target);
369
-
370
- if (!el.contains(evt.relatedTarget) &&
371
- !hasClass(target, `${p.baseClassName}__search_field`) &&
372
- !hasClass(target, `${p.baseClassName}__item`)) {
373
- let field = el.querySelector(`.${p.baseClassName}__search_field`);
374
- field && field.focus();
375
- }
376
- }, true);
377
-
378
- p.sink
379
- .add(p.input, 'keydown', (/**KeyboardEvent*/event) => {
380
- this._handleInputKeydown(event);
381
- })
382
- .add(p.input, 'input', () => {
383
- this._resizeInput();
384
- });
385
-
386
- const focusInOutHandler = (() => {
387
- let t;
388
- return () => {
389
- if (t) {
390
- clearTimeout(t);
391
- }
392
- t = setTimeout(() => {
393
- toggleClass(el, `${p.baseClassName}__focus`, el.contains(document.activeElement));
394
- });
395
- };
396
- })();
397
- p.sink.add(el, 'focus', focusInOutHandler, true);
398
- p.sink.add(el, 'blur', focusInOutHandler, true);
399
-
400
- // --- Resize input on window change
401
- p.sink.add(window, 'resize', () => this._resizeInput());
402
- p.sink.add(window, 'orientationchange', () => this._resizeInput());
403
-
404
- if (window.ResizeObserver !== undefined) {
405
- let lastSize = {
406
- borderBoxSize: {
407
- blockSize: null,
408
- inlineSize: null,
409
- },
410
- contentBoxSize: {
411
- blockSize: null,
412
- inlineSize: null,
413
- },
414
- };
415
- p.resizeObserver = new ResizeObserver(entries => {
416
- if (this[DestroyedSymbol])
417
- return;
418
-
419
- const entry = entries[0];
420
- if (!lastSize ||
421
- entry.borderBoxSize[0].blockSize !== lastSize.borderBoxSize.blockSize ||
422
- entry.borderBoxSize[0].inlineSize !== lastSize.borderBoxSize.inlineSize ||
423
- entry.contentBoxSize[0].blockSize !== lastSize.contentBoxSize.blockSize ||
424
- entry.contentBoxSize[0].inlineSize !== lastSize.contentBoxSize.inlineSize) {
425
- p.resizeObserver.unobserve(p.el);
426
- this._resizeInput();
427
- requestAnimationFrame(() => p.resizeObserver.observe(p.el));
428
- }
429
-
430
- lastSize.borderBoxSize = entry.borderBoxSize[0];
431
- lastSize.contentBoxSize = entry.contentBoxSize[0];
432
- });
433
- p.resizeObserver.observe(p.el);
434
- }
435
-
436
- this.setFilterFn(o.filterFn);
437
-
438
- this.setItems(o.items);
439
- delete o.items; // we do not need this in memory anymore
440
-
441
- if (o.multi && Array.isArray(o.selectedValues)) {
442
- this.setSelectedValues(o.selectedValues);
443
- } else if (o.value != null) {
444
- this.setValue(o.value);
445
- }
446
-
447
- this._scheduleSync('full');
448
-
449
- this.silenceEvents = false;
450
-
451
- return this;
452
- }
453
-
454
- destroy() {
455
- if (this[DestroyedSymbol])
456
- return;
457
- this[DestroyedSymbol] = true;
458
-
459
- const p = this._p;
460
-
461
- if (p.syncTimeout) {
462
- clearTimeout(p.syncTimeout);
463
- delete p.syncTimeout;
464
- }
465
-
466
- this._stopTrackingPresence();
467
-
468
- p.sink.remove();
469
- p.dropList && p.dropList.destroy();
470
-
471
- this._cleanupSingleWrapper();
472
-
473
- if (p.unrenderMultiItem || p.unrenderRestMultiItem) {
474
- // Remove all item elements
475
- while (p.multiItemEls.length > 0) {
476
- // use fast path by removing in reverse
477
- this._removeMultiItemElementByIndex(p.multiItemEls.length - 1);
478
- }
479
- }
480
-
481
- remove(p.list);
482
- remove(p.singleWrapper);
483
- remove(p.input);
484
- remove(p.inputBackBuffer);
485
- remove(p.clearButtonWrapper);
486
- remove(p.openIndicator);
487
-
488
- if (!p.ownsEl) {
489
- for (let name of Array.from(p.el.classList)) {
490
- if (name.startsWith(p.baseClassName)) {
491
- p.el.classList.remove(name);
492
- }
493
- }
494
- p.el.removeAttribute('role');
495
- p.el.removeAttribute('aria-haspopup');
496
- p.el.removeAttribute('aria-expanded');
497
- }
498
-
499
- p.resizeObserver?.disconnect();
500
-
501
- this._p = null;
502
- }
503
-
504
- get el() {
505
- return this._p?.el ?? null;
506
- }
507
-
508
- get droplistInstance() {
509
- return this._p.dropList;
510
- }
511
-
512
- /**
513
- * Returns true if other is an inclusive descendant of droplist node, false otherwise, and undefined if the droplist is not initiated.
514
- * @param {Node} other
515
- * @param {boolean} [considerSubmenus=true]
516
- * @returns {boolean|undefined}
517
- */
518
- droplistElContains(other, considerSubmenus = true) {
519
- return this._p.dropList?.elContains(other, considerSubmenus);
520
- }
521
-
522
- /**
523
- * Enables the control
524
- * @param {boolean=true} enabled Should the control be enabled?
525
- * @returns {SelectBox}
526
- */
527
- enable(enabled) {
528
- const p = this._p;
529
-
530
- if (enabled === undefined) {
531
- enabled = true;
532
- }
533
- p.disabled = !enabled;
534
- p.el.setAttribute('aria-disabled', p.disabled.toString());
535
- p.input.disabled = !!p.disabled;
536
-
537
- const multiItemEls = p.multiItemEls;
538
-
539
- for (let itemEl of multiItemEls) {
540
- if (p.disabled) {
541
- itemEl.removeAttribute('tabindex');
542
- } else {
543
- itemEl.setAttribute('tabindex', '0');
544
- }
545
- }
546
-
547
- return this;
548
- }
549
-
550
- /**
551
- * Is the control enabled?
552
- * @returns {boolean}
553
- */
554
- isEnabled() {
555
- return !this._p.disabled;
556
- }
557
-
558
- /**
559
- * Disables the control
560
- * @param {boolean=true} disabled Should the control be disabled?
561
- * @returns {SelectBox}
562
- */
563
- disable(disabled) {
564
- return this.enable(disabled === undefined ? false : !disabled);
565
- }
566
-
567
- /**
568
- * Is the control disabled?
569
- * @returns {boolean}
570
- */
571
- isDisabled() {
572
- return this._p.disabled;
573
- }
574
-
575
- /**
576
- * Sets read only mode
577
- * @param {boolean=true} readOnly Should the control be read only?
578
- * @returns {SelectBox}
579
- */
580
- setReadOnly(readOnly) {
581
- const p = this._p;
582
-
583
- if (readOnly === undefined) {
584
- readOnly = true;
585
- }
586
- p.readOnly = readOnly;
587
- p.el.setAttribute('aria-readOnly', p.readOnly.toString());
588
- p.input.readOnly = !(p.searchable || p.multi) || !!p.readOnly;
589
-
590
- return this;
591
- }
592
-
593
- /**
594
- * Is the control enabled?
595
- * @returns {boolean}
596
- */
597
- isReadOnly() {
598
- return this._p.readOnly;
599
- }
600
-
601
- /**
602
- * @param {string|string[]} classes
603
- * @returns {SelectBox}
604
- */
605
- setAdditionalClasses(classes) {
606
- const p = this._p;
607
- p.additionalClasses = classes;
608
- this._syncBaseClasses();
609
- return this;
610
- }
611
-
612
- /**
613
- *
614
- * @param {DropList.ItemBase[]} [items]
615
- * @param {boolean} [resetValues=true] should reset values to current values (essentially refresh the data based on items & values). If set to false, use setValue to set a fresh value
616
- * @returns {SelectBox}
617
- */
618
- setItems(items, resetValues = true) {
619
- const p = this._p;
620
-
621
- if (!items)
622
- items = [];
623
-
624
- p.items = items.slice(0);
625
- p.itemsChanged = true;
626
-
627
- this._refreshItemByValueMap();
628
-
629
- if (resetValues) {
630
- this.setSelectedValues(this.getSelectedValues());
631
- }
632
-
633
- this._trigger('itemschanged', { term: null, mutated: true, count: this.getFilteredItemCount() });
634
-
635
- return this;
636
- }
637
-
638
- getFilteredItemCount() {
639
- const p = this._p;
640
-
641
- if (p.dropList)
642
- return p.dropList.getFilteredItemCount();
643
-
644
- if (p.items)
645
- return p.items.length;
646
-
647
- return 0;
648
- }
649
-
650
- isFilterPending() {
651
- const p = this._p;
652
- return p.dropList?.isFilterPending() === true;
653
- }
654
-
655
- updateItemByValue(value, newItem) {
656
- const p = this._p;
657
-
658
- let existingItem = this._getItemByValue(value);
659
- if (existingItem) {
660
- const valueProp = existingItem[p.valueProp];
661
- if (p.itemByValueMap?.has(valueProp))
662
- p.itemByValueMap.delete(valueProp);
663
-
664
- Object.assign(existingItem, newItem);
665
-
666
- p.itemByValueMap.set(existingItem[p.valueProp], existingItem);
667
- }
668
-
669
- if (p.dropList) {
670
- p.dropList.updateItemByValue(value, newItem);
671
- }
672
- }
673
-
674
- /**
675
- * @returns {DropList.ItemBase[]|*}
676
- */
677
- getItems() {
678
- const p = this._p;
679
- return p.items;
680
- }
681
-
682
- /**
683
- * @param {boolean} clearable
684
- * @returns {SelectBox}
685
- */
686
- setClearable(clearable) {
687
- clearable = !!clearable;
688
-
689
- if (this._p.clearable === clearable)
690
- return this;
691
-
692
- this._p.clearable = !!clearable;
693
- this._scheduleSync('render_clear');
694
- return this;
695
- }
696
-
697
- /**
698
- * @returns {boolean}
699
- */
700
- getClearable() {
701
- return this._p.clearable;
702
- }
703
-
704
- /**
705
- * @param {boolean} enabled
706
- * @returns {SelectBox}
707
- */
708
- setHasOpenIndicator(enabled) {
709
- enabled = !!enabled;
710
-
711
- if (this._p.hasOpenIndicator === enabled)
712
- return this;
713
-
714
- this._p.hasOpenIndicator = enabled;
715
- this._scheduleSync('render_base');
716
- return this;
717
- }
718
-
719
- /**
720
- * @returns {boolean}
721
- */
722
- getHasOpenIndicator() {
723
- return this._p.hasOpenIndicator;
724
- }
725
-
726
- /**
727
- * @param {string} placeholder
728
- * @returns {SelectBox}
729
- */
730
- setPlaceholder(placeholder) {
731
- this._p.placeholder = placeholder == null ? '' : String(placeholder);
732
- this._scheduleSync('render_base');
733
- return this;
734
- }
735
-
736
- /**
737
- * @returns {string}
738
- */
739
- getPlaceHolder() {
740
- return this._p.placeholder;
741
- }
742
-
743
- /**
744
- * @param {string} term
745
- * @param {boolean} [performSearch=false] should actually perform the search, or just set the input's text?
746
- * @returns {SelectBox}
747
- */
748
- setSearchTerm(term, performSearch = false) {
749
- const p = this._p;
750
-
751
- if (!p.input) return this;
752
-
753
- p.input.value = term;
754
-
755
- this._scheduleSync('resize_input');
756
-
757
- if (performSearch) {
758
- p.filterTerm = p.input.value.trim();
759
- this._trigger('search:term', p.filterTerm);
760
- p.dropList?.setSearchTerm(p.filterTerm, performSearch);
761
- }
762
-
763
- return this;
764
- }
765
-
766
- /**
767
- * @returns {string}
768
- */
769
- getSearchTerm() {
770
- const p = this._p;
771
- if (p.input)
772
- return p.input.value;
773
- return '';
774
- }
775
-
776
- invokeRefilter() {
777
- const p = this._p;
778
- p.dropList?.invokeRefilter();
779
- return this;
780
- }
781
-
782
- /**
783
- * @param {boolean} sortSelectedItems
784
- * @returns {SelectBox}
785
- */
786
- setSortSelectedItems(sortSelectedItems) {
787
- const p = this._p;
788
- sortSelectedItems = !!sortSelectedItems;
789
- if (p.sortSelectedItems === sortSelectedItems)
790
- return this;
791
-
792
- p.sortSelectedItems = sortSelectedItems;
793
- this._scheduleSync('render_items');
794
- return this;
795
- }
796
-
797
- /**
798
- * @returns {boolean}
799
- */
800
- isSortSelectedItemsEnabled() {
801
- return this._p.sortSelectedItems;
802
- }
803
-
804
- /**
805
- * @param {boolean} sortListItems
806
- * @returns {SelectBox}
807
- */
808
- setSortListItems(sortListItems) {
809
- const p = this._p;
810
- sortListItems = !!sortListItems;
811
- if (p.sortListItems === sortListItems)
812
- return this;
813
-
814
- p.sortListItems = sortListItems;
815
- p.itemsChanged = true;
816
- this._scheduleSync('render_list');
817
- return this;
818
- }
819
-
820
- /**
821
- * @returns {boolean}
822
- */
823
- isSortListItemsEnabled() {
824
- return this._p.sortListItems;
825
- }
826
-
827
- /**
828
- * @param {boolean} sortListCheckedFirst
829
- * @returns {SelectBox}
830
- */
831
- setSortListCheckedFirst(sortListCheckedFirst) {
832
- const p = this._p;
833
- sortListCheckedFirst = !!sortListCheckedFirst;
834
- if (p.sortListCheckedFirst === sortListCheckedFirst)
835
- return this;
836
-
837
- p.sortListCheckedFirst = sortListCheckedFirst;
838
- p.itemsChanged = true;
839
- this._scheduleSync('render_list');
840
- return this;
841
- }
842
-
843
- /**
844
- * @returns {boolean}
845
- */
846
- isSortListCheckedFirstEnabled() {
847
- return this._p.sortListCheckedFirst;
848
- }
849
-
850
- /**
851
- * @param {*[]} values
852
- * @returns {SelectBox}
853
- */
854
- setStickyValues(values) {
855
- const p = this._p;
856
-
857
- p.stickyValues = Array.isArray(values) ? new Set(values) : null;
858
- p.itemsChanged = true;
859
- this._scheduleSync('render_list');
860
- return this;
861
- }
862
-
863
- /**
864
- * @returns {*[]}
865
- */
866
- getStickyValues() {
867
- return this._p.stickyValues ? Array.from(this._p.stickyValues) : null;
868
- }
869
-
870
- /**
871
- * @param {function(a: DropList.ItemBase, b: DropList.ItemBase):number} comparator
872
- * @returns {SelectBox}
873
- */
874
- setSortItemComparator(comparator) {
875
- const p = this._p;
876
- if (p.sortItemComparator === comparator)
877
- return this;
878
-
879
- p.sortItemComparator = comparator;
880
- p.itemsChanged = true;
881
- this._scheduleSync('render_list');
882
- return this;
883
- }
884
-
885
- /**
886
- * @returns {function(a: DropList.ItemBase, b: DropList.ItemBase):number}
887
- */
888
- getSortItemComparator() {
889
- return this._p.sortItemComparator;
890
- }
891
-
892
- /**
893
- * @param {boolean} treatGroupSelectionAsItems
894
- * @returns {SelectBox}
895
- */
896
- setTreatGroupSelectionAsItems(treatGroupSelectionAsItems) {
897
- const p = this._p;
898
- treatGroupSelectionAsItems = !!treatGroupSelectionAsItems;
899
- if (p.treatGroupSelectionAsItems === treatGroupSelectionAsItems)
900
- return this;
901
-
902
- p.treatGroupSelectionAsItems = treatGroupSelectionAsItems;
903
- p.dropList?.setFilterGroups(treatGroupSelectionAsItems);
904
- p.dropList?.setFilterEmptyGroups(!treatGroupSelectionAsItems);
905
- p.itemsChanged = true;
906
- this._scheduleSync('render_list');
907
- return this;
908
- }
909
-
910
- /**
911
- * @returns {boolean}
912
- */
913
- isTreatGroupSelectionAsItemsEnabled() {
914
- return !this._p.treatGroupSelectionAsItems;
915
- }
916
-
917
- /**
918
- * @param {boolean} splitListCheckedGroups
919
- * @returns {SelectBox}
920
- */
921
- setSplitListCheckedGroups(splitListCheckedGroups) {
922
- const p = this._p;
923
- splitListCheckedGroups = !!splitListCheckedGroups;
924
- if (p.splitListCheckedGroups === splitListCheckedGroups)
925
- return this;
926
-
927
- p.splitListCheckedGroups = splitListCheckedGroups;
928
- p.itemsChanged = true;
929
- this._scheduleSync('render_list');
930
- return this;
931
- }
932
-
933
- /**
934
- * @returns {boolean}
935
- */
936
- isSplitListCheckedGroupsEnabled() {
937
- return this._p.splitListCheckedGroups;
938
- }
939
-
940
- /**
941
- * @param {boolean} showSelection
942
- * @returns {SelectBox}
943
- */
944
- setShowSelection(showSelection) {
945
- const p = this._p;
946
- showSelection = !!showSelection;
947
- if (p.showSelection === showSelection)
948
- return this;
949
-
950
- p.showSelection = showSelection;
951
- this._scheduleSync('render_items');
952
- return this;
953
- }
954
-
955
- /**
956
- * @returns {boolean}
957
- */
958
- isShowSelectionEnabled() {
959
- return this._p.showSelection;
960
- }
961
-
962
- /**
963
- * @param {boolean} showPlaceholderInTooltip
964
- * @returns {SelectBox}
965
- */
966
- setShowPlaceholderInTooltip(showPlaceholderInTooltip) {
967
- const p = this._p;
968
- showPlaceholderInTooltip = !!showPlaceholderInTooltip;
969
- if (p.showPlaceholderInTooltip === showPlaceholderInTooltip)
970
- return this;
971
-
972
- p.showPlaceholderInTooltip = showPlaceholderInTooltip;
973
- this._scheduleSync('render_base');
974
- return this;
975
- }
976
-
977
- /**
978
- * @returns {boolean}
979
- */
980
- isShowPlaceholderInTooltipEnabled() {
981
- return this._p.showPlaceholderInTooltip;
982
- }
983
-
984
- /**
985
- * @param {function(items: DropList.ItemBase[]):string} formatter
986
- * @returns {SelectBox}
987
- */
988
- setMultiPlaceholderFormatter(formatter) {
989
- const p = this._p;
990
-
991
- if (p.multiPlaceholderFormatter === formatter)
992
- return this;
993
-
994
- p.multiPlaceholderFormatter = formatter;
995
- this._scheduleSync('render_base');
996
- return this;
997
- }
998
-
999
- /**
1000
- * @param {boolean|'touch'} value
1001
- * @returns {SelectBox}
1002
- */
1003
- setBlurOnSingleSelection(value) {
1004
- const p = this._p;
1005
- if (p.blurOnSingleSelection === value)
1006
- return this;
1007
-
1008
- p.blurOnSingleSelection = value;
1009
- return this;
1010
- }
1011
-
1012
- /**
1013
- * @returns {boolean|'touch'}
1014
- */
1015
- getBlurOnSingleSelection() {
1016
- return this._p.blurOnSingleSelection;
1017
- }
1018
-
1019
- /**
1020
- * @param {boolean} multi
1021
- * @returns {SelectBox}
1022
- */
1023
- setMulti(multi) {
1024
- const p = this._p;
1025
- multi = !!multi;
1026
- if (p.multi === multi)
1027
- return this;
1028
-
1029
- p.multi = multi;
1030
-
1031
- this._setupDropdownMenu();
1032
-
1033
- // move to correct parent
1034
- remove(p.clearButtonWrapper);
1035
- delete p.clearButtonWrapper;
1036
-
1037
- if (multi &&
1038
- p.selectedValues &&
1039
- p.selectedValues.length === 1 &&
1040
- Array.isArray(p.selectedValues[0])) {
1041
- this.setSelectedValues(/**@type Array*/p.selectedValues[0]);
1042
- }
1043
-
1044
- this._scheduleSync('full');
1045
-
1046
- return this;
1047
- }
1048
-
1049
- /**
1050
- * @returns {boolean}
1051
- */
1052
- isMultiEnabled() {
1053
- return this._p.multi;
1054
- }
1055
-
1056
- /**
1057
- * @param {boolean} searchable
1058
- * @returns {SelectBox}
1059
- */
1060
- setSearchable(searchable) {
1061
- const p = this._p;
1062
- searchable = !!searchable;
1063
- if (p.searchable === searchable)
1064
- return this;
1065
-
1066
- p.searchable = searchable;
1067
- this._scheduleSync('full');
1068
-
1069
- return this;
1070
- }
1071
-
1072
- /**
1073
- * @param {boolean} allowTypeToSelect
1074
- * @returns {SelectBox}
1075
- */
1076
- setAllowTypeToSelect(allowTypeToSelect) {
1077
- const p = this._p;
1078
- allowTypeToSelect = !!allowTypeToSelect;
1079
- if (p.allowTypeToSelect === allowTypeToSelect)
1080
- return this;
1081
-
1082
- p.allowTypeToSelect = allowTypeToSelect;
1083
- return this;
1084
- }
1085
-
1086
- /**
1087
- * @returns {boolean}
1088
- */
1089
- isSearchableEnabled() {
1090
- return this._p.searchable;
1091
- }
1092
-
1093
- /**
1094
- * @param {string} noResultsText
1095
- * @returns {SelectBox}
1096
- */
1097
- setNoResultsText(noResultsText) {
1098
- this._p.dropList?.setNoResultsText(noResultsText);
1099
- return this;
1100
- }
1101
-
1102
- /**
1103
- * @returns {string}
1104
- */
1105
- getNoResultsText() {
1106
- return this._p.noResultsText;
1107
- }
1108
-
1109
- /**
1110
- * @param {boolean} autoSelectTextOnCheck
1111
- * @returns {SelectBox}
1112
- */
1113
- setAutoSelectTextOnCheck(autoSelectTextOnCheck) {
1114
- this._p.autoSelectTextOnCheck = autoSelectTextOnCheck;
1115
- return this;
1116
- }
1117
-
1118
- /**
1119
- * @returns {boolean}
1120
- */
1121
- getAutoSelectTextOnCheck() {
1122
- return this._p.autoSelectTextOnCheck;
1123
- }
1124
-
1125
- /**
1126
- * @param {number} window
1127
- * @returns {SelectBox}
1128
- */
1129
- setFilterThrottleWindow(window) {
1130
- const p = this._p;
1131
- p.filterThrottleWindow = window;
1132
- p.dropList?.setFilterThrottleWindow(window);
1133
- return this;
1134
- }
1135
-
1136
- /**
1137
- * @returns {number}
1138
- */
1139
- getFilterThrottleWindow() {
1140
- return this._p.filterThrottleWindow;
1141
- }
1142
-
1143
- /**
1144
- * @param {boolean} value
1145
- * @returns {SelectBox}
1146
- */
1147
- setFilterOnEmptyTerm(value) {
1148
- const p = this._p;
1149
- if (p.filterOnEmptyTerm === value)
1150
- return this;
1151
- p.dropList?.setFilterOnEmptyTerm(value);
1152
- return this;
1153
- }
1154
-
1155
- /**
1156
- * @returns {boolean}
1157
- */
1158
- getFilterOnEmptyTerm() {
1159
- return this._p.filterOnEmptyTerm;
1160
- }
1161
-
1162
- /**
1163
- * @param {DropList.Options} listOptions
1164
- * @returns {SelectBox}
1165
- */
1166
- setListOptions(listOptions) {
1167
- const p = this._p;
1168
- p.listOptions = listOptions;
1169
- this._setupDropdownMenu();
1170
- return this;
1171
- }
1172
-
1173
- /**
1174
- * @param {(function(item: DropList.ItemBase, itemEl: Element):(*|false))|null} render
1175
- * @param {(function(item: DropList.ItemBase, itemEl: Element))|null} unrender
1176
- * @returns {SelectBox})|null
1177
- */
1178
- setRenderSingleItem(render, unrender) {
1179
- const p = this._p;
1180
- p.renderSingleItem = render;
1181
- p.unrenderSingleItem = unrender;
1182
- return this;
1183
- }
1184
-
1185
- /**
1186
- * @param {(function(item: DropList.ItemBase, itemEl: Element):(*|false))|null} render
1187
- * @param {(function(item: DropList.ItemBase, itemEl: Element))|null} unrender
1188
- * @returns {SelectBox}
1189
- */
1190
- setRenderMultiItem(render, unrender) {
1191
- const p = this._p;
1192
- p.renderMultiItem = render;
1193
- p.unrenderMultiItem = unrender;
1194
- return this;
1195
- }
1196
-
1197
- /**
1198
- * @param {(function(item: DropList.ItemBase, itemEl: Element):(*|false))|null} render
1199
- * @param {(function(item: DropList.ItemBase, itemEl: Element))|null} unrender
1200
- * @returns {SelectBox}
1201
- */
1202
- setRenderRestMultiItem(render, unrender) {
1203
- const p = this._p;
1204
- p.renderRestMultiItem = render;
1205
- p.unrenderRestMultiItem = unrender;
1206
- return this;
1207
- }
1208
-
1209
- /**
1210
- * @param {string} prop
1211
- * @returns {SelectBox}
1212
- */
1213
- setLabelProp(prop) {
1214
- const p = this._p;
1215
- p.labelProp = prop;
1216
-
1217
- if (p.dropList)
1218
- p.dropList.setLabelProp(prop);
1219
-
1220
- return this;
1221
- }
1222
-
1223
- /**
1224
- * @param {string} prop
1225
- * @returns {SelectBox}
1226
- */
1227
- setValueProp(prop) {
1228
- const p = this._p;
1229
-
1230
- if (p.valueProp === prop)
1231
- return this;
1232
-
1233
- p.valueProp = prop;
1234
-
1235
- if (p.dropList)
1236
- p.dropList.setValueProp(prop);
1237
-
1238
- this._refreshItemByValueMap();
1239
-
1240
- return this;
1241
- }
1242
-
1243
- /**
1244
- * @param {string} prop
1245
- * @returns {SelectBox}
1246
- */
1247
- setMultiItemLabelProp(prop) {
1248
- const p = this._p;
1249
- p.multiItemLabelProp = prop;
1250
- this._scheduleSync('render_items');
1251
- return this;
1252
- }
1253
-
1254
- /**
1255
- * @param {'before'|'after'|'none'} position
1256
- * @returns {SelectBox}
1257
- */
1258
- setMultiItemRemovePosition(position) {
1259
- const p = this._p;
1260
- p.multiItemRemovePosition = position;
1261
- this._scheduleSync('render_items');
1262
- return this;
1263
- }
1264
-
1265
- /**
1266
- * @param {number|null|undefined} value
1267
- * @returns {SelectBox}
1268
- */
1269
- setMaxMultiItems(value) {
1270
- const p = this._p;
1271
- p.maxMultiItems = value;
1272
- return this;
1273
- }
1274
-
1275
- /**
1276
- * @param {function(count: number, items: DropList.ItemBase[]):string|null|undefined} value
1277
- * @returns {SelectBox}
1278
- */
1279
- setMultiItemsRestLabelProvider(value) {
1280
- const p = this._p;
1281
- p.multiItemsRestLabelProvider = value;
1282
- return this;
1283
- }
1284
-
1285
- /**
1286
- * @param {function(items: DropList.ItemBase[], term: string):(DropList.ItemBase[]|null)} fn
1287
- * @returns {SelectBox}
1288
- */
1289
- setFilterFn(fn) {
1290
- const p = this._p;
1291
- if (p.filterFn === fn)
1292
- return this;
1293
-
1294
- // Do not keep this reference, as far as the user is concerned - he/she did not set a custom filter.
1295
- p.filterFn = fn;
1296
-
1297
- if (!fn) {
1298
- // Add search by multi-item label
1299
- fn = (items, term) => {
1300
- const matcher = new RegExp(escapeRegex(term), 'i');
1301
- const labelProp = p.labelProp,
1302
- multiItemLabelProp = p.multiItemLabelProp;
1303
-
1304
- return p.items.filter(x => {
1305
- if (!p.treatGroupSelectionAsItems && x._group) return true;
1306
- return matcher.test(x[labelProp] || x[multiItemLabelProp]);
1307
- });
1308
- };
1309
- }
1310
-
1311
- p.actualFilterFn = fn;
1312
- p.dropList?.setFilterFn(fn);
1313
- return this;
1314
- }
1315
-
1316
- /**
1317
- * @returns {function(items: DropList.ItemBase[], term: string):(DropList.ItemBase[]|null)}
1318
- */
1319
- getFilterFn() {
1320
- return this._p.filterFn;
1321
- }
1322
-
1323
- /**
1324
- * Focus on input element
1325
- * @returns {SelectBox}
1326
- */
1327
- focusInput() {
1328
- const p = this._p;
1329
-
1330
- if (p.input)
1331
- p.input.focus();
1332
-
1333
- return this;
1334
- }
1335
-
1336
- /**
1337
- * Remvoe focus from the input element
1338
- * @returns {SelectBox}
1339
- */
1340
- blurInput() {
1341
- const p = this._p;
1342
-
1343
- if (p.input)
1344
- p.input.blur();
1345
-
1346
- return this;
1347
- }
1348
-
1349
- /**
1350
- * Removes all selected items
1351
- * @returns {SelectBox}
1352
- */
1353
- clear() {
1354
- if (!this._performClearWithEvent(true))
1355
- return this;
1356
-
1357
- if (this[DestroyedSymbol]) return this; // destroyed by event handler
1358
-
1359
- return this;
1360
- }
1361
-
1362
- /**
1363
- * Returns a single value or an array of selected values - depending on `multi` prop
1364
- * @public
1365
- * @returns {*[]}
1366
- */
1367
- getValue() {
1368
- const p = this._p;
1369
- if (p.multi)
1370
- return p.selectedValues.slice(0);
1371
- else if (p.selectedValues.length > 0)
1372
- return p.selectedValues[0];
1373
- return undefined;
1374
- }
1375
-
1376
- /**
1377
- * Selects the specified value or multiple values - depending on `multi` prop
1378
- * @public
1379
- * @param {*|*[]} value - if `multi`, then an array of values to select, otherwise - a single value to select
1380
- * @returns {SelectBox}
1381
- */
1382
- setValue(value) {
1383
- const p = this._p;
1384
- if (p.multi)
1385
- return this.setSelectedValues(Array.isArray(value) ? value : value !== undefined ? [value] : []);
1386
- else
1387
- return this.setSelectedValues(value !== undefined ? [value] : []);
1388
- }
1389
-
1390
- /**
1391
- * Returns an array of selected values
1392
- * @public
1393
- * @returns {*[]}
1394
- */
1395
- getSelectedValues() {
1396
- const p = this._p;
1397
- return p.selectedValues.slice(0);
1398
- }
1399
-
1400
- /**
1401
- * Selects the specified values
1402
- * @public
1403
- * @param {*[]} values - an array of *values* to select
1404
- * @returns {SelectBox}
1405
- */
1406
- setSelectedValues(values) {
1407
- const p = this._p, valueProp = p.valueProp;
1408
-
1409
- if (!p.multi) {
1410
- values = values.slice(0, 1);
1411
- }
1412
-
1413
- let set = new Set();
1414
- let selectedValues = [];
1415
- let selectedItems = [];
1416
-
1417
- for (let value of values) {
1418
- if (set.has(value))
1419
- continue;
1420
- set.add(value);
1421
-
1422
- selectedValues.push(value);
1423
-
1424
- let item = this._getItemByValue(value);
1425
- if (item !== undefined) {
1426
- selectedItems.push(item);
1427
- } else {
1428
- selectedItems.push({ [valueProp]: value });
1429
- }
1430
- }
1431
-
1432
- p.selectedValues = selectedValues;
1433
- p.selectedItems = selectedItems;
1434
- p.selectionChanged = true;
1435
- p.resortBySelectionNeeded = true;
1436
-
1437
- this._scheduleSync('full');
1438
-
1439
- return this;
1440
- }
1441
-
1442
- /**
1443
- * Returns the count of selected values
1444
- * @public
1445
- * @returns {number}
1446
- */
1447
- getSelectedValueCount() {
1448
- const p = this._p;
1449
- return p.selectedValues.length;
1450
- }
1451
-
1452
- /**
1453
- * Returns an array of selected items
1454
- * @public
1455
- * @returns {Array.<Object>}
1456
- */
1457
- getSelectedItems() {
1458
- const p = this._p;
1459
- return p.selectedItems.slice(0);
1460
- }
1461
-
1462
- /**
1463
- * Sets the specified items to "checked" mode.
1464
- * An array of items is passed, not values, because we need to keep track if items,
1465
- * and if we already have the array of items then this spares the process of searching for the items by values.
1466
- * @public
1467
- * @param {DropList.ItemBase[]} items - an array of *items* to select (not values)
1468
- * @returns {SelectBox}
1469
- */
1470
- setSelectedItems(items) {
1471
- this._setSelectedItems(items);
1472
- return this;
1473
- }
1474
-
1475
- /**
1476
- * @returns {SelectBox}
1477
- */
1478
- openList() {
1479
- const p = this._p;
1480
-
1481
- if (p.dropList.isVisible())
1482
- return this;
1483
-
1484
- if (p.isLoadingMode && p.items.length === 0)
1485
- return this;
1486
-
1487
- this._trigger('open:before', { list: p.dropList });
1488
-
1489
- if (document.activeElement !== p.input)
1490
- p.lastActiveElement = document.activeElement === document.body ? null : getFocusState(document.activeElement);
1491
-
1492
- // Propagate direction to droplist
1493
- p.dropList.setDirection(getComputedStyle(p.el).direction);
1494
-
1495
- p.dropList.show();
1496
- this._repositionDropList();
1497
-
1498
- // Another one in case the droplist position messed with screen layout.
1499
- // If the out element's bounds stayed the same - nothing will be recalculated.
1500
- // So this is *not* expensive.
1501
- this._repositionDropList();
1502
-
1503
- if (p.dropList.hasFocusedItem()) {
1504
- p.dropList.setFocusedItemAtIndex(p.dropList.getFocusedItemIndex());
1505
- } else if (!p.multi && this.getValue() !== undefined) {
1506
- p.dropList.setFocusedItemByValue(this.getValue());
1507
- }
1508
-
1509
- return this;
1510
- }
1511
-
1512
- /**
1513
- * @returns {SelectBox}
1514
- */
1515
- closeList() {
1516
- const p = this._p;
1517
-
1518
- if (this[DestroyedSymbol])
1519
- return this;
1520
-
1521
- if (!p.dropList.isVisible())
1522
- return this;
1523
-
1524
- p.dropList.hide();
1525
-
1526
- if (p.lastActiveElement) {
1527
- if (!p.multi && !p.searchable)
1528
- restoreFocusState(p.lastActiveElement);
1529
- p.lastActiveElement = null;
1530
- }
1531
-
1532
- return this;
1533
- }
1534
-
1535
- /**
1536
- * @param {boolean} [open]
1537
- * @returns {SelectBox}
1538
- */
1539
- toggleList(open) {
1540
- const p = this._p;
1541
-
1542
- let shouldOpen = open === undefined ? !p.dropList.isVisible() : !!open;
1543
-
1544
- if (shouldOpen)
1545
- return this.openList();
1546
- else return this.closeList();
1547
- }
1548
-
1549
- /**
1550
- * @returns {boolean}
1551
- */
1552
- isListOpen() {
1553
- return !!this._p.dropListVisible;
1554
- }
1555
-
1556
- /**
1557
- * @param {boolean} [on]
1558
- * @returns {SelectBox}
1559
- */
1560
- toggleLoading(on) {
1561
- return this.setIsLoadingMode(on === undefined ? !this.getIsLoadingMode() : !!on);
1562
- }
1563
-
1564
- /**
1565
- * @param {boolean} isLoadingMode
1566
- * @returns {SelectBox}
1567
- */
1568
- setIsLoadingMode(isLoadingMode) {
1569
- const p = this._p;
1570
-
1571
- isLoadingMode = isLoadingMode === undefined ? true : !!isLoadingMode;
1572
-
1573
- if (p.isLoadingMode === isLoadingMode)
1574
- return this;
1575
-
1576
- p.isLoadingMode = isLoadingMode;
1577
-
1578
- if (p.isLoadingMode && p.closeListWhenLoading && p.items.length === 0 && this.isListOpen()) {
1579
- this.closeList();
1580
- } else if (!p.isLoadingMode && p.closeListWhenLoading && document.activeElement &&
1581
- ((p.multi || p.searchable) && p.input.contains(document.activeElement) ||
1582
- (!p.multi && !p.searchable) && p.el.contains(document.activeElement))) {
1583
- this.openList();
1584
- }
1585
-
1586
- this._scheduleSync('render_base');
1587
- return this;
1588
- }
1589
-
1590
- /**
1591
- * @returns {boolean}
1592
- */
1593
- getIsLoadingMode() {
1594
- return this._p.isLoadingMode;
1595
- }
1596
-
1597
- /**
1598
- * Sets whether to close the list when loading mode is enabled
1599
- * @param {boolean} closeListWhenLoading
1600
- * @returns {SelectBox}
1601
- */
1602
- setCloseListWhenLoading(closeListWhenLoading) {
1603
- this._p.closeListWhenLoading = closeListWhenLoading;
1604
- return this;
1605
- }
1606
-
1607
- /**
1608
- * @returns {boolean}
1609
- */
1610
- getCloseListWhenLoading() {
1611
- return this._p.closeListWhenLoading;
1612
- }
1613
-
1614
- /**
1615
- * Sets when to clear the input field
1616
- * @param {string[]} clearInputWhen
1617
- * @returns {SelectBox}
1618
- */
1619
- setClearInputWhen(clearInputWhen) {
1620
- this._p.clearInputWhen = Array.isArray(clearInputWhen) ? clearInputWhen.slice(0) : [];
1621
- return this;
1622
- }
1623
-
1624
- /**
1625
- * Retrieves the settings for when to clear the input field
1626
- * @returns {string[]}
1627
- */
1628
- getClearInputWhen() {
1629
- return this._p.clearInputWhen;
1630
- }
1631
-
1632
- /**
1633
- * Sets the appropriate direction for the selectbox
1634
- * @param {'ltr'|'rtl'|'auto'} direction
1635
- * @return {SelectBox}
1636
- */
1637
- setDirection(direction) {
1638
- const p = this._p;
1639
- p.direction = direction === 'ltr' ? 'ltr' : direction === 'rtl' ? 'rtl' : 'auto';
1640
- this._syncBaseClasses();
1641
- return this;
1642
- }
1643
-
1644
- /**
1645
- * Gets the supplied direction for the selectbox
1646
- * @return {'ltr'|'rtl'|'auto'}
1647
- */
1648
- getDirection() {
1649
- const p = this._p;
1650
- return p.direction;
1651
- }
1652
-
1653
- /**
1654
- * Can be called in case that the selectbox was attached to the dom late and has a weird size.
1655
- * @returns {SelectBox}
1656
- */
1657
- refreshSize() {
1658
- this._resizeInput();
1659
- return this;
1660
- }
1661
-
1662
- /**
1663
- * Register an event handler
1664
- * @param {(string|'*')?} event
1665
- * @param {function(any)} handler
1666
- * @returns {SelectBox}
1667
- */
1668
- on(/**string|'*'*/event, /**Function?*/handler) {
1669
- this._p.mitt.on(event, handler);
1670
- return this;
1671
- }
1672
-
1673
- /**
1674
- * Register a one time event handler
1675
- * @param {(string|'*')?} event
1676
- * @param {function(any)} handler
1677
- * @returns {SelectBox}
1678
- */
1679
- once(/**string|'*'*/event, /**Function?*/handler) {
1680
- let wrapped = (value) => {
1681
- this._p.mitt.off(event, wrapped);
1682
- handler(value);
1683
- };
1684
- this._p.mitt.on(event, wrapped);
1685
- return this;
1686
- }
1687
-
1688
- /**
1689
- * Remove an `handler` for `event`, all events for `event`, or all events completely.
1690
- * @param {(string|'*')?} event
1691
- * @param {function(any)} handler
1692
- * @returns {SelectBox}
1693
- */
1694
- off(/**(string|'*')?*/event, /**Function?*/handler) {
1695
- if (!event && !event) {
1696
- this._p.mitt.all.clear();
1697
- } else {
1698
- this._p.mitt.off(event, handler);
1699
- }
1700
- return this;
1701
- }
1702
-
1703
- /**
1704
- * Emit an event
1705
- * @param {string} event
1706
- * @param {any} value
1707
- * @returns {SelectBox}
1708
- */
1709
- emit(/**string|'*'*/event, /**any?*/value) {
1710
- this._p.mitt.emit(event, value);
1711
- return this;
1712
- }
1713
-
1714
- /**
1715
- * Prepare the mapping between values and items.
1716
- * This reduces search time greatly (i.e when checking items), especially when Vue proxies are in place.
1717
- * @private
1718
- */
1719
- _refreshItemByValueMap() {
1720
- const p = this._p;
1721
-
1722
- const itemByValueMap = p.itemByValueMap = new Map();
1723
- const valueProp = p.valueProp;
1724
- for (let item of p.items) {
1725
- itemByValueMap.set(item[valueProp], item);
1726
- }
1727
-
1728
- p.subitemByValueMap = null;
1729
- }
1730
-
1731
- /**
1732
- * @param {*} value
1733
- * @returns {DropList.ItemBase|undefined}
1734
- * @private
1735
- */
1736
- _getItemByValue(value) {
1737
- const p = this._p;
1738
- let item = p.itemByValueMap.get(value);
1739
- if (item !== undefined)
1740
- return item;
1741
-
1742
- if (!p.subitemByValueMap)
1743
- this._refreshSubitemByValueMap();
1744
-
1745
- return p.subitemByValueMap.get(value);
1746
- }
1747
-
1748
- /** @private */
1749
- _refreshSubitemByValueMap() {
1750
- const p = this._p;
1751
- const subitemByValueMap = p.subitemByValueMap = new Map();
1752
- this._addSubitemsToValueMap(p.items, subitemByValueMap, p.valueProp);
1753
- }
1754
-
1755
- /**
1756
- * @param {DropList.ItemBase[]} items
1757
- * @param {Map<*, DropList.ItemBase>} itemByValueMap
1758
- * @param {string} valueProp
1759
- * @private
1760
- */
1761
- _addSubitemsToValueMap(items, itemByValueMap, valueProp) {
1762
- for (let item of items) {
1763
- if (!item._subitems?.length)
1764
- continue;
1765
-
1766
- for (let subitem of item._subitems) {
1767
- if (!itemByValueMap.has(subitem[valueProp]))
1768
- itemByValueMap.set(subitem[valueProp], subitem);
1769
- }
1770
-
1771
- this._addSubitemsToValueMap(item._subitems, itemByValueMap, valueProp);
1772
- }
1773
- }
1774
-
1775
- /** @private */
1776
- _renderBase() {
1777
- const p = this._p;
1778
-
1779
- if (!p.inputBackBuffer) {
1780
- p.inputBackBuffer = createElement('span', {
1781
- css: {
1782
- position: 'absolute',
1783
- zIndex: -1,
1784
- left: 0,
1785
- top: '-9999px',
1786
- whiteSpace: 'pre',
1787
- },
1788
- });
1789
- }
1790
-
1791
- if (!p.input) {
1792
- p.inputWrapper = createElement('span',
1793
- {
1794
- class: `${p.baseClassName}__search_wrapper`,
1795
- },
1796
- p.input = createElement('input', {
1797
- class: `${p.baseClassName}__search_field`,
1798
- type: 'search',
1799
- autocomplete: 'off',
1800
- autocorrect: 'off',
1801
- autocapitalize: 'off',
1802
- spellcheck: 'false',
1803
- role: 'textbox',
1804
- 'aria-autocomplete': 'list',
1805
- readOnly: !(p.searchable || p.multi) || !!p.readOnly,
1806
- }),
1807
- );
1808
- }
1809
-
1810
- if (p.multi) {
1811
- if (p.singleWrapper) {
1812
- this._cleanupSingleWrapper();
1813
- remove(p.singleWrapper);
1814
- delete p.singleWrapper;
1815
- }
1816
-
1817
- if (!p.list) {
1818
- // Moving `inputWrapper` to a new parent may cause a 'blur' event, and an unwanted chain reaction!
1819
- // So we're unregistering those events here.
1820
- this._unregisterDropdownEvents();
1821
-
1822
- // Restore focus to this one later if we affected it
1823
- const lastActiveElement = document.activeElement;
1824
-
1825
- p.list = createElement('ul', {
1826
- class: `${p.baseClassName}__list`,
1827
- });
1828
- p.el.appendChild(p.list);
1829
- p.list.appendChild(p.inputWrapper);
1830
- p.el.classList.remove(`${p.baseClassName}__single`);
1831
- p.el.classList.add(`${p.baseClassName}__multi`);
1832
-
1833
- // Hook clear and remove
1834
- p.sink
1835
- .add(p.list, 'click', (evt) => {
1836
- if (!closestUntil(evt.target, `.${p.baseClassName}__item_remove`, evt.currentTarget))
1837
- return;
1838
-
1839
- if (p.disabled || p.readOnly) return;
1840
-
1841
- this._removeMultiItemFromEvent(
1842
- /**@type Element*/
1843
- closestUntil(evt.target, `.${p.baseClassName}__item`, evt.currentTarget),
1844
- evt);
1845
- })
1846
- .add(p.list, 'keydown', (/**KeyboardEvent*/evt) => {
1847
- if (!closestUntil(evt.target, `.${p.baseClassName}__item`, evt.currentTarget))
1848
- return;
1849
-
1850
- this._handleMultiKeydown(evt);
1851
- });
1852
-
1853
- if (lastActiveElement === p.input)
1854
- p.input.focus();
1855
-
1856
- this._registerDropdownEvents();
1857
- }
1858
- } else {
1859
- if (p.list) {
1860
- remove(p.list);
1861
- p.sink.remove(p.list);
1862
- delete p.list;
1863
- }
1864
-
1865
- if (!p.singleWrapper) {
1866
- // Moving `inputWrapper` to a new parent may cause a 'blur' event, and an unwanted chain reaction!
1867
- // So we're unregistering those events here.
1868
- this._unregisterDropdownEvents();
1869
-
1870
- // Restore focus to this one later if we affected it
1871
- const lastActiveElement = document.activeElement;
1872
-
1873
- p.singleWrapper = createElement('div', {
1874
- class: `${p.baseClassName}__single_wrapper`,
1875
- });
1876
- p.el.appendChild(p.singleWrapper);
1877
- p.el.appendChild(p.inputWrapper);
1878
- p.el.classList.remove(`${p.baseClassName}__multi`);
1879
- p.el.classList.add(`${p.baseClassName}__single`);
1880
-
1881
- if (lastActiveElement === p.input)
1882
- p.input.focus();
1883
-
1884
- this._registerDropdownEvents();
1885
- }
1886
- }
1887
-
1888
- if (p.hasOpenIndicator !== !!p.openIndicator) {
1889
- if (p.hasOpenIndicator) {
1890
- p.openIndicator = createElement('span', { class: `${p.baseClassName}__open_indicator` });
1891
- p.el.appendChild(p.openIndicator);
1892
- p.el.classList.add(`${p.baseClassName}__has_open_indicator`);
1893
- } else {
1894
- remove(p.openIndicator);
1895
- delete p.openIndicator;
1896
- p.el.classList.remove(`${p.baseClassName}__has_open_indicator`);
1897
- }
1898
- }
1899
-
1900
- if (p.isLoadingMode !== !!p.spinner) {
1901
- if (p.isLoadingMode) {
1902
- p.spinner = createElement('span', { class: `${p.baseClassName}__spinner` });
1903
- p.el.appendChild(p.spinner);
1904
- p.el.classList.add(`${p.baseClassName}__has_spinner`);
1905
- } else {
1906
- remove(p.spinner);
1907
- delete p.spinner;
1908
- p.el.classList.remove(`${p.baseClassName}__has_spinner`);
1909
- }
1910
- }
1911
- }
1912
-
1913
- /**
1914
- * @private
1915
- */
1916
- _syncBaseClasses() {
1917
- const p = this._p, el = p.el;
1918
-
1919
- if (!el)
1920
- return;
1921
-
1922
- let classes = [p.baseClassName];
1923
-
1924
- if (p.multi)
1925
- classes.push(`${p.baseClassName}__multi`);
1926
- else classes.push(`${p.baseClassName}__single`);
1927
-
1928
- if (this.isListOpen())
1929
- classes.push(`${p.baseClassName}__open_list`);
1930
- else classes.push(`${p.baseClassName}__closed_list`);
1931
-
1932
- if (p.hasOpenIndicator)
1933
- classes.push(`${p.baseClassName}__has_open_indicator`);
1934
-
1935
- if (p.clearButtonWrapper)
1936
- classes.push(`${p.baseClassName}__has_clear`);
1937
-
1938
- if (p.isLoadingMode)
1939
- classes.push(`${p.baseClassName}__has_spinner`);
1940
-
1941
- if (p.selectedValues.length === 0)
1942
- classes.push(`${p.baseClassName}__empty_selection`);
1943
-
1944
- if (p.selectedValues.length > 0)
1945
- classes.push(`${p.baseClassName}__has_selection`);
1946
-
1947
- if (p.searchable || p.multi)
1948
- classes.push(`${p.baseClassName}__searchable`);
1949
-
1950
- if (p.direction === 'ltr' || p.direction === 'rtl')
1951
- classes.push(`${p.baseClassName}__` + p.direction);
1952
-
1953
- if (p.additionalClasses) {
1954
- classes = classes.concat(p.additionalClasses);
1955
- }
1956
-
1957
- el.className = classes.join(' ');
1958
- }
1959
-
1960
- /** @private */
1961
- _setupDropdownMenu() {
1962
- const p = this._p, valueProp = p.valueProp;
1963
-
1964
- if (p.dropList) {
1965
- p.dropList.destroy();
1966
- delete p.dropList;
1967
- p.itemsChanged = true;
1968
- p.selectionChanged = true;
1969
- p.resortBySelectionNeeded = true;
1970
- }
1971
-
1972
- const preventDropListMouseDownBlur = (event) => {
1973
- const li = closestUntil(event.target, 'li', event.currentTarget);
1974
- if (!li) return;
1975
-
1976
- event.preventDefault();
1977
- };
1978
- const dropList = p.dropList = new DropList({
1979
- virtualMinItems: 10,
1980
-
1981
- searchable: false,
1982
- ...p.listOptions,
1983
-
1984
- multi: p.multi,
1985
- singleSelectedValue: !p.multi ? this.getValue() : undefined,
1986
- capturesFocus: false,
1987
-
1988
- labelProp: p.labelProp,
1989
- valueProp: p.valueProp,
1990
-
1991
- noResultsText: p.noResultsText,
1992
- filterThrottleWindow: p.filterThrottleWindow,
1993
- filterOnEmptyTerm: p.filterOnEmptyTerm,
1994
- filterGroups: p.treatGroupSelectionAsItems,
1995
- filterEmptyGroups: !p.treatGroupSelectionAsItems,
1996
- filterFn: p.actualFilterFn,
1997
-
1998
- positionOptionsProvider: () => this._getDropListPositionOptions(),
1999
-
2000
- on: (name, event) => {
2001
- switch (name) {
2002
- case 'show:before': {
2003
- p.dropListVisible = true;
2004
- p.el.setAttribute('aria-expanded', 'true');
2005
- p.el.classList.add(`${p.baseClassName}__open_list`);
2006
- p.el.classList.remove(`${p.baseClassName}__closed_list`);
2007
-
2008
- if (p.resortBySelectionNeeded && (p.sortListCheckedFirst && p.multi))
2009
- p.itemsChanged = true;
2010
-
2011
- this._updateListItems();
2012
- this._trigger('open', { list: dropList });
2013
-
2014
- this._startTrackingPresence();
2015
-
2016
- p.sink.add(window, 'resize.trackposition', () => this._repositionDropList());
2017
-
2018
- let parent = p.el.parentNode;
2019
- while (parent) {
2020
- if (parent.scrollHeight > parent.offsetHeight ||
2021
- parent.scrollWidth > parent.offsetWidth) {
2022
- if (parent === document.documentElement) {
2023
- parent = window;
2024
- }
2025
- p.sink.add(parent, 'scroll.trackposition', () => this._repositionDropList());
2026
- }
2027
- parent = parent.parentNode;
2028
- }
2029
- }
2030
- break;
2031
-
2032
- case 'hide': {
2033
- p.dropListVisible = false;
2034
- p.el.setAttribute('aria-expanded', 'false');
2035
- p.el.classList.remove(`${p.baseClassName}__open_list`);
2036
- p.el.classList.add(`${p.baseClassName}__closed_list`);
2037
-
2038
- if (!p.multi) {
2039
- if (p.clearInputWhen.includes('single_close'))
2040
- this._setInputText('');
2041
- this._scheduleSync('render_base');
2042
- } else {
2043
- if (p.clearInputWhen.includes('multi_close'))
2044
- this._setInputText('');
2045
- }
2046
-
2047
- this._trigger('close');
2048
-
2049
- if (this[DestroyedSymbol]) return; // destroyed by event handler
2050
-
2051
- this._stopTrackingPresence();
2052
- p.sink.remove(null, '.trackposition');
2053
- }
2054
- break;
2055
-
2056
- case 'check': {
2057
- if (!p.multi) return;
2058
-
2059
- if (p.autoSelectTextOnCheck && p.input && document.activeElement === p.input) {
2060
- // Select the text in the input, without causing any focus changes
2061
- p.input.setSelectionRange(0, p.input.value.length);
2062
- }
2063
-
2064
- const item = /**@type DropList.Item*/event.item;
2065
- const value = event.value;
2066
-
2067
- let checked = event.checked;
2068
- if (event.isGroup && !p.treatGroupSelectionAsItems) return; // Ignore groups
2069
-
2070
- let selEvt = {
2071
- value: value,
2072
- item: item,
2073
- cancel: false,
2074
- isCheckingGroup: event.isCheckingGroup,
2075
- };
2076
- this._trigger((checked ? 'addsel' : 'removesel') + ':before', selEvt);
2077
-
2078
- if (selEvt.cancel) {
2079
- // Rollback that check
2080
- p.dropList.setItemChecked(value, !checked);
2081
- return;
2082
- }
2083
-
2084
- if (checked) {
2085
- p.selectedItems.push(item);
2086
- p.selectedValues.push(value);
2087
- } else {
2088
- const idx = p.selectedValues.indexOf(value);
2089
- if (idx !== -1) {
2090
- p.selectedItems.splice(idx, 1);
2091
- p.selectedValues.splice(idx, 1);
2092
- }
2093
- }
2094
-
2095
- p.selectionChanged = true;
2096
- p.resortBySelectionNeeded = true;
2097
-
2098
- // If we are in context of group, then there are lots of syncs coming, so do not do it now
2099
- const hasGroupSync = !!event.isCheckingGroup;
2100
-
2101
- if (p.showSelection) {
2102
- if (checked) {
2103
- if (dropList.itemCount() === 1 && p.clearInputWhen.includes('multi_select_single')) {
2104
- this._setInputText('');
2105
- }
2106
-
2107
- if (p.sortSelectedItems) {
2108
- if (!hasGroupSync)
2109
- this._scheduleSync('full');
2110
- } else {
2111
- if (p.maxMultiItems != null &&
2112
- (p.treatGroupSelectionAsItems ? p.selectedItems : p.selectedItems.filter(x => !x._group)).length > p.maxMultiItems) {
2113
- this._scheduleSync('addOrUpdateMultiItemRestElement');
2114
- } else {
2115
- this._scheduleSync('addMultiItemElement', item);
2116
- }
2117
-
2118
- if (!hasGroupSync)
2119
- this._scheduleSync('render_base');
2120
- }
2121
- } else {
2122
- if (p.maxMultiItems != null &&
2123
- (p.treatGroupSelectionAsItems ? p.selectedItems : p.selectedItems.filter(x => !x._group)).length === p.maxMultiItems) {
2124
- this._scheduleSync('removeMultiItemRestElement');
2125
- } else {
2126
- this._scheduleSync('removeMultiItemElement', item);
2127
- }
2128
-
2129
- if (!hasGroupSync)
2130
- this._scheduleSync('render_base');
2131
- }
2132
- } else if (p.multi) {
2133
- this._scheduleSync('syncPlaceholder');
2134
- }
2135
-
2136
- this._trigger(checked ? 'addsel' : 'removesel', {
2137
- value: value,
2138
- item: item,
2139
- isCheckingGroup: event.isCheckingGroup,
2140
- });
2141
- }
2142
- break;
2143
-
2144
- case 'groupcheck': {
2145
- if (!p.multi) return;
2146
-
2147
- if (p.autoSelectTextOnCheck && p.input && document.activeElement === p.input) {
2148
- // Select the text in the input, without causing any focus changes
2149
- p.input.setSelectionRange(0, p.input.value.length);
2150
- }
2151
-
2152
- if (event.affectedCount) {
2153
- this._scheduleSync(p.sortSelectedItems ? 'full' : 'render_base');
2154
- }
2155
-
2156
- this._trigger('groupcheck', {
2157
- value: event.value,
2158
- item: event.item,
2159
- affectedCount: event.affectedCount,
2160
- });
2161
- }
2162
- break;
2163
-
2164
- case 'select':
2165
- case 'subitems:select': {
2166
- if (p.multi) return;
2167
-
2168
- const item = event.item;
2169
- const value = event.value;
2170
-
2171
- if (!this._performSelectWithEvent(item, value))
2172
- return;
2173
-
2174
- if (this[DestroyedSymbol]) return; // destroyed by event handler
2175
-
2176
- this.closeList();
2177
-
2178
- if ((p.blurOnSingleSelection === 'touch' && hasTouchCapability ||
2179
- p.blurOnSingleSelection !== 'touch' && p.blurOnSingleSelection) &&
2180
- p.input && document.activeElement === p.input) {
2181
- p.input.blur();
2182
- }
2183
- }
2184
- break;
2185
-
2186
- case 'show_subitems':
2187
- p.sink.add(event.droplist.el, 'mousedown.subitems', preventDropListMouseDownBlur);
2188
- break;
2189
-
2190
- case 'hide_subitems':
2191
- p.sink.remove(event.droplist.el, '.subitems');
2192
- break;
2193
-
2194
- case 'blur':
2195
- this._handleOnBlur();
2196
- break;
2197
-
2198
- case 'search':
2199
- this._trigger('search', event);
2200
- break;
2201
-
2202
- case 'itemschanged':
2203
- this._trigger('itemschanged', event);
2204
- break;
2205
- }
2206
- },
2207
- });
2208
-
2209
- p.sink.add(dropList.el, 'mousedown', preventDropListMouseDownBlur);
2210
-
2211
- this._registerDropdownEvents();
2212
- }
2213
-
2214
- _handleOnBlur() {
2215
- const p = this._p;
2216
-
2217
- setTimeout(() => {
2218
- if (this[DestroyedSymbol]) return; // destroyed by event handler
2219
- if (p.disabled || p.readOnly) return;
2220
-
2221
- this._trigger('search:blur');
2222
-
2223
- if (this[DestroyedSymbol]) return; // destroyed by event handler
2224
-
2225
- if (document.activeElement &&
2226
- (p.input && p.input.contains(document.activeElement) ||
2227
- p.dropList && this.droplistElContains(document.activeElement, true))) {
2228
- return;
2229
- }
2230
-
2231
- this.closeList();
2232
- });
2233
- }
2234
-
2235
- _unregisterDropdownEvents() {
2236
- const p = this._p;
2237
-
2238
- p.sink.remove(null, '.dropdown');
2239
- }
2240
-
2241
- _registerDropdownEvents() {
2242
- const p = this._p;
2243
-
2244
- this._unregisterDropdownEvents();
2245
-
2246
- const dropList = p.dropList;
2247
- if (!dropList) return;
2248
-
2249
- let avoidToggleFromClick = false,
2250
- currentTouchId = null;
2251
-
2252
- const keyEventsTarget = p.multi || p.searchable ? p.input : p.el;
2253
-
2254
- p.sink
2255
- .add(keyEventsTarget, 'keydown.dropdown', evt => {
2256
- if ((/**@type HTMLInputElement*/evt.currentTarget).readOnly)
2257
- return;
2258
-
2259
- let suppressEnterSpaceToggle = false;
2260
- let lastKeyAllowsNonTypeKeys = p.lastKeyAllowsNonTypeKeys;
2261
- p.lastKeyAllowsNonTypeKeys = false;
2262
- let hasInputText = p.input && p.input.value.length > 0;
2263
-
2264
- switch (evt.key) {
2265
- case VALUE_PAGE_UP:
2266
- case VALUE_PAGE_DOWN:
2267
- case VALUE_UP:
2268
- case VALUE_DOWN:
2269
- case VALUE_HOME:
2270
- case VALUE_END:
2271
- if ((evt.key === VALUE_HOME || evt.key === VALUE_END) &&
2272
- hasInputText && !lastKeyAllowsNonTypeKeys) {
2273
- // Allow using HOME/END button within the textbox
2274
- dropList._keydownFreeType(evt);
2275
- break;
2276
- }
2277
-
2278
- p.lastKeyAllowsNonTypeKeys = true;
2279
- evt.preventDefault();
2280
-
2281
- switch (evt.key) {
2282
- case VALUE_PAGE_UP:
2283
- if (dropList.isVisible())
2284
- dropList.previousPage(evt);
2285
- break;
2286
- case VALUE_PAGE_DOWN:
2287
- if (dropList.isVisible())
2288
- dropList.nextPage(evt);
2289
- break;
2290
- case VALUE_UP:
2291
- if (dropList.isVisible()) {
2292
- dropList.previous(evt);
2293
- } else {
2294
- this._movePrev();
2295
- }
2296
- break;
2297
- case VALUE_DOWN:
2298
- if (dropList.isVisible()) {
2299
- dropList.next(evt);
2300
- } else {
2301
- this._moveNext();
2302
- }
2303
- break;
2304
-
2305
- case VALUE_HOME:
2306
- dropList.goToFirst(evt);
2307
- break;
2308
-
2309
- case VALUE_END:
2310
- dropList.goToLast(evt);
2311
- break;
2312
- }
2313
- break;
2314
-
2315
- case VALUE_SPACE:
2316
- if (lastKeyAllowsNonTypeKeys) {
2317
- p.lastKeyAllowsNonTypeKeys = true;
2318
-
2319
- if (dropList.isVisible() && dropList.hasFocusedItem()) {
2320
- suppressEnterSpaceToggle = true;
2321
- if (p.multi)
2322
- dropList.toggleFocusedItem(evt);
2323
- else dropList.triggerItemSelection(null, evt);
2324
- evt.preventDefault();
2325
- }
2326
- }
2327
- break;
2328
-
2329
- case VALUE_ENTER:
2330
- if (dropList.isVisible() && dropList.hasFocusedItem()) {
2331
- suppressEnterSpaceToggle = true;
2332
- evt.preventDefault();
2333
- dropList.triggerItemSelection(null, evt);
2334
- }
2335
-
2336
- break;
2337
-
2338
- case VALUE_TAB:
2339
- if (dropList.isVisible() && dropList.hasFocusedItem()) {
2340
- dropList.triggerItemSelection(null, evt);
2341
- }
2342
- break;
2343
-
2344
- case VALUE_ESCAPE:
2345
- if (dropList.isVisible()) {
2346
- dropList.hide(evt);
2347
- evt.preventDefault();
2348
- }
2349
- break;
2350
-
2351
- default:
2352
- if (dropList.isVisible()) {
2353
- dropList._keydownFreeType(evt, false);
2354
- } else if (p.allowTypeToSelect) {
2355
- dropList._keydownFreeType(evt, true);
2356
- } else {
2357
- this.openList();
2358
- setTimeout(() => {
2359
- if (this[DestroyedSymbol]) return; // destroyed by event handler
2360
- dropList._keydownFreeType(evt, false);
2361
- });
2362
- }
2363
- break;
2364
- }
2365
-
2366
- if (!suppressEnterSpaceToggle) {
2367
- if (evt.key === VALUE_ENTER || (
2368
- evt.key === VALUE_SPACE &&
2369
- p.lastKeyAllowsNonTypeKeys &&
2370
- !p.multi &&
2371
- !dropList.hasFocusedItem() &&
2372
- !p.disabled &&
2373
- !p.readOnly
2374
- )) {
2375
- this.toggleList();
2376
- evt.preventDefault();
2377
- evt.stopPropagation();
2378
- }
2379
- }
2380
- });
2381
-
2382
- if (p.input) {
2383
- p.sink
2384
- .add(p.input, 'input.dropdown', () => {
2385
- if (p.disabled || p.readOnly) return;
2386
-
2387
- p.filterTerm = p.input.value.trim();
2388
- this._trigger('search:term', p.filterTerm);
2389
- p.dropList?.setSearchTerm(p.filterTerm, true);
2390
- })
2391
- .add(p.input, 'click.dropdown', () => {
2392
- if (p.disabled || p.readOnly) return;
2393
-
2394
- if (!p.multi && p.searchable) {
2395
- this.openList();
2396
- }
2397
- })
2398
- .add(p.input, 'focus.dropdown', () => {
2399
- if (p.disabled || p.readOnly) return;
2400
-
2401
- this._trigger('search:focus');
2402
-
2403
- if (this[DestroyedSymbol]) return; // destroyed by event handler
2404
-
2405
- avoidToggleFromClick = false;
2406
- this.openList();
2407
-
2408
- avoidToggleFromClick = true;
2409
- setTimeout(() => { avoidToggleFromClick = false; }, 10);
2410
- })
2411
- .add(p.input, 'blur.dropdown', () => this._handleOnBlur());
2412
- }
2413
-
2414
- p.sink
2415
- .add(p.el, 'mousedown.dropdown', () => {
2416
- if (!p.multi && !p.searchable && !avoidToggleFromClick && !p.disabled && !p.readOnly) {
2417
- this.toggleList();
2418
- }
2419
- avoidToggleFromClick = false;
2420
- })
2421
- .add(p.el, 'touchstart.dropdown', evt => {
2422
- if (currentTouchId) return;
2423
- currentTouchId = evt.changedTouches[0].identifier;
2424
-
2425
- if (this.isDisabled() || this.isReadOnly())
2426
- return;
2427
-
2428
- if (closestUntil(evt.target, `.${p.baseClassName}__item,.${p.baseClassName}__clear`, p.el))
2429
- return;
2430
-
2431
- let onTouchCancel = () => {
2432
- currentTouchId = null;
2433
- p.sink.remove(p.el, '.dropdown_touchextra');
2434
- };
2435
-
2436
- (p.input || p.el).focus();
2437
-
2438
- p.sink
2439
- .add(p.el, 'touchend.dropdown_touchextra', (tevt) => {
2440
- let touch = Array.prototype.find.call(evt.changedTouches,
2441
- touch => touch.identifier === currentTouchId);
2442
- if (!touch) return onTouchCancel();
2443
-
2444
- tevt.preventDefault();
2445
- onTouchCancel();
2446
- })
2447
- .add(p.el, 'touchmove.dropdown_touchextra', (tevt) => {
2448
- tevt.preventDefault();
2449
- })
2450
- .add(p.el, 'touchcancel.dropdown_touchextra', onTouchCancel);
2451
- });
2452
- }
2453
-
2454
- _performSelectWithEvent(item, value) {
2455
- let cancellable = { value: value, item: item, cancel: false };
2456
- this._trigger('select:before', cancellable);
2457
-
2458
- if (cancellable.cancel)
2459
- return false;
2460
-
2461
- if (this[DestroyedSymbol]) return false; // destroyed by event handler
2462
-
2463
- this._setSelectedItems([item]);
2464
- this._trigger('select', { value: value, item: item });
2465
-
2466
- return true;
2467
- }
2468
-
2469
- _performClearWithEvent(clearInput = false) {
2470
- let cancellable = { cancel: false };
2471
- this._trigger('clear:before', cancellable);
2472
-
2473
- if (cancellable.cancel)
2474
- return false;
2475
-
2476
- if (this[DestroyedSymbol]) return false; // destroyed by event handler
2477
-
2478
- this._setSelectedItems([]);
2479
-
2480
- if (clearInput)
2481
- this._setInputText('');
2482
-
2483
- this._trigger('clear');
2484
-
2485
- return true;
2486
- }
2487
-
2488
- _movePrev() {
2489
- const p = this._p;
2490
-
2491
- if (this.isMultiEnabled()) return;
2492
-
2493
- let selectedItems = this.getSelectedItems();
2494
- let finalItemCount = p.dropList.getFilteredItemCount();
2495
-
2496
- if ((finalItemCount + (p.clearable ? 1 : 0)) > 1) {
2497
- let nextIndex = selectedItems.length > 0
2498
- ? p.dropList.filteredItemIndexByItem(selectedItems[0]) - 1
2499
- : (finalItemCount - 1);
2500
- if (nextIndex === -1 && !p.clearable)
2501
- nextIndex = finalItemCount - 1;
2502
-
2503
- let item = nextIndex === -1 ? null : p.dropList.filteredItemAtIndex(nextIndex);
2504
- if (item) {
2505
- this._performSelectWithEvent(item, item[p.valueProp]);
2506
- } else {
2507
- this._performClearWithEvent();
2508
- }
2509
- }
2510
- }
2511
-
2512
- _moveNext() {
2513
- const p = this._p;
2514
-
2515
- if (this.isMultiEnabled()) return;
2516
-
2517
- let selectedItems = this.getSelectedItems();
2518
- let finalItemCount = p.dropList.getFilteredItemCount();
2519
-
2520
- if ((finalItemCount + (p.clearable ? 1 : 0)) > 1) {
2521
- let nextIndex = selectedItems.length > 0
2522
- ? p.dropList.filteredItemIndexByItem(selectedItems[0]) + 1
2523
- : 0;
2524
- if (nextIndex === finalItemCount)
2525
- nextIndex = p.clearable ? -1 : 0;
2526
-
2527
- let item = nextIndex === -1 ? null : p.dropList.filteredItemAtIndex(nextIndex);
2528
- if (item) {
2529
- this._performSelectWithEvent(item, item[p.valueProp]);
2530
- } else {
2531
- this._performClearWithEvent();
2532
- }
2533
- }
2534
- }
2535
-
2536
- /** @private */
2537
- _updateListItems() {
2538
- const p = this._p;
2539
-
2540
- const dropList = p.dropList;
2541
- if (!dropList || !p.dropListVisible)
2542
- return;
2543
-
2544
- if (p.itemsChanged || p.selectionChanged) {
2545
- p.dropList._lastSerializedBox = null;
2546
- }
2547
-
2548
- if (p.itemsChanged) {
2549
- let items = p.items;
2550
- if (p.sortListItems || (p.sortListCheckedFirst && p.multi)) {
2551
- items = this._sortItems(items,
2552
- p.sortListItems,
2553
- p.sortListCheckedFirst && p.multi,
2554
- p.splitListCheckedGroups);
2555
- }
2556
- dropList.setItems(items);
2557
- dropList.invokeRefilter();
2558
- p.itemsChanged = false;
2559
- p.selectionChanged = true;
2560
- p.resortBySelectionNeeded = false;
2561
- }
2562
-
2563
- let hasRefocusedItem = false;
2564
-
2565
- if (p.selectionChanged) {
2566
- if (p.multi) {
2567
- p.dropList.setCheckedValues(p.selectedValues);
2568
- } else {
2569
- const singleValue = this.getValue();
2570
- const singleItemIndex = p.dropList.itemIndexByValue(singleValue);
2571
-
2572
- p.dropList
2573
- .setFocusedItemAtIndex(singleItemIndex)
2574
- .setSingleSelectedItemByValue(singleValue);
2575
-
2576
- hasRefocusedItem = p.dropList.hasFocusedItem();
2577
- }
2578
- p.selectionChanged = false;
2579
- }
2580
-
2581
- this._repositionDropList();
2582
-
2583
- if (hasRefocusedItem) {
2584
- p.dropList.setFocusedItemAtIndex(p.dropList.getFocusedItemIndex());
2585
- }
2586
- }
2587
-
2588
- /** @private */
2589
- _setSelectedItems(items) {
2590
- const p = this._p, valueProp = p.valueProp;
2591
-
2592
- if (p.multi) {
2593
- p.selectedItems = items.filter(x => x[valueProp] !== undefined);
2594
- p.selectedValues = p.selectedItems.map(x => x[valueProp]);
2595
- } else {
2596
- p.selectedItems = items.slice(0, 1);
2597
- p.selectedValues = items.slice(0, 1).map(x => x[valueProp]);
2598
- }
2599
-
2600
- p.selectionChanged = true;
2601
- p.resortBySelectionNeeded = true;
2602
-
2603
- this._updateListItems();
2604
- this._scheduleSync('full');
2605
- }
2606
-
2607
- /** @private */
2608
- _scheduleSync(mode, data) {
2609
- const p = this._p;
2610
-
2611
- if (!p.syncQueue)
2612
- p.syncQueue = [];
2613
-
2614
- if (mode === 'full' || ('render_items' === mode && !p.syncQueue.some(x => x.mode === 'full')))
2615
- p.syncQueue.length = 0;
2616
-
2617
- if (p.syncQueue.length === 0 ||
2618
- (!['full', 'render_items'].includes(mode)))
2619
- p.syncQueue.push({ mode: mode, data: data });
2620
-
2621
- if (p.syncTimeout)
2622
- return;
2623
-
2624
- p.syncTimeout = setTimeout(() => {
2625
- delete p.syncTimeout;
2626
- let queue = p.syncQueue;
2627
- delete p.syncQueue;
2628
- this._performSync(queue);
2629
- });
2630
- }
2631
-
2632
- /** @private */
2633
- _performSync(queue) {
2634
- const p = this._p;
2635
-
2636
- if (this[DestroyedSymbol])
2637
- return;
2638
-
2639
- for (let op of queue) {
2640
- switch (op.mode) {
2641
- case 'full':
2642
- this._syncFull(true, true);
2643
- break;
2644
-
2645
- case 'render_base':
2646
- this._syncFull(false, false);
2647
- break;
2648
-
2649
- case 'render_items':
2650
- this._syncFull(true, false);
2651
- break;
2652
-
2653
- case 'render_list':
2654
- this._syncFull(false, true);
2655
- break;
2656
-
2657
- case 'render_clear':
2658
- this._syncClearButton();
2659
- this._resizeInput();
2660
- break;
2661
-
2662
- case 'singleItem':
2663
- this._syncSingleItem();
2664
- break;
2665
-
2666
- case 'syncPlaceholder':
2667
- this._syncPlaceholder();
2668
- break;
2669
-
2670
- case 'removeMultiItemElement': {
2671
- if (p.showSelection) {
2672
- this._syncPlaceholder();
2673
- } else {
2674
- const valueProp = p.valueProp;
2675
- const item = op.data,
2676
- value = item[valueProp];
2677
-
2678
- let idx = p.multiItemEls.findIndex(x => x[ItemSymbol][valueProp] === value);
2679
- if (idx !== -1) {
2680
- this._removeMultiItemElementByIndex(idx);
2681
- }
2682
- }
2683
- }
2684
- break;
2685
-
2686
- case 'addMultiItemElement': {
2687
- if (!p.showSelection) {
2688
- this._syncPlaceholder();
2689
- } else {
2690
- this._addMultiItemElement(op.data);
2691
- }
2692
- }
2693
- break;
2694
-
2695
- case 'addOrUpdateMultiItemRestElement': {
2696
- if (!p.showSelection) {
2697
- this._syncPlaceholder();
2698
- } else {
2699
- this._addMultiItemRestElement();
2700
- }
2701
- }
2702
- break;
2703
-
2704
- case 'removeMultiItemRestElement': {
2705
- if (!p.showSelection) {
2706
- this._syncPlaceholder();
2707
- } else {
2708
- let itemEl = p.multiItemEls[p.multiItemEls.length - 1];
2709
- if (itemEl?.[ItemSymbol]?.[p.valueProp] === RestMultiItemsSymbol) {
2710
- this._removeMultiItemElementByIndex(p.multiItemEls.length - 1);
2711
- }
2712
- }
2713
- }
2714
- break;
2715
-
2716
- case 'resize_input': {
2717
- this._resizeInput();
2718
- }
2719
- break;
2720
- }
2721
- }
2722
- }
2723
-
2724
- /** @private */
2725
- _cleanupSingleWrapper() {
2726
- const p = this._p;
2727
-
2728
- if (!p.singleWrapper) return;
2729
-
2730
- if (p.unrenderSingleItem && p.singleWrapper.childNodes.length > 0) {
2731
- try {
2732
- p.unrenderSingleItem(p.singleWrapper[ItemSymbol], p.singleWrapper);
2733
- } catch (err) {
2734
- console.error(err); // eslint-disable-line no-console
2735
- }
2736
- }
2737
-
2738
- delete p.singleWrapper[ItemSymbol];
2739
- p.singleWrapper.innerHTML = '';
2740
- }
2741
-
2742
- /**
2743
- * @param {number} index
2744
- * @private
2745
- */
2746
- _removeMultiItemElementByIndex(index) {
2747
- const p = this._p, multiItemEls = p.multiItemEls;
2748
-
2749
- if (multiItemEls.length > index) {
2750
- const itemEl = multiItemEls[index];
2751
- const item = itemEl[ItemSymbol];
2752
-
2753
- let unrender = item?.[p.valueProp] === RestMultiItemsSymbol
2754
- ? p.unrenderRestMultiItem ?? p.unrenderMultiItem
2755
- : p.unrenderMultiItem;
2756
-
2757
- if (unrender && itemEl.childNodes.length > 0) {
2758
- try {
2759
- unrender(item, itemEl);
2760
- } catch (err) {
2761
- console.error(err); // eslint-disable-line no-console
2762
- }
2763
- }
2764
- remove(itemEl);
2765
-
2766
- // fastpath
2767
- if (index === multiItemEls.length - 1) multiItemEls.pop();
2768
- else multiItemEls.splice(index, 1);
2769
- }
2770
- }
2771
-
2772
- /**
2773
- * @param {DropList.ItemBase} item
2774
- * @private
2775
- */
2776
- _renderSingleItemContent(item) {
2777
- const p = this._p;
2778
-
2779
- if (!p.renderSingleItem || p.renderSingleItem(item, p.singleWrapper) === false) {
2780
- const labelProp = p.labelProp,
2781
- multiItemLabelProp = p.multiItemLabelProp;
2782
-
2783
- let label = item[multiItemLabelProp] || item[labelProp];
2784
- if (label === null || label === undefined)
2785
- label = '';
2786
-
2787
- p.singleWrapper.appendChild(document.createTextNode(label));
2788
- }
2789
- }
2790
-
2791
- /**
2792
- * @param {DropList.ItemBase} item
2793
- * @param {Element} itemEl
2794
- * @private
2795
- */
2796
- _renderMultiItemContent(item, itemEl) {
2797
- const p = this._p;
2798
-
2799
- let render = item[p.valueProp] === RestMultiItemsSymbol
2800
- ? p.renderRestMultiItem ?? p.renderMultiItem
2801
- : p.renderMultiItem;
2802
-
2803
- if (!render || render(item, itemEl) === false) {
2804
- const labelProp = p.labelProp,
2805
- multiItemLabelProp = p.multiItemLabelProp;
2806
- const label = item[multiItemLabelProp] || item[labelProp];
2807
- itemEl.appendChild(createElement('span', {
2808
- textContent: label,
2809
- }));
2810
- }
2811
- }
2812
-
2813
- /**
2814
- * @param {DropList.ItemBase} item
2815
- * @returns {boolean} true if rendered, false if not
2816
- * @private
2817
- */
2818
- _addMultiItemElement(item) {
2819
- const p = this._p;
2820
- const itemEl = this._renderMultiItem(item);
2821
- if (!itemEl) return false;
2822
-
2823
- before(p.inputWrapper, itemEl);
2824
- p.multiItemEls.push(itemEl);
2825
-
2826
- return true;
2827
- }
2828
-
2829
- /** @private */
2830
- _addMultiItemRestElement() {
2831
- const p = this._p;
2832
-
2833
- let items = p.selectedItems.slice(0);
2834
- let count = (p.treatGroupSelectionAsItems ? items : items.filter(x => !x._group)).length - p.maxMultiItems;
2835
- let label = p.multiItemsRestLabelProvider
2836
- ? p.multiItemsRestLabelProvider(count, items)
2837
- : `+ ${count}`;
2838
-
2839
- this._addMultiItemElement({
2840
- items: items,
2841
- [p.valueProp]: RestMultiItemsSymbol,
2842
- [p.labelProp]: label,
2843
- });
2844
- }
2845
-
2846
- /** @private */
2847
- _syncClearButton() {
2848
- const p = this._p,
2849
- multiItemLabelProp = p.multiItemLabelProp;
2850
-
2851
- // Set clear button
2852
- if (p.selectedItems.length > 0 &&
2853
- p.selectedItems.some(x => x[multiItemLabelProp] !== false) &&
2854
- p.clearable && p.showSelection) {
2855
- if (!p.clearButtonWrapper) {
2856
- p.clearButtonWrapper = createElement(
2857
- p.multi ? 'li' : 'span',
2858
- { class: `${p.baseClassName}__clear` },
2859
- p.clearButton = createElement('button'));
2860
- if (p.multi)
2861
- append(p.list, p.clearButtonWrapper);
2862
- else append(p.el, p.clearButtonWrapper);
2863
- p.el.classList.add(`${p.baseClassName}__has_clear`);
2864
-
2865
- p.sink.add(p.clearButton, 'click', () => {
2866
- if (this.isDisabled() || this.isReadOnly()) return;
2867
- this.clear();
2868
- });
2869
- }
2870
- } else {
2871
- if (p.clearButtonWrapper) {
2872
- p.sink.remove(p.clearButton, 'click');
2873
-
2874
- remove(p.clearButtonWrapper);
2875
- delete p.clearButtonWrapper;
2876
- delete p.clearButton;
2877
- p.el.classList.remove(`${p.baseClassName}__has_clear`);
2878
- }
2879
- }
2880
- }
2881
-
2882
- /** @private */
2883
- _syncPlaceholder() {
2884
- const p = this._p,
2885
- multiItemLabelProp = p.multiItemLabelProp;
2886
-
2887
- let placeholder = '';
2888
-
2889
- if (p.multi && !p.showSelection) {
2890
- if (typeof p.multiPlaceholderFormatter === 'function') {
2891
- placeholder = p.multiPlaceholderFormatter(p.selectedItems);
2892
- } else {
2893
- placeholder = p.selectedItems.length === 0
2894
- ? (p.placeholder || '')
2895
- : defaultMultiPlaceholderFormatter(p.selectedItems, p.labelProp);
2896
- }
2897
- } else if (p.selectedItems.length === 0 ||
2898
- !p.showSelection ||
2899
- p.selectedItems.every(x => x[multiItemLabelProp] === false)) {
2900
- placeholder = p.placeholder == null ? '' : (p.placeholder + '');
2901
- }
2902
-
2903
- // Set input placeholder
2904
- p.input.setAttribute('placeholder', placeholder);
2905
-
2906
- if (p.showPlaceholderInTooltip) {
2907
- p.input.setAttribute('title', placeholder);
2908
- } else {
2909
- p.input.removeAttribute('title');
2910
- }
2911
- }
2912
-
2913
- /** @private */
2914
- _syncSingleItem() {
2915
- const p = this._p;
2916
-
2917
- if (p.singleWrapper)
2918
- this._cleanupSingleWrapper();
2919
-
2920
- const items = p.selectedItems;
2921
-
2922
- if (items.length > 0) {
2923
- this._renderSingleItemContent(items[0]);
2924
- p.singleWrapper[ItemSymbol] = items[0];
2925
- }
2926
- }
2927
-
2928
- /**
2929
- * Syncs render state, selected items, and position
2930
- * @param {boolean=false} fullItemsRender Should re-render all items?
2931
- * @param {boolean=false} updateListItems Should call updateListItems?
2932
- * @returns {SelectBox}
2933
- */
2934
- _syncFull(fullItemsRender, updateListItems) {
2935
- const p = this._p,
2936
- multiItemLabelProp = p.multiItemLabelProp;
2937
-
2938
- this._renderBase();
2939
- this._syncClearButton();
2940
- this._syncPlaceholder();
2941
-
2942
- fullItemsRender = p.multi &&
2943
- p.showSelection &&
2944
- (fullItemsRender || p.selectedItems.filter(x => x[multiItemLabelProp] !== false).length !== p.multiItemEls.length);
2945
-
2946
- if (fullItemsRender || !p.showSelection || !p.multi) {
2947
- // Remove all item elements
2948
- while (p.multiItemEls.length > 0) {
2949
- // use fast path by removing in reverse
2950
- this._removeMultiItemElementByIndex(p.multiItemEls.length - 1);
2951
- }
2952
- }
2953
-
2954
- if (p.multi) {
2955
- if (fullItemsRender) {
2956
- const items = p.selectedItems;
2957
- const treatGroupSelectionAsItems = p.treatGroupSelectionAsItems;
2958
-
2959
- // Sort these
2960
- if (p.sortSelectedItems) {
2961
- const labelProp = p.labelProp,
2962
- multiItemLabelProp = p.multiItemLabelProp,
2963
- valueProp = p.valueProp,
2964
- stickyValues = p.stickyValues;
2965
-
2966
- const comparator = p.sortItemComparator || ((a, b) => {
2967
- if (stickyValues !== null) {
2968
- let sa = stickyValues.has(a[valueProp]);
2969
- let sb = stickyValues.has(b[valueProp]);
2970
- if (sa && !sb) return -1;
2971
- if (!sa && sb) return 1;
2972
- }
2973
-
2974
- const aLabel = a[multiItemLabelProp] || a[labelProp];
2975
- const bLabel = b[multiItemLabelProp] || b[labelProp];
2976
- return aLabel < bLabel ? -1 : (aLabel > bLabel ? 1 : 0);
2977
- });
2978
-
2979
- items.sort(comparator);
2980
-
2981
- p.selectedValues = items.map(x => x[valueProp]);
2982
- }
2983
-
2984
- let actualItemCount = 0;
2985
- let max = p.maxMultiItems;
2986
- let addRestItem = false;
2987
-
2988
- // Add item elements
2989
- for (let i = 0; i < items.length; i++) {
2990
- if (!treatGroupSelectionAsItems && items[i]._group) continue;
2991
-
2992
- if (max != null && actualItemCount === max) {
2993
- addRestItem = true;
2994
- break;
2995
- }
2996
-
2997
- if (this._addMultiItemElement(items[i])) {
2998
- actualItemCount++;
2999
- }
3000
- }
3001
-
3002
- if (addRestItem) {
3003
- this._addMultiItemRestElement();
3004
- }
3005
- }
3006
- } else if (!p.multi) {
3007
- this._syncSingleItem();
3008
- }
3009
-
3010
- if (getRootNode(p.el) !== document)
3011
- return this;
3012
-
3013
- toggleClass(p.el, `${p.baseClassName}__empty_selection`, p.selectedValues.length === 0);
3014
- toggleClass(p.el, `${p.baseClassName}__has_selection`, p.selectedValues.length > 0);
3015
-
3016
- if (p.searchable) {
3017
- if (p.input) p.input.readOnly = p.readOnly;
3018
- p.el.classList.add(`${p.baseClassName}__searchable`);
3019
- } else {
3020
- if (p.input) p.input.readOnly = true;
3021
- p.el.classList.remove(`${p.baseClassName}__searchable`);
3022
- }
3023
-
3024
- // Update input size
3025
- this._resizeInput();
3026
-
3027
- if (updateListItems) {
3028
- this._updateListItems();
3029
- }
3030
-
3031
- return this;
3032
- }
3033
-
3034
- /**
3035
- * @param {string} event
3036
- * @param {*} [data]
3037
- * @private
3038
- */
3039
- _trigger(event, data) {
3040
- const p = this._p;
3041
- if (p === undefined)
3042
- return;
3043
- if (p.on)
3044
- p.on(event, ...(data === undefined ? [] : [data]));
3045
- p.mitt.emit(event, data);
3046
- }
3047
-
3048
- /**
3049
- * Render a multi item
3050
- * @param {Object} item
3051
- * @returns {Element|null}
3052
- * @private
3053
- */
3054
- _renderMultiItem(item) {
3055
- const p = this._p;
3056
-
3057
- const labelProp = p.labelProp,
3058
- multiItemLabelProp = p.multiItemLabelProp;
3059
- const label = item[multiItemLabelProp] ?? item[labelProp];
3060
- if (label === false)
3061
- return null;
3062
-
3063
- const elRemove = createElement('span', {
3064
- class: `${p.baseClassName}__item_remove`,
3065
- role: 'presentation',
3066
- });
3067
-
3068
- const itemEl = createElement('li',
3069
- {
3070
- class: `${p.baseClassName}__item`,
3071
- tabindex: '0',
3072
- title: label,
3073
- },
3074
- );
3075
-
3076
- if (p.multiItemRemovePosition === 'before') {
3077
- itemEl.appendChild(elRemove);
3078
- }
3079
-
3080
- this._renderMultiItemContent(item, itemEl);
3081
-
3082
- if (p.multiItemRemovePosition === 'after') {
3083
- itemEl.appendChild(elRemove);
3084
- }
3085
-
3086
- itemEl[ItemSymbol] = item;
3087
-
3088
- return itemEl;
3089
- }
3090
-
3091
- /**
3092
- * Removes a specific multi item by user event
3093
- * @param {Element} itemEl
3094
- * @param {Event} originatingEvent
3095
- * @returns {SelectBox}
3096
- * @private
3097
- */
3098
- _removeMultiItemFromEvent(itemEl, originatingEvent) {
3099
- const p = this._p;
3100
-
3101
- let nextFocus;
3102
- if (/key/.test(originatingEvent.type)) {
3103
- const kEvent = /**@type KeyboardEvent*/originatingEvent;
3104
- if (kEvent.key === VALUE_DELETE) { // Delete
3105
- nextFocus = next(itemEl, `.${p.baseClassName}__item,.${p.baseClassName}__search_wrapper`);
3106
- } else if (kEvent.key === VALUE_BACK_SPACE) { // Backspace
3107
- nextFocus = prev(itemEl, `.${p.baseClassName}__item,.${p.baseClassName}__search_wrapper`);
3108
- }
3109
- } else if (/click|mouse|touch/.test(originatingEvent.type)) {
3110
- nextFocus = next(itemEl, `.${p.baseClassName}__item,.${p.baseClassName}__search_wrapper`);
3111
- }
3112
-
3113
- const item = itemEl[ItemSymbol], value = item[p.valueProp];
3114
-
3115
- if (item !== undefined) {
3116
- if (value === RestMultiItemsSymbol) {
3117
- let items = (p.treatGroupSelectionAsItems ? p.selectedItems : p.selectedItems.filter(x => !x._group))
3118
- .slice(p.maxMultiItems);
3119
- let itemsToRemove = [];
3120
-
3121
- for (let item of items) {
3122
- let removeselEvt = { value: value, item: item, cancel: false };
3123
- this._trigger('removesel:before', removeselEvt);
3124
- if (!removeselEvt.cancel)
3125
- itemsToRemove.push(item);
3126
- }
3127
-
3128
- if (itemsToRemove.length > 0) {
3129
- // remove the "rest" element, we'll add that back later if necessary
3130
- this._removeMultiItemElementByIndex(p.multiItemEls.length - 1);
3131
-
3132
- for (let item of itemsToRemove) {
3133
- // sync selection
3134
- let idx = p.selectedItems.indexOf(item);
3135
- if (idx === -1)
3136
- idx = p.selectedValues.indexOf(value[p.valueProp]);
3137
- if (idx !== -1) {
3138
- p.selectedItems.splice(idx, 1);
3139
- p.selectedValues.splice(idx, 1);
3140
- p.selectionChanged = true;
3141
- p.resortBySelectionNeeded = true;
3142
- }
3143
- }
3144
- }
3145
-
3146
- // we have not removed the whole "rest", then add the "rest" element back
3147
- if (items.length > itemsToRemove.length) {
3148
- this._addMultiItemRestElement();
3149
- }
3150
-
3151
- if (itemsToRemove.length > 0) {
3152
- this._scheduleSync('render_list');
3153
- }
3154
- } else {
3155
- let removeselEvt = { value: value, item: item, cancel: false };
3156
- this._trigger('removesel:before', removeselEvt);
3157
- if (removeselEvt.cancel)
3158
- return this;
3159
-
3160
- this._removeMultiItem(item);
3161
-
3162
- // trigger event
3163
- this._trigger('removesel', { value: value, item: item });
3164
- }
3165
- }
3166
-
3167
- if (!nextFocus) {
3168
- nextFocus = p.el.querySelector(`.${p.baseClassName}__item, .${p.baseClassName}__search_field`);
3169
- }
3170
-
3171
- if (hasClass(nextFocus, `${p.baseClassName}__search_wrapper`)) {
3172
- nextFocus = nextFocus.querySelector('input');
3173
- }
3174
-
3175
- nextFocus && nextFocus.focus();
3176
-
3177
- return this;
3178
- }
3179
-
3180
- /**
3181
- * @param {DropList.ItemBase} item
3182
- * @param {boolean} [populate]
3183
- * @private
3184
- */
3185
- _removeMultiItem(item, populate = false) {
3186
- const p = this._p;
3187
- const valueProp = p.valueProp,
3188
- labelProp = p.labelProp;
3189
- const value = item[valueProp];
3190
-
3191
- // sync selection
3192
- let idx = p.selectedItems.indexOf(item);
3193
- if (idx === -1)
3194
- idx = p.selectedValues.indexOf(value);
3195
- if (idx !== -1) {
3196
- p.selectedItems.splice(idx, 1);
3197
- p.selectedValues.splice(idx, 1);
3198
- p.selectionChanged = true;
3199
- p.resortBySelectionNeeded = true;
3200
- }
3201
-
3202
- // sync multi item element
3203
- idx = p.multiItemEls.findIndex(x => x[ItemSymbol] === item);
3204
- if (idx === -1)
3205
- idx = p.multiItemEls.findIndex(x => x[ItemSymbol][valueProp] === value);
3206
- if (idx !== -1) {
3207
- this._removeMultiItemElementByIndex(idx);
3208
- }
3209
-
3210
- if (populate) {
3211
- this._setInputText(item[p.multiItemLabelProp] || item[labelProp]);
3212
-
3213
- p.input.focus();
3214
-
3215
- // Go to end of input
3216
- p.input.selectionStart = p.input.selectionEnd = p.input.value.length;
3217
- }
3218
-
3219
- // sync
3220
- this._scheduleSync('render_list');
3221
- }
3222
-
3223
- /**
3224
- * @param {*} value
3225
- * @private
3226
- */
3227
- _setInputText(value) {
3228
- const p = this._p;
3229
-
3230
- p.input.value = value == null ? '' : String(value);
3231
-
3232
- p.filterTerm = '';
3233
- this._trigger('search:term', p.filterTerm);
3234
- p.dropList?.setSearchTerm('', true);
3235
- }
3236
-
3237
- /**
3238
- * Update input size to current state
3239
- * @returns {SelectBox}
3240
- * @private
3241
- */
3242
- _resizeInput() {
3243
- const p = this._p, el = p.el;
3244
-
3245
- if (!el.parentNode || !document.body.contains(el))
3246
- return this;
3247
-
3248
- const input = p.input, backBufferEl = p.inputBackBuffer;
3249
-
3250
- let inputValue = input.value || input.placeholder;
3251
- toggleClass(el, `${p.baseClassName}__has_input`, !!inputValue);
3252
- toggleClass(el, `${p.baseClassName}__empty_input`, !inputValue);
3253
-
3254
- let hasResize = false;
3255
-
3256
- if (p.multi && p.multiItemEls.length === 0 && p.showSelection) {
3257
- // Full width of list wrapper
3258
- input.style.width = ''; // reset first
3259
-
3260
- let beforeWidth = 0, afterWidth = 0;
3261
-
3262
- let beforeStyle = getComputedStyle(p.list || el, '::before');
3263
- if (beforeStyle.content &&
3264
- beforeStyle.content !== 'none' &&
3265
- beforeStyle.position !== 'absolute' &&
3266
- beforeStyle.float !== 'none') {
3267
- beforeWidth = getPseudoElementWidth(p.list || el, '::before', true, true, true);
3268
- }
3269
-
3270
- let afterStyle = getComputedStyle(p.list || el, '::after');
3271
- if (afterStyle.content &&
3272
- afterStyle.content !== 'none' &&
3273
- afterStyle.position !== 'absolute' &&
3274
- afterStyle.float !== 'none') {
3275
- afterWidth = getPseudoElementWidth(p.list || el, '::after', true, true, true);
3276
- }
3277
-
3278
- let contentWidth = getElementWidth(p.list || el); // calculate width
3279
- contentWidth -= beforeWidth + afterWidth;
3280
-
3281
- input.style.width = `${contentWidth}px`;
3282
-
3283
- hasResize = true; // We may want to track the resize here better to avoid unnecessary event
3284
- } else {
3285
- // Introduce backbuffer to DOM
3286
- setCssProps(backBufferEl, getCssProps(input, inputBackbufferCssProps));
3287
- backBufferEl.textContent = inputValue;
3288
- el.appendChild(backBufferEl);
3289
-
3290
- // Measure these
3291
- const computedStyle = getComputedStyle(input);
3292
- const paddingTotal = (parseFloat(computedStyle.paddingLeft) || 0) + (parseFloat(computedStyle.paddingRight) || 0);
3293
- const minWidth = (parseFloat(computedStyle['font-size']) || 0) * 0.75 + paddingTotal;
3294
- const backBufferWidth = getElementWidth(backBufferEl, true, true);
3295
- const currentWidth = getElementWidth(input, true, true);
3296
- let newWidth = Math.max(backBufferWidth, minWidth);
3297
-
3298
- // Compare
3299
- if (newWidth !== currentWidth) {
3300
- // Update if needed
3301
- setElementWidth(input, newWidth, true, true);
3302
-
3303
- let bordersWidth = (parseFloat(computedStyle.borderLeftWidth) || 0) + (parseFloat(computedStyle.borderRightWidth) || 0);
3304
- let scrollWidth = input.scrollWidth + bordersWidth;
3305
-
3306
- if (scrollWidth > newWidth) {
3307
- // consider scrollWidth delta
3308
- let delta = scrollWidth - newWidth;
3309
- input.style.width = `${parseFloat(input.style.width) + delta}px`;
3310
-
3311
- newWidth += delta;
3312
- }
3313
-
3314
- // sync the single value wrapper.
3315
- // it is meant as a preview or spacer for single selection value, so its appropriate to sync it with this width
3316
- if (p.singleWrapper) {
3317
- p.singleWrapper.style.width = '';
3318
-
3319
- if (inputValue) {
3320
- let width = newWidth - paddingTotal - bordersWidth;
3321
- if (getElementWidth(p.singleWrapper, false, false) < width) {
3322
- setElementWidth(p.singleWrapper, width, false, false);
3323
- }
3324
- }
3325
- }
3326
-
3327
- hasResize = true;
3328
- }
3329
-
3330
- // Remove backbuffer from DOM
3331
- remove(backBufferEl);
3332
- }
3333
-
3334
- if (hasResize)
3335
- this._trigger('input:resize');
3336
-
3337
- return this;
3338
- }
3339
-
3340
- /**
3341
- * Update autocomplete position if needed
3342
- * @returns {SelectBox}
3343
- * @private
3344
- */
3345
- _repositionDropList() {
3346
- const p = this._p, el = p.el;
3347
-
3348
- if (!p.dropList || !p.dropListVisible || !p.dropList.isVisible())
3349
- return this;
3350
-
3351
- const box = el.getBoundingClientRect();
3352
- const serialized = box.left + ',' + box.top + ',' + box.right + ',' + box.bottom;
3353
-
3354
- if (p.dropList._lastSerializedBox !== serialized) {
3355
- p.dropList.relayout();
3356
- p.dropList._lastSerializedBox = serialized;
3357
- }
3358
-
3359
- return this;
3360
- }
3361
-
3362
- /**
3363
- * @param {KeyboardEvent} event
3364
- * @private
3365
- */
3366
- _handleInputKeydown(event) {
3367
- const p = this._p;
3368
-
3369
- const target = (/**@type HTMLInputElement*/event.target);
3370
-
3371
- if (event.key === VALUE_BACK_SPACE && event.ctrlKey && target.value.length === 0) {
3372
- this.clear();
3373
-
3374
- event.preventDefault();
3375
- } else if (event.key === VALUE_BACK_SPACE && target.value.length === 0) {
3376
- const itemEl = p.multiItemEls[p.multiItemEls.length - 1];
3377
- if (!itemEl)
3378
- return;
3379
-
3380
- const item = itemEl[ItemSymbol], value = item[p.valueProp];
3381
- if (value === undefined)
3382
- return;
3383
-
3384
- let removeselEvt = { value: value, item: item, cancel: false };
3385
- this._trigger('removesel:before', removeselEvt);
3386
- if (removeselEvt.cancel)
3387
- return;
3388
-
3389
- this._removeMultiItem(item, true);
3390
-
3391
- // trigger event
3392
- this._trigger('removesel', { value: value, item: item });
3393
-
3394
- event.preventDefault();
3395
- }
3396
- }
3397
-
3398
- /**
3399
- * @param {KeyboardEvent} event
3400
- * @private
3401
- */
3402
- _handleMultiKeydown(event) {
3403
- const p = this._p;
3404
-
3405
- if (p.disabled || p.readOnly) return;
3406
-
3407
- const isRtl = getComputedStyle(p.el).direction === 'rtl';
3408
-
3409
- let nextFocus;
3410
-
3411
- if (event.key === (isRtl ? VALUE_LEFT : VALUE_RIGHT)) { // Next arrow
3412
- nextFocus = next(/**@type Element*/event.target, `.${p.baseClassName}__item,.${p.baseClassName}__search_wrapper`);
3413
- if (hasClass(nextFocus, `${p.baseClassName}__search_wrapper`)) {
3414
- nextFocus = nextFocus.querySelector('input');
3415
- }
3416
- nextFocus && nextFocus.focus();
3417
-
3418
- event.preventDefault();
3419
- } else if (event.key === (isRtl ? VALUE_RIGHT : VALUE_LEFT)) { // Prev arrow
3420
- nextFocus = prev(/**@type Element*/event.target, `.${p.baseClassName}__item,.${p.baseClassName}__search_wrapper`);
3421
- if (hasClass(nextFocus, `${p.baseClassName}__search_wrapper`)) {
3422
- nextFocus = nextFocus.querySelector('input');
3423
- }
3424
- nextFocus && nextFocus.focus();
3425
-
3426
- event.preventDefault();
3427
- } else if (event.key === VALUE_BACK_SPACE && event.ctrlKey) { // Ctrl + Backspace
3428
- const multiItemEls = [];
3429
- let itemEl = event.target;
3430
- while (itemEl) {
3431
- multiItemEls.push(itemEl);
3432
- itemEl = prev(/**@type Element*/itemEl, `.${p.baseClassName}__item`);
3433
- }
3434
-
3435
- while (multiItemEls.length) {
3436
- this._removeMultiItemFromEvent(multiItemEls.shift(), event);
3437
- }
3438
-
3439
- event.preventDefault();
3440
- } else if (event.key === VALUE_DELETE || event.key === VALUE_BACK_SPACE) { // Delete / Backspace
3441
- this._removeMultiItemFromEvent(closestUntil(event.target, `.${p.baseClassName}__item`, p.el), event);
3442
- event.preventDefault();
3443
- }
3444
- }
3445
-
3446
- /**
3447
- * @returns {DropList.PositionOptions}
3448
- * @private
3449
- */
3450
- _getDropListPositionOptions() {
3451
- const p = this._p;
3452
-
3453
- return {
3454
- target: /**@type Element*/p.el,
3455
- offset: { x: 0, y: 0 },
3456
- anchor: { x: 'start', y: 'bottom' },
3457
- position: { x: 'start', y: 'top' },
3458
- updateWidth: true,
3459
- };
3460
- }
3461
-
3462
- /** @private */
3463
- _startTrackingPresence() {
3464
- const p = this._p;
3465
-
3466
- this._stopTrackingPresence();
3467
-
3468
- p.presenceInt = setInterval(() => {
3469
- if (getRootNode(p.el) !== document)
3470
- this.closeList();
3471
- }, 200);
3472
- }
3473
-
3474
- /** @private */
3475
- _stopTrackingPresence() {
3476
- const p = this._p;
3477
-
3478
- if (p.presenceInt) {
3479
- clearInterval(p.presenceInt);
3480
- p.presenceInt = null;
3481
- }
3482
- }
3483
-
3484
- /**
3485
- * Handles sorting, and putting checked items first (according to selectedValues, not item.checked)
3486
- * @private
3487
- * @param {DropList.ItemBase[]} items
3488
- * @param {boolean=false} sort
3489
- * @param {boolean=false} sortCheckedFirst
3490
- * @param {boolean=false} splitCheckedGroups
3491
- * @returns {DropList.ItemBase[]}
3492
- */
3493
- _sortItems(items, sort, sortCheckedFirst, splitCheckedGroups) {
3494
- const p = this._p;
3495
-
3496
- if (!sort && !sortCheckedFirst)
3497
- return items; // Nothing to do
3498
-
3499
- const labelProp = p.labelProp,
3500
- multiItemLabelProp = p.multiItemLabelProp,
3501
- valueProp = p.valueProp,
3502
- stickyValues = p.stickyValues,
3503
- comparator = p.sortItemComparator || ((a, b) => {
3504
- if (stickyValues !== null) {
3505
- let sa = stickyValues.has(a[valueProp]);
3506
- let sb = stickyValues.has(b[valueProp]);
3507
- if (sa && !sb) return -1;
3508
- if (!sa && sb) return 1;
3509
- }
3510
-
3511
- const aLabel = a[labelProp] || a[multiItemLabelProp];
3512
- const bLabel = b[labelProp] || b[multiItemLabelProp];
3513
-
3514
- if (aLabel < bLabel) return -1;
3515
- if (aLabel > bLabel) return 1;
3516
-
3517
- return 0;
3518
- });
3519
-
3520
- let group = [], stickyGroup = null;
3521
- let groups = [group];
3522
- let inGroup = false;
3523
- const selectedValuesSet = new Set(p.selectedValues);
3524
- let item, i, len;
3525
-
3526
- // Split to groups
3527
- for (i = 0, len = items.length; i < len; i++) {
3528
- item = items[i];
3529
-
3530
- if ((item._group && group.length) || (inGroup && !item._group && !item._child)) {
3531
- inGroup = !!item._group;
3532
- group = [];
3533
- groups.push(group);
3534
- }
3535
-
3536
- group.push(item);
3537
- }
3538
-
3539
- // Leftover
3540
- if (!group.length) {
3541
- groups.length = 0;
3542
- }
3543
-
3544
- // Non-grouped sticky should be first
3545
- if (stickyValues && items.length > 0 && !items[0]._group) {
3546
- stickyGroup = groups[0].filter(x => stickyValues.has(x[valueProp]));
3547
- if (stickyGroup.length > 0) {
3548
- groups[0] = groups[0].filter(x => !stickyValues.has(x[valueProp]));
3549
-
3550
- if (groups[0].length === 0)
3551
- groups.shift();
3552
- } else {
3553
- stickyGroup = null;
3554
- }
3555
- }
3556
-
3557
- if (sort) {
3558
- // Sort the groups
3559
- groups.sort((a, b) => {
3560
- a = a[0];
3561
- b = b[0];
3562
-
3563
- if (stickyValues !== null) {
3564
- let sa = stickyValues.has(a[valueProp]);
3565
- let sb = stickyValues.has(b[valueProp]);
3566
- if (sa && !sb) return -1;
3567
- if (!sa && sb) return 1;
3568
- }
3569
-
3570
- // A "group" without a group item will come first
3571
- if (!a._group && b._group) return -1;
3572
- if (a._group && !b._group) return 1;
3573
-
3574
- return comparator(a, b);
3575
- });
3576
- }
3577
-
3578
- if (stickyGroup) {
3579
- groups.unshift(stickyGroup);
3580
- }
3581
-
3582
- // Now we have an array of groups, possibly sorted.
3583
- // Each group is an array that begins with the group item (group name/id).
3584
- // A group could possible start with a normal item, if it's a "default group", which had no group item.
3585
-
3586
- const checkedGroups = [], uncheckedGroups = [];
3587
-
3588
- // Iterate groups
3589
- for (let g = 0, glen = groups.length; g < glen; g++) {
3590
- group = groups[g];
3591
-
3592
- // Sort each group
3593
- group.sort((a, b) => {
3594
-
3595
- // Grouping items come first
3596
- if (a._group && !b._group) return -1;
3597
- if (!a._group && b._group) return 1;
3598
-
3599
- if (sortCheckedFirst) {
3600
- const aChecked = selectedValuesSet.has(a[valueProp]);
3601
- const bChecked = selectedValuesSet.has(b[valueProp]);
3602
-
3603
- if (aChecked && !bChecked) return -1;
3604
- if (!aChecked && bChecked) return 1;
3605
- }
3606
-
3607
- if (sort) {
3608
- return comparator(a, b);
3609
- }
3610
-
3611
- return 0;
3612
- });
3613
-
3614
- uncheckedGroups.push(group);
3615
- }
3616
-
3617
- if (sortCheckedFirst && splitCheckedGroups) {
3618
-
3619
- let virtualGroup;
3620
-
3621
- // Iterate groups
3622
- for (let g = 0, glen = groups.length; g < glen; g++) {
3623
- group = groups[g];
3624
-
3625
- if (group === stickyGroup) {
3626
- checkedGroups.push(stickyGroup);
3627
- let sgi = uncheckedGroups.indexOf(stickyGroup);
3628
- if (sgi !== -1) {
3629
- uncheckedGroups.splice(sgi, 1);
3630
- }
3631
- continue;
3632
- }
3633
-
3634
- virtualGroup = null;
3635
-
3636
- for (let gi = 0, gilen = group.length; gi < gilen; gi++) {
3637
- item = group[gi];
3638
- if (item._group) continue;
3639
- if (!selectedValuesSet.has(item[p.valueProp])) break;
3640
-
3641
- if (!virtualGroup) {
3642
- virtualGroup = [];
3643
- if (group[0]._group) {
3644
- virtualGroup.push(group[0]);
3645
- }
3646
- }
3647
-
3648
- virtualGroup.push(item);
3649
- group.splice(gi--, 1);
3650
- gilen--;
3651
- }
3652
-
3653
- if (virtualGroup) {
3654
- checkedGroups.push(virtualGroup);
3655
- if (group.length === 0 || (group.length === 1 && group[0]._group)) {
3656
- groups.splice(g--, 1);
3657
- glen--;
3658
-
3659
- let sgi = uncheckedGroups.indexOf(group);
3660
- if (sgi !== -1) {
3661
- uncheckedGroups.splice(sgi, 1);
3662
- }
3663
- }
3664
- }
3665
- }
3666
- }
3667
-
3668
- // Prepare the target array
3669
- const joined = [];
3670
- joined.length = items.length;
3671
- let itemIndex = 0;
3672
-
3673
- groups = checkedGroups.length ?
3674
- checkedGroups.concat(uncheckedGroups) : // Concat both lists
3675
- uncheckedGroups; // No need for concat
3676
-
3677
- for (let g = 0, glen = groups.length; g < glen; g++) {
3678
- group = groups[g];
3679
-
3680
- for (i = 0, len = group.length; i < len; i++) {
3681
- joined[itemIndex++] = group[i];
3682
- }
3683
- }
3684
-
3685
- return joined;
3686
- }
3687
- }
3688
-
3689
- export default SelectBox;
1
+ export { SelectBox as default, SelectBoxDefaultOptions as DefaultOptions } from '../dist/lib.es6.js';