@danielgindi/selectbox 2.0.57 → 2.0.59

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/DropList.js CHANGED
@@ -1,3430 +1 @@
1
- import escapeRegex from './utils/escapeRegex';
2
- import {
3
- closestUntil,
4
- createElement,
5
- } from '@danielgindi/dom-utils/lib/Dom';
6
- import {
7
- remove,
8
- toggleClass,
9
- } from '@danielgindi/dom-utils/lib/DomCompat';
10
- import {
11
- setCssProps,
12
- getElementHeight,
13
- getElementWidth,
14
- setElementHeight,
15
- setElementWidth, getElementOffset, anchoredPosition,
16
- parseTransition,
17
- } from '@danielgindi/dom-utils/lib/Css';
18
- import DomEventsSink from '@danielgindi/dom-utils/lib/DomEventsSink';
19
- import VirtualListHelper from '@danielgindi/virtual-list-helper';
20
- import {
21
- VALUE_BACK_SPACE,
22
- VALUE_DOWN,
23
- VALUE_END,
24
- VALUE_ENTER, VALUE_ESCAPE,
25
- VALUE_HOME, VALUE_LEFT,
26
- VALUE_PAGE_DOWN,
27
- VALUE_PAGE_UP, VALUE_RIGHT,
28
- VALUE_SPACE,
29
- VALUE_UP,
30
- } from 'keycode-js';
31
- import mitt from 'mitt';
32
- import throttle from './utils/throttle';
33
-
34
- const ItemSymbol = Symbol('item');
35
- const DestroyedSymbol = Symbol('destroyed');
36
- const GhostSymbol = Symbol('ghost');
37
- const NoResultsItemSymbol = Symbol('no_results_items');
38
-
39
- const hasOwnProperty = Object.prototype.hasOwnProperty;
40
-
41
- /**
42
- * @typedef {Object} DropList.Options
43
- * @property {Element} [el] An element to attach to, instead of creating a new one
44
- * @property {string} [baseClassName='droplist'] class name for the menu root element
45
- * @property {string|string[]} [additionalClasses]
46
- * @property {'ltr'|'rtl'|'auto'} [direction='auto']
47
- * @property {boolean} [autoItemBlur=true] Should we automatically blur the focused item when the droplist loses focus?
48
- * @property {number} [autoItemBlurDelay=300] How long to wait before deciding to blur the focused item (when the droplist loses focus)?
49
- * @property {boolean} [capturesFocus=true] Should this DropList be added to the TAB-key stack?
50
- * @property {boolean} [multi=false] Does this DropList show checkboxes for multiple item selection?
51
- * @property {*} [singleSelectedValue] Current selected value when using single selection.
52
- * @property {function} [keyDownHandler=null] An alternative "keydown" event handler. Return true to prevent default behaviour.
53
- * @property {boolean} [autoCheckGroupChildren=true] When a group is checked/unchecked - all items beneath it will update accordingly
54
- * @property {boolean} [useExactTargetWidth=false] Use the exact target's width, do not allow growing
55
- * @property {boolean} [constrainToWindow=true] Should the position be constrained to the window, attaching to window's borders if needed?
56
- * @property {Boolean} [autoFlipDirection=true] Should the position/anchor be flipped automatically when there's no space in the required direction?
57
- * @property {number} [estimatedItemHeight=20] An estimated row height, for approximating scroll height.
58
- * @property {boolean} [estimateWidth=false] Use an estimation for the width instead of measuring. May be faster - needs testing and may depend on the CSS.
59
- * @property {number} [virtualMinItems=100] Turns into a virtual list - with items being created and showing up on viewport only. The value specified the minimum item count where a virtual list will be created.
60
- * @property {string} [labelProp='label']
61
- * @property {string} [valueProp='value']
62
- * @property {function(item: DropList.ItemBase, itemEl: Element):(*|false)} [renderItem] Function to call when rendering an item element
63
- * @property {function(item: DropList.ItemBase, itemEl: Element)} [unrenderItem] Function to call when rendering an item element
64
- * @property {function(item: DropList.ItemBase, itemEl: Element):(*|false)} [renderNoResultsItem]
65
- * @property {function(item: DropList.ItemBase, itemEl: Element)} [unrenderNoResultsItem]
66
- * @property {function(name: string, data: *)} [on]
67
- * @property {boolean} [isHeaderVisible=false] show header element
68
- * @property {boolean} [isFooterVisible=false] show footer element
69
- * @property {boolean} [searchable=false] include inline search box
70
- * @property {string} [searchPlaceholder=''] placeholder text for the inline search box
71
- * @property {string} [noResultsText='No matching results'] text for no results (empty for none)
72
- * @property {number} [filterThrottleWindow=300] throttle time (milliseconds) for filtering
73
- * @property {boolean} [filterOnEmptyTerm=false] call the filter function on empty search term too
74
- * @property {boolean} [filterGroups=false] should groups be filtered?
75
- * @property {boolean} [filterEmptyGroups=false] should empty groups be filtered out?
76
- * @property {function(items: DropList.ItemBase[], term: string):(DropList.ItemBase[]|null)} [filterFn]
77
- * @property {function(dropList: DropList):DropList.PositionOptions} [positionOptionsProvider]
78
- * */
79
- /** */
80
-
81
- /**
82
- * @typedef {Object} DropList.PositionAnchor
83
- * @property {'left'|'center'|'right'|'start'|'end'|string|number} x - horizontal anchor specification (could be either `'left'|'center'|'right'|'start'|'end'` or a percentage `'50%'` or a fixed decimal `Number`)
84
- * @property {'top'|'center'|'bottom'|string|number} y - vertical anchor specification (could be either `'top'|'center'|'bottom'` or a percentage `'50%'` or a fixed decimal `Number`)
85
- * */
86
- /** */
87
-
88
- /**
89
- * @typedef {Object} DropList.PositionOptions
90
- * @property {Element?} [target] Target element to act as anchor
91
- * @property {{left: number, top: number}?} [targetOffset] Override the offset of target. Automatically calculated if unspecified.
92
- * @property {number?} [targetHeight] Override height of the target
93
- * @property {number?} [targetWidth] Override width of the target
94
- * @property {DropList.PositionAnchor?} [position]
95
- * @property {DropList.PositionAnchor?} [anchor]
96
- * @property {boolean|number?} [updateWidth=false] `true` to set width of the menu according to `target`'s width, or specify an arbitrary number.
97
- * @property {string?} [targetRtl] Override for rtl mode of the target
98
- * @property {{x: number, y: number}} [offset=undefined] Extra rtl-aware offset to the target
99
- * */
100
- /** */
101
-
102
- /**
103
- * @typedef {Object} DropList.ItemBase
104
- * @property {string} [value]
105
- * @property {string} [label]
106
- * @property {boolean} [_group=false]
107
- * @property {boolean} [_child=false]
108
- * @property {boolean} [_nocheck=false]
109
- * @property {boolean} [_nointeraction=false]
110
- * @property {DropList.ItemBase[]} [_subitems]
111
- * */
112
-
113
- /**
114
- * @typedef {DropList.ItemBase} DropList.Item
115
- * @property {boolean} [_checked=false]
116
- * */
117
- /** */
118
-
119
- /** @type {DropList.Options} */
120
- export const DefaultOptions = {
121
- baseClassName: 'droplist',
122
-
123
- autoItemBlur: true,
124
- autoItemBlurDelay: 300,
125
- capturesFocus: true,
126
- multi: false,
127
- singleSelectedValue: undefined,
128
- keyDownHandler: null,
129
- autoCheckGroupChildren: true,
130
- useExactTargetWidth: false,
131
-
132
- constrainToWindow: true,
133
- autoFlipDirection: true,
134
-
135
- estimateWidth: false,
136
- virtualMinItems: 100,
137
-
138
- labelProp: 'label',
139
- valueProp: 'value',
140
-
141
- on: null,
142
-
143
- isHeaderVisible: false,
144
- isFooterVisible: false,
145
- searchable: false,
146
- searchPlaceholder: '',
147
- noResultsText: 'No matching results',
148
- filterThrottleWindow: 300,
149
- filterOnEmptyTerm: false,
150
- filterGroups: false,
151
- filterEmptyGroups: false,
152
- };
153
-
154
- /*
155
- Emits the following events:
156
- ---------------------------
157
-
158
- 'itemfocus' {value, item, event?, el}: item gained focus.
159
- 'itemblur' {value, item}: item lost focus.
160
- 'select' {value, item, event?, el}: item was selected (in single mode).
161
- 'show:before': the drop list will show.
162
- 'show': the drop list has been shown.
163
- 'hide:before': the drop list will hide.
164
- 'hide': the drop list was hidden.
165
- 'hide:after': emitted after the hide css transition has ended, or immediately after 'hide'.
166
- 'check' {value, item, checked: boolean, isGroup: boolean, isCheckingGroup: boolean}: item was selected (in multi mode).
167
- 'groupcheck' {value, item, affectedCount: number}: item was selected (in multi mode).
168
- 'blur' {event}: element lost focus
169
- 'show_subitems {value, item, el, droplist: DropList}': subitems dropdown will show.
170
- 'hide_subitems {value, item, el, droplist: DropList}': subitems dropdown did hide.
171
- 'subitems:select' {value, item, event?, el}: item was selected (in single mode).
172
- 'subitems:blur' {event}: subitems element lost focus
173
- */
174
-
175
- // noinspection JSUnusedGlobalSymbols
176
- class DropList {
177
-
178
- /**
179
- * @param {DropList.Options} options
180
- */
181
- constructor(options) {
182
- const o = { ...DefaultOptions };
183
-
184
- for (let [key, value] of Object.entries(/**@type Object*/options))
185
- if (value !== undefined)
186
- o[key] = value;
187
-
188
- const p = this._p = {
189
- ownsEl: true,
190
- elOriginalDisplay: '',
191
-
192
- baseClassName: o.baseClassName,
193
- additionalClasses: o.additionalClasses,
194
- direction: o.direction === 'ltr' ? 'ltr' : o.direction === 'rtl' ? 'rtl' : 'auto',
195
-
196
- autoItemBlur: o.autoItemBlur,
197
- autoItemBlurDelay: o.autoItemBlurDelay,
198
- capturesFocus: o.capturesFocus,
199
- multi: o.multi,
200
- singleSelectedValue: o.singleSelectedValue,
201
- keyDownHandler: o.keyDownHandler,
202
- autoCheckGroupChildren: o.autoCheckGroupChildren,
203
- useExactTargetWidth: o.useExactTargetWidth,
204
- constrainToWindow: o.constrainToWindow,
205
- autoFlipDirection: o.autoFlipDirection,
206
- estimatedItemHeight: o.estimatedItemHeight,
207
- estimateWidth: o.estimateWidth,
208
- virtualMinItems: o.virtualMinItems,
209
- labelProp: o.labelProp,
210
- valueProp: o.valueProp,
211
- renderItem: o.renderItem,
212
- unrenderItem: o.unrenderItem,
213
- renderNoResultsItem: o.renderNoResultsItem,
214
- unrenderNoResultsItem: o.unrenderNoResultsItem,
215
- on: o.on || null,
216
- positionOptionsProvider: o.positionOptionsProvider ?? null,
217
-
218
- searchable: o.searchable,
219
- searchPlaceholder: o.searchPlaceholder,
220
- isHeaderVisible: o.isHeaderVisible,
221
- isFooterVisible: o.isFooterVisible,
222
-
223
- silenceEvents: true,
224
- mitt: mitt(),
225
-
226
- filterThrottleWindow: o.filterThrottleWindow,
227
- filterOnEmptyTerm: o.filterOnEmptyTerm,
228
- filterGroups: o.filterGroups,
229
- filterEmptyGroups: o.filterEmptyGroups,
230
- filterFn: o.filterFn,
231
- filteredItems: null,
232
- filterTerm: '',
233
- needsRefilter: false,
234
- throttledRefilterItems: null,
235
-
236
- focusItemIndex: -1,
237
- focusItemEl: null,
238
-
239
- sink: new DomEventsSink(),
240
- };
241
-
242
- const baseClass = p.baseClassName + '_wrapper';
243
-
244
- let classes = [baseClass];
245
-
246
- if (p.additionalClasses) {
247
- classes = classes.concat((p.additionalClasses + '').split(' ').filter(x => x));
248
- }
249
-
250
- const initialCss = {
251
- // make initial position not interfere with layout so it can be correctly calculated
252
- top: '-9999px',
253
- };
254
-
255
- let wrapperEl = o.el;
256
-
257
- if (wrapperEl instanceof Element) {
258
- p.elOriginalDisplay = wrapperEl.style.display || '';
259
- wrapperEl.classList.add(...classes);
260
- setCssProps(/**@type ElementCSSInlineStyle*/wrapperEl, initialCss);
261
- p.ownsEl = false;
262
- } else {
263
- wrapperEl = createElement('div', {
264
- class: classes.join(' '),
265
- css: initialCss,
266
- });
267
- }
268
-
269
- p.el = wrapperEl;
270
-
271
- let menuEl = createElement('ul');
272
- menuEl.role = 'menu';
273
- p.menuEl = menuEl;
274
-
275
- p.headerEl = createElement('div', {
276
- class: p.baseClassName + '_header',
277
- });
278
-
279
- p.footerEl = createElement('div', {
280
- class: p.baseClassName + '_footer',
281
- });
282
-
283
- if (o.searchable) {
284
- this.setSearchable(true);
285
- }
286
-
287
- if (o.isHeaderVisible)
288
- this.setHeaderVisible(o.isHeaderVisible);
289
-
290
- wrapperEl.appendChild(menuEl);
291
-
292
- if (o.isFooterVisible)
293
- this.setFooterVisible(o.isFooterVisible);
294
-
295
- p.items = [];
296
- p.groupCount = 0; // This will keep state of how many `group` items we have
297
- p.mouseHandled = false;
298
-
299
- p.virtualListHelper = new VirtualListHelper({
300
- list: p.menuEl,
301
- virtual: true,
302
- buffer: 5,
303
- estimatedItemHeight: o.estimatedItemHeight || 20,
304
- itemElementCreatorFn: () => {
305
- return createElement('li',
306
- {
307
- role: 'menuitem',
308
- tabIndex: p.capturesFocus ? -1 : null,
309
- },
310
- );
311
- },
312
- onItemRender: (itemEl, index) => {
313
- let item;
314
-
315
- if ((/**@type any*/index) === GhostSymbol) {
316
- item = {
317
- label: p.lastMeasureLongestLabelText,
318
- value: 'Measure',
319
-
320
- [ItemSymbol]: {
321
- [p.labelProp]: p.lastMeasureLongestLabelText,
322
- [p.valueProp]: 'Measure',
323
- },
324
- };
325
- itemEl.setAttribute('aria-hidden', 'true');
326
- } else {
327
- const items = p.filteredItems ?? p.items;
328
- if (items.length === 0 && p.noResultsText) {
329
- item = {
330
- value: NoResultsItemSymbol,
331
- label: p.noResultsText,
332
- _nointeraction: true,
333
- _nocheck: true,
334
-
335
- [ItemSymbol]: NoResultsItemSymbol,
336
- };
337
- } else {
338
- item = items[index];
339
- }
340
- }
341
-
342
- if (!item) {
343
- // eslint-disable-next-line no-console
344
- console.warn('onItemRender called for (' + index + ') which has no item');
345
- }
346
-
347
- itemEl.className = `${p.baseClassName}__item`;
348
-
349
- const classList = itemEl.classList;
350
-
351
- if (item) {
352
- if (p.multi) {
353
- if (item._nocheck) {
354
- classList.add(`${p.baseClassName}__item_multi_nocheck`);
355
- } else {
356
- classList.add(`${p.baseClassName}__item_multi`);
357
-
358
- if (item._checked) {
359
- classList.add(`${p.baseClassName}__item_checked`);
360
- }
361
- }
362
- } else {
363
- classList.add(`${p.baseClassName}__item_single`);
364
-
365
- if (p.singleSelectedValue !== undefined && item.value === p.singleSelectedValue) {
366
- classList.add(`${p.baseClassName}__item_selected`);
367
- p.singleSelectedItemEl = itemEl;
368
- } else if (p.singleSelectedItemEl === itemEl) {
369
- p.singleSelectedItemEl = null;
370
- }
371
- }
372
-
373
- if (item._group)
374
- classList.add(`${p.baseClassName}__item_group`);
375
-
376
- if (item._child)
377
- classList.add(`${p.baseClassName}__item_child`);
378
-
379
- if (item._nointeraction)
380
- classList.add(`${p.baseClassName}__item_nointeraction`);
381
- }
382
-
383
- if (p.focusItemIndex === index) {
384
- p.focusItemEl = itemEl;
385
- classList.add(`${p.baseClassName}__item_focus`);
386
- }
387
-
388
- this._renderItemContent(item, itemEl);
389
-
390
- itemEl[ItemSymbol] = item;
391
- },
392
- });
393
-
394
- this._setupUnrenderFunction();
395
-
396
- if (p.capturesFocus) {
397
- wrapperEl.tabIndex = 0;
398
- }
399
-
400
- this.setFilterThrottleWindow(o.filterThrottleWindow);
401
- this.setNoResultsText(o.noResultsText);
402
-
403
- this._hookMouseEvents();
404
- this._hookTouchEvents();
405
- this._hookFocusEvents();
406
- this._hookKeyEvents();
407
- this._hookSearchEvents();
408
-
409
- this.silenceEvents = false;
410
- }
411
-
412
- destroy() {
413
- if (this[DestroyedSymbol])
414
- return;
415
- this[DestroyedSymbol] = true;
416
-
417
- const p = this._p;
418
-
419
- clearTimeout(p.blurTimer);
420
- clearTimeout(p.filterTimer);
421
-
422
- p.sink.remove();
423
- p.virtualListHelper.destroy();
424
-
425
- if (p.el?.parentNode) {
426
- remove(p.el);
427
- }
428
-
429
- if (p.currentSubDropList) {
430
- p.currentSubDropList?.droplist?.destroy();
431
- p.currentSubDropList = null;
432
- }
433
-
434
- if (p.throttledRefilterItems)
435
- p.throttledRefilterItems.cancel();
436
-
437
- if (!p.ownsEl) {
438
- for (let name of Array.from(p.el.classList)) {
439
- if (name.startsWith(p.baseClassName)) {
440
- p.el.classList.remove(name);
441
- }
442
- }
443
- for (let key of ['position', 'left', 'top', 'right', 'bottom', 'z-index']) {
444
- p.el.style[key] = '';
445
- }
446
- p.el.style.display = p.elOriginalDisplay;
447
- }
448
-
449
- if (p.lastPositionTarget) {
450
- p.lastPositionTarget.classList.remove(
451
- `has_${p.baseClassName}`,
452
- `has_${p.baseClassName}_above`,
453
- `has_${p.baseClassName}_below`);
454
- delete p.lastPositionTarget;
455
- }
456
-
457
- delete p.lastPositionOptions;
458
-
459
- this._p = null;
460
- }
461
-
462
- get el() {
463
- return this._p?.el ?? null;
464
- }
465
-
466
- /**
467
- * Returns true if other is an inclusive descendant of node, and false otherwise.
468
- * @param {Node} other
469
- * @param {boolean} [considerSubmenus=true]
470
- * @returns {boolean}
471
- */
472
- elContains(other, considerSubmenus = true) {
473
- if (this.el.contains(other))
474
- return true;
475
-
476
- if (considerSubmenus && this._p.currentSubDropList?.droplist?.elContains(other))
477
- return true;
478
-
479
- return false;
480
- }
481
-
482
- /**
483
- * @param {string|string[]} classes
484
- * @returns {DropList}
485
- */
486
- setAdditionalClasses(classes) {
487
- const p = this._p;
488
- p.additionalClasses = classes;
489
- this._syncBaseClasses();
490
- return this;
491
- }
492
-
493
- /**
494
- * Sets the appropriate direction for the droplist
495
- * @param {'ltr'|'rtl'|'auto'} direction
496
- * @return {DropList}
497
- */
498
- setDirection(direction) {
499
- const p = this._p;
500
- p.direction = direction === 'ltr' ? 'ltr' : direction === 'rtl' ? 'rtl' : 'auto';
501
- this._syncBaseClasses();
502
- return this;
503
- }
504
-
505
- /**
506
- * Gets the supplied direction for the droplist
507
- * @return {'ltr'|'rtl'|'auto'}
508
- */
509
- getDirection() {
510
- const p = this._p;
511
- return p.direction;
512
- }
513
-
514
- /**
515
- * @param {string} prop
516
- * @returns {DropList}
517
- */
518
- setLabelProp(prop) {
519
- const p = this._p;
520
- p.labelProp = prop;
521
- return this;
522
- }
523
-
524
- /**
525
- *
526
- * @property {function(item: DropList.ItemBase, itemEl: Element):(*|false)} [fn] Function to call when rendering an item element
527
- * @returns {DropList}
528
- */
529
- setRenderItem(fn) {
530
- const p = this._p;
531
- p.renderItem = fn;
532
- return this;
533
- }
534
-
535
- /**
536
- *
537
- * @property {function(item: DropList.ItemBase, itemEl: Element)} [fn] Function to call when rendering an item element
538
- * @returns {DropList}
539
- */
540
- setUnrenderItem(fn) {
541
- const p = this._p;
542
- p.unrenderItem = fn;
543
- this._setupUnrenderFunction();
544
- return this;
545
- }
546
-
547
- /**
548
- * @param {(function(item: DropList.ItemBase, itemEl: Element):(*|false))|null} render
549
- * @param {(function(item: DropList.ItemBase, itemEl: Element))|null} unrender
550
- * @returns {DropList}
551
- */
552
- setRenderNoResultsItem(render, unrender) {
553
- const p = this._p;
554
- p.renderNoResultsItem = render;
555
- p.unrenderNoResultsItem = unrender;
556
- this._setupUnrenderFunction();
557
- return this;
558
- }
559
-
560
- /**
561
- * @private
562
- */
563
- _setupUnrenderFunction() {
564
- const p = this._p;
565
-
566
- if (typeof p.unrenderItem === 'function' || typeof p.unrenderNoResultsItem === 'function') {
567
- const fn = p.unrenderItem;
568
- const fnNoResults = p.unrenderNoResultsItem;
569
- p.virtualListHelper.setOnItemUnrender(el => {
570
- const item = el[ItemSymbol];
571
- if (item === NoResultsItemSymbol) {
572
- try {
573
- fnNoResults(item, el);
574
- } catch (err) {
575
- console.error(err); // eslint-disable-line no-console
576
- }
577
- } else {
578
- try {
579
- fn(item[ItemSymbol], el);
580
- } catch (err) {
581
- console.error(err); // eslint-disable-line no-console
582
- }
583
- }
584
- delete el[ItemSymbol];
585
-
586
- if (p.focusItemEl === el)
587
- p.focusItemEl = null;
588
- });
589
- } else {
590
- p.virtualListHelper.setOnItemUnrender(el => {
591
- delete el[ItemSymbol];
592
-
593
- if (p.focusItemEl === el)
594
- p.focusItemEl = null;
595
- });
596
- }
597
-
598
- return this;
599
- }
600
-
601
- /**
602
- * @param {string} prop
603
- * @returns {DropList}
604
- */
605
- setValueProp(prop) {
606
- const p = this._p;
607
- p.valueProp = prop;
608
- return this;
609
- }
610
-
611
- _syncBaseClasses() {
612
- const p = this._p, el = p.el;
613
-
614
- if (!el)
615
- return;
616
-
617
- const baseClass = p.baseClassName + '_wrapper';
618
- let classes = [baseClass];
619
-
620
- if (p.direction === 'ltr' || p.direction === 'rtl')
621
- classes.push(`${p.baseClassName}__` + p.direction);
622
-
623
- if (p.additionalClasses) {
624
- classes = classes.concat(p.additionalClasses);
625
- }
626
-
627
- el.className = classes.join(' ');
628
- }
629
-
630
- blurFocusedItem() {
631
- const p = this._p;
632
-
633
- clearTimeout(p.blurTimer);
634
-
635
- if (!this.hasFocusedItem()) {
636
- return;
637
- }
638
-
639
- let focusItemEl = p.focusItemEl;
640
- if (focusItemEl) {
641
- focusItemEl.classList.remove(`${p.baseClassName}__item_focus`);
642
- p.focusItemEl = null;
643
- }
644
-
645
- const items = p.filteredItems ?? p.items;
646
- const item = items[p.focusItemIndex];
647
- p.focusItemIndex = -1;
648
-
649
- if (!item) {
650
- return;
651
- }
652
-
653
- if (p.currentSubDropList) {
654
- this._hideSublist();
655
- }
656
-
657
- this._trigger('itemblur', { value: item.value, item: item[ItemSymbol] ?? item });
658
- }
659
-
660
- nextPage(event) {
661
- this._move('next_page', event);
662
- }
663
-
664
- previousPage(event) {
665
- this._move('prev_page', event);
666
- }
667
-
668
- goToFirst(event) {
669
- this._move('first', event);
670
- }
671
-
672
- goToLast(event) {
673
- this._move('last', event);
674
- }
675
-
676
- toggleFocusedItem() {
677
- const p = this._p;
678
-
679
- if (this.hasFocusedItem() && p.multi) {
680
- const items = p.filteredItems ?? p.items;
681
- let item = items[p.focusItemIndex];
682
- if (!item || item._nocheck || item._nointeraction) return this;
683
-
684
- item._checked = !item._checked;
685
- if (p.focusItemEl) {
686
- toggleClass(p.focusItemEl, `${p.baseClassName}__item_checked`, item._checked);
687
- }
688
- this._trigger('check', {
689
- value: item.value,
690
- item: item[ItemSymbol] ?? item,
691
- checked: item._checked,
692
- isGroup: item._group,
693
- isCheckingGroup: false,
694
- });
695
-
696
- this._updateGroupStateForItem(item);
697
- }
698
-
699
- return this;
700
- }
701
-
702
- triggerItemSelection(item, event) {
703
- const p = this._p;
704
-
705
- p.focusItemEl = p.focusItemEl || closestUntil(event.target, 'li', p.el);
706
- p.focusItemIndex = p.virtualListHelper.getItemIndexFromElement(p.focusItemEl);
707
- if (p.focusItemIndex === undefined)
708
- p.focusItemIndex = -1;
709
-
710
- item = item ?? p.focusItemEl[ItemSymbol];
711
- if (item._nointeraction) {
712
- return false;
713
- }
714
-
715
- if (item._subitems?.length) {
716
- this._showSublist(item, p.focusItemEl);
717
- return false;
718
- }
719
-
720
- if (p.multi) {
721
- if (this.hasFocusedItem()) {
722
- this.toggleFocusedItem();
723
- }
724
- } else {
725
- this._setSingleSelectedItemEl(p.focusItemEl, item ? item.value : undefined);
726
-
727
- this._trigger('select', {
728
- value: item ? item.value : undefined,
729
- item: item[ItemSymbol] ?? item,
730
- event: event,
731
- el: p.focusItemEl,
732
- });
733
- }
734
-
735
- return true;
736
- }
737
-
738
- /**
739
- *
740
- * @param {DropList.Item} item The item to add. It is copied.
741
- * @param {number} [atIndex=-1] The index to insert at (or -1)
742
- * @returns {DropList}
743
- */
744
- addItem(item, atIndex = -1) {
745
- return this.addItems([item], atIndex);
746
- }
747
-
748
- /**
749
- * Adds items to the menu and renders
750
- * @param {DropList.Item[]} itemsToAdd The items to add. These are copied.
751
- * @param {number} [atIndex=-1] The index to insert at (or -1)
752
- * @returns {DropList}
753
- */
754
- addItems(itemsToAdd, atIndex = -1) {
755
- const p = this._p, labelProp = p.labelProp, valueProp = p.valueProp;
756
-
757
- let isMulti = p.multi;
758
- const items = p.items;
759
-
760
- if (atIndex == null || atIndex < 0 || atIndex >= p.items.length) {
761
- atIndex = -1;
762
- }
763
-
764
- // Determine if the list is virtual or not
765
- this._determineVirtualMode(items.length + itemsToAdd.length);
766
-
767
- for (let i = 0, count = itemsToAdd.length; i < count; i++) {
768
- let oitem = itemsToAdd[i];
769
- //noinspection PointlessBooleanExpressionJS
770
- let item = {
771
- [ItemSymbol]: oitem,
772
- label: oitem[labelProp],
773
- value: oitem[valueProp],
774
- _nocheck: !!oitem._nocheck,
775
- _nointeraction: !!oitem._nointeraction,
776
- _subitems: oitem._subitems,
777
- };
778
-
779
- if (isMulti) {
780
- item._checked = !!oitem._checked;
781
- }
782
-
783
- if (oitem._group) {
784
- item._group = true;
785
- p.groupCount++;
786
- }
787
-
788
- if (typeof oitem._level === 'number') {
789
- item._level = oitem._level;
790
- }
791
-
792
- if (oitem._child) {
793
- // This is used for setting a child class,
794
- // But can be used to determine that current item is not part of above group,
795
- // mainly where the groups are oddly sorted.
796
- item._child = true;
797
- }
798
-
799
- // Add the item to the list of them
800
- if (atIndex !== -1) {
801
- items.splice(atIndex, 0, item);
802
- } else {
803
- items.push(item);
804
- }
805
-
806
- if (atIndex !== -1) {
807
- atIndex++;
808
- }
809
- }
810
-
811
- if (!p.filteredItems) {
812
- let hadNoResultItem = p.hasNoResultsItem;
813
- p.hasNoResultsItem = p.items.length === 0 && !!p.noResultsText;
814
- if (p.hasNoResultsItem) {
815
- p.virtualListHelper
816
- .setCount(1)
817
- .render();
818
- } else {
819
- if (hadNoResultItem)
820
- p.virtualListHelper.removeItemsAt(1, 0);
821
-
822
- p.virtualListHelper
823
- .addItemsAt(itemsToAdd.length, atIndex === -1 ? atIndex : (atIndex - itemsToAdd.length))
824
- .render();
825
- }
826
- } else {
827
- p.needsRefilter = true;
828
- }
829
-
830
- return this;
831
- }
832
-
833
- /**
834
- * Replaces all current items with the supplied items
835
- * @param {DropList.Item[]} items The items to set. These are copied.
836
- * @returns {DropList}
837
- */
838
- setItems(items) {
839
- const p = this._p;
840
-
841
- p.items.length = 0;
842
- p.filteredItems = null;
843
- p.groupCount = 0;
844
-
845
- p.hasNoResultsItem = !!p.noResultsText;
846
- p.virtualListHelper.setCount(p.hasNoResultsItem ? 1 : 0);
847
-
848
- this.addItems(items);
849
- this.updateSublist();
850
-
851
- return this;
852
- }
853
-
854
- updateItemByValue(value, newItem) {
855
- const p = this._p;
856
-
857
- // Look for the proper item
858
- let itemIndex = this.itemIndexByValue(value);
859
- if (itemIndex === -1) return this;
860
-
861
- let item = this.itemAtIndex(itemIndex);
862
- item[ItemSymbol] = newItem;
863
-
864
- if (hasOwnProperty.call(newItem, p.labelProp))
865
- item.label = newItem[p.labelProp];
866
-
867
- if (hasOwnProperty.call(newItem, p.valueProp))
868
- item.value = newItem[p.valueProp];
869
-
870
- if (hasOwnProperty.call(newItem, '_nocheck'))
871
- item._nocheck = !!newItem._nocheck;
872
-
873
- if (hasOwnProperty.call(newItem, '_nointeraction'))
874
- item._nointeraction = !!newItem._nointeraction;
875
-
876
- if (hasOwnProperty.call(newItem, '_subitems'))
877
- item._subitems = !!newItem._subitems;
878
-
879
- if (p.multi) {
880
- if (hasOwnProperty.call(newItem, '_checked'))
881
- item._checked = !!newItem._checked;
882
- }
883
-
884
- if (hasOwnProperty.call(newItem, '_group')) {
885
- if (!!newItem._group !== item._group) {
886
- if (item._group)
887
- p.groupCount--;
888
- else p.groupCount++;
889
-
890
- newItem._group = !!item._group;
891
- }
892
- }
893
-
894
- if (hasOwnProperty.call(newItem, '_level')) {
895
- newItem._level = item._level;
896
- }
897
-
898
- if (hasOwnProperty.call(newItem, '_child'))
899
- item._child = !!newItem._child;
900
-
901
- let virtualItemIndex = itemIndex;
902
- if (p.filteredItems) {
903
- virtualItemIndex = p.filteredItems.indexOf(item);
904
- if (virtualItemIndex !== -1) {
905
- p.filteredItems.splice(virtualItemIndex, 1);
906
- }
907
- }
908
-
909
- if (virtualItemIndex !== -1 &&
910
- p.virtualListHelper.isItemRendered(virtualItemIndex)) {
911
- p.virtualListHelper
912
- .refreshItemAt(virtualItemIndex)
913
- .render();
914
- }
915
-
916
- return this;
917
- }
918
-
919
- removeItem(value, label) {
920
- const p = this._p;
921
-
922
- // Look for the proper item
923
- let itemIndex = this.itemIndexByValueOrLabel(value, label);
924
- if (itemIndex === -1) return this;
925
-
926
- let spliced = p.items.splice(itemIndex, 1);
927
- if (spliced[0]._group) {
928
- p.groupCount--;
929
- }
930
-
931
- let virtualItemIndex = itemIndex;
932
- if (p.filteredItems) {
933
- virtualItemIndex = p.filteredItems.indexOf(spliced[0]);
934
- if (virtualItemIndex !== -1) {
935
- p.filteredItems.splice(virtualItemIndex, 1);
936
- }
937
- }
938
-
939
- if (virtualItemIndex !== -1) {
940
- p.hasNoResultsItem = (p.filteredItems ?? p.items).length === 0 && !!p.noResultsText;
941
-
942
- if (p.hasNoResultsItem) {
943
- p.virtualListHelper
944
- .setCount(1)
945
- .render();
946
- } else {
947
- p.virtualListHelper
948
- .removeItemsAt(virtualItemIndex, 1)
949
- .render();
950
- }
951
- }
952
-
953
- return this;
954
- }
955
-
956
- removeAllItems() {
957
- const p = this._p;
958
-
959
- p.items.length = 0;
960
- p.filteredItems = null;
961
- p.groupCount = 0;
962
-
963
- p.hasNoResultsItem = !!p.noResultsText;
964
-
965
- p.virtualListHelper
966
- .setCount(p.hasNoResultsItem ? 1 : 0)
967
- .render();
968
-
969
- return this;
970
- }
971
-
972
- /**
973
- * Should only be used if the items array has been manually manipulated.
974
- * @return {DropList}
975
- */
976
- invalidate() {
977
- const p = this._p;
978
-
979
- p.virtualListHelper
980
- .invalidate()
981
- .render();
982
-
983
- return this;
984
- }
985
-
986
- itemDataByValue(value) {
987
- const p = this._p;
988
-
989
- for (let i = 0, count = p.items.length; i < count; i++) {
990
- let item = p.items[i];
991
- if (item.value === value) {
992
- return item[ItemSymbol];
993
- }
994
- }
995
-
996
- return null;
997
- }
998
-
999
- itemIndexByValue(value) {
1000
- const p = this._p;
1001
-
1002
- const items = p.items;
1003
- for (let i = 0, count = items.length; i < count; i++) {
1004
- let item = items[i];
1005
- if (item.value === value) {
1006
- return i;
1007
- }
1008
- }
1009
-
1010
- return -1;
1011
- }
1012
-
1013
- filteredItemIndexByValue(value) {
1014
- const p = this._p;
1015
-
1016
- const items = p.filteredItems ?? p.items;
1017
- for (let i = 0, count = items.length; i < count; i++) {
1018
- let item = items[i];
1019
- if (item.value === value) {
1020
- return i;
1021
- }
1022
- }
1023
-
1024
- return -1;
1025
- }
1026
-
1027
- itemIndexByValueOrLabel(value, label) {
1028
- const p = this._p;
1029
-
1030
- const items = p.items;
1031
- for (let i = 0, count = items.length; i < count; i++) {
1032
- let item = items[i];
1033
- if (item.value === value || item.label === label) {
1034
- return i;
1035
- }
1036
- }
1037
-
1038
- return -1;
1039
- }
1040
-
1041
- filteredItemIndexByValueOrLabel(value, label) {
1042
- const p = this._p;
1043
-
1044
- const items = p.filteredItems ?? p.items;
1045
- for (let i = 0, count = items.length; i < count; i++) {
1046
- let item = items[i];
1047
- if (item.value === value || item.label === label) {
1048
- return i;
1049
- }
1050
- }
1051
-
1052
- return -1;
1053
- }
1054
-
1055
- itemIndexByItem(item) {
1056
- const p = this._p;
1057
-
1058
- const items = p.items;
1059
-
1060
- for (let i = 0, count = items.length; i < count; i++) {
1061
- let it = items[i];
1062
- if (it[ItemSymbol] === item) {
1063
- return i;
1064
- }
1065
- }
1066
-
1067
- return -1;
1068
- }
1069
-
1070
- filteredItemIndexByItem(item) {
1071
- const p = this._p;
1072
-
1073
- const items = p.filteredItems ?? p.items;
1074
-
1075
- for (let i = 0, count = items.length; i < count; i++) {
1076
- let it = items[i];
1077
- if (it[ItemSymbol] === item) {
1078
- return i;
1079
- }
1080
- }
1081
-
1082
- return -1;
1083
- }
1084
-
1085
- items() {
1086
- return this._p.items.map(x => x[ItemSymbol]);
1087
- }
1088
-
1089
- itemsReference() {
1090
- return this._p.items;
1091
- }
1092
-
1093
- itemCount() {
1094
- return this._p.items.length;
1095
- }
1096
-
1097
- itemAtIndex(index) {
1098
- return this._p.items[index]?.[ItemSymbol];
1099
- }
1100
-
1101
- filteredItemAtIndex(index) {
1102
- const p = this._p;
1103
- const items = p.filteredItems ?? p.items;
1104
- return items[index]?.[ItemSymbol];
1105
- }
1106
-
1107
- /**
1108
- * Return the item element at the given original index, if it exists.
1109
- * The item may not be currently rendered, and null will be returned
1110
- * @param index
1111
- * @returns {HTMLElement|null}
1112
- */
1113
- itemElementAtIndex(index) {
1114
- const p = this._p;
1115
- if (!p.filteredItems)
1116
- return this.filteredElementItemAtIndex(index);
1117
-
1118
- index = p.filteredItems.indexOf(this._p.items[index]);
1119
-
1120
- const li = p.virtualListHelper.getItemElementAt(index);
1121
- return li ?? null;
1122
- }
1123
-
1124
- /**
1125
- * Return the item element at the given index, if it exists.
1126
- * The item may not be currently rendered, and null will be returned
1127
- * @param index
1128
- * @returns {HTMLElement|null}
1129
- */
1130
- filteredElementItemAtIndex(index) {
1131
- const p = this._p;
1132
- const li = p.virtualListHelper.getItemElementAt(index);
1133
- return li ?? null;
1134
- }
1135
-
1136
- /**
1137
- * @param {function(dropList: DropList):DropList.PositionOptions} fn
1138
- * @returns {DropList}
1139
- */
1140
- setPositionOptionsProvider(fn) {
1141
- const p = this._p;
1142
- if (p.positionOptionsProvider === fn)
1143
- return this;
1144
- p.positionOptionsProvider = fn ?? null;
1145
- this.relayout();
1146
- return this;
1147
- }
1148
-
1149
- /**
1150
- * @returns {function(dropList: DropList):DropList.PositionOptions|null}
1151
- */
1152
- getPositionOptionsProvider() {
1153
- const p = this._p;
1154
- return p.positionOptionsProvider;
1155
- }
1156
-
1157
- /**
1158
- * @param {string} term
1159
- * @param {boolean} [performSearch=false] should actually perform the search, or just set the input's text?
1160
- * @returns {DropList}
1161
- */
1162
- setSearchTerm(term, performSearch = false) {
1163
- const p = this._p;
1164
-
1165
- if (p.searchInput) {
1166
- p.searchInput.value = term;
1167
- }
1168
-
1169
- if (performSearch) {
1170
- p.filterTerm = term.trim();
1171
- p.filteredItems = null;
1172
-
1173
- this._trigger('search', { value: term });
1174
- p.throttledRefilterItems();
1175
- }
1176
-
1177
- return this;
1178
- }
1179
-
1180
- isFilterPending() {
1181
- const p = this._p;
1182
-
1183
- return !!(p.throttledRefilterItems.isScheduled() ||
1184
- (!p.filteredItems && (p.filterTerm || (p.filterOnEmptyTerm && p.filterFn))));
1185
- }
1186
-
1187
- /** @private */
1188
- _refilterItems() {
1189
- const p = this._p;
1190
-
1191
- const term = p.filterTerm;
1192
- const filterGroups = p.filterGroups;
1193
- const filterEmptyGroups = p.filterEmptyGroups;
1194
-
1195
- if (term || (p.filterOnEmptyTerm && p.filterFn)) {
1196
- let fn = p.filterFn;
1197
-
1198
- let filteredItems;
1199
-
1200
- if (typeof fn === 'function') {
1201
- // Send the original items to the filter function
1202
- filteredItems = p.filterFn(
1203
- p.items.map(x => {
1204
- const y = x[ItemSymbol];
1205
- if (y !== undefined) {
1206
- // Seal it to avoid object finding issues when wrapped in proxies by Vue or other libs
1207
- y[ItemSymbol] = Object.seal({
1208
- [ItemSymbol]: x,
1209
- });
1210
- return y;
1211
- }
1212
-
1213
- return x;
1214
- }),
1215
- term);
1216
-
1217
- if (Array.isArray(filteredItems)) {
1218
- // And back
1219
- filteredItems = filteredItems.map(oitem => {
1220
- let our = oitem[ItemSymbol]?.[ItemSymbol]; // double-unwrap sealed->item
1221
- if (!our) {
1222
- our = {
1223
- [ItemSymbol]: oitem,
1224
- label: oitem[p.labelProp],
1225
- value: oitem[p.valueProp],
1226
- _nocheck: !!oitem._nocheck,
1227
- _nointeraction: !!oitem._nointeraction,
1228
- _subitems: oitem._subitems,
1229
- _group: !!oitem._group,
1230
- _level: !!oitem._level,
1231
- _checked: !!oitem._checked,
1232
- };
1233
- }
1234
- return our;
1235
- });
1236
- }
1237
- }
1238
-
1239
- // If there was no filter function, or it gave up on filtering.
1240
- if (!Array.isArray(filteredItems)) {
1241
- if (term) {
1242
- const matcher = new RegExp(escapeRegex(term), 'i');
1243
-
1244
- filteredItems = p.items.filter(x => {
1245
- if (!filterGroups && x._group) return true;
1246
- return matcher.test(x.label);
1247
- });
1248
- } else {
1249
- filteredItems = null;
1250
- }
1251
- }
1252
-
1253
- p.filteredItems = filteredItems;
1254
-
1255
- if (filteredItems && filterEmptyGroups) {
1256
- // Clean up groups without children
1257
-
1258
- let lastGroup = -1;
1259
- let len = filteredItems.length;
1260
-
1261
- for (let i = 0; i < len; i++) {
1262
- let item = filteredItems[i];
1263
-
1264
- if (item._group) {
1265
- if (lastGroup !== -1 && lastGroup === i - 1) {
1266
- // It was an empty group
1267
- filteredItems.splice(lastGroup, 1);
1268
- i--;
1269
- len--;
1270
- }
1271
-
1272
- lastGroup = i;
1273
- }
1274
- }
1275
-
1276
- if (lastGroup !== -1) {
1277
- if (lastGroup === len - 1) {
1278
- // It was an empty group
1279
- filteredItems.splice(lastGroup, 1);
1280
- }
1281
- }
1282
- }
1283
- } else {
1284
- p.filteredItems = null;
1285
- }
1286
-
1287
- p.needsRefilter = false;
1288
-
1289
- const items = p.filteredItems ?? p.items;
1290
- p.hasNoResultsItem = items.length === 0 && !!p.noResultsText;
1291
- p.virtualListHelper
1292
- .setCount(items.length + (p.hasNoResultsItem ? 1 : 0))
1293
- .render();
1294
-
1295
- this._trigger('itemschanged', { term: term, mutated: false, count: this.getFilteredItemCount() });
1296
- this.relayout();
1297
- }
1298
-
1299
- invokeRefilter() {
1300
- const p = this._p;
1301
- if (!p.filterTerm && !p.filterOnEmptyTerm && !p.filteredItems)
1302
- return this;
1303
- p.filteredItems = null;
1304
- p.throttledRefilterItems();
1305
- return this;
1306
- }
1307
-
1308
- rushRefilter() {
1309
- const p = this._p;
1310
- if (p.needsRefilter)
1311
- this._refilterItems();
1312
- return this;
1313
- }
1314
-
1315
- getFilteredItemCount() {
1316
- const p = this._p;
1317
-
1318
- this.rushRefilter();
1319
-
1320
- if (p.filteredItems)
1321
- return p.filteredItems.length;
1322
-
1323
- if (p.items)
1324
- return p.items.length;
1325
-
1326
- return 0;
1327
- }
1328
-
1329
- /**
1330
- * @param {string} noResultsText
1331
- * @returns {DropList}
1332
- */
1333
- setNoResultsText(noResultsText) {
1334
- const p = this._p;
1335
-
1336
- p.noResultsText = noResultsText;
1337
-
1338
- if (p.hasNoResultsItem) {
1339
- p.virtualListHelper.refreshItemAt(0).render();
1340
- }
1341
-
1342
- return this;
1343
- }
1344
-
1345
- /**
1346
- * @returns {string}
1347
- */
1348
- getNoResultsText() {
1349
- return this._p.noResultsText;
1350
- }
1351
-
1352
- /**
1353
- * @param {number} window
1354
- * @returns {DropList}
1355
- */
1356
- setFilterThrottleWindow(window) {
1357
- const p = this._p;
1358
- p.filterThrottleWindow = window;
1359
-
1360
- let isScheduled = p.throttledRefilterItems ? p.throttledRefilterItems.isScheduled() : false;
1361
-
1362
- if (p.throttledRefilterItems)
1363
- p.throttledRefilterItems.cancel();
1364
-
1365
- p.throttledRefilterItems = throttle(() => this._refilterItems(), p.filterThrottleWindow, true);
1366
-
1367
- if (isScheduled)
1368
- p.throttledRefilterItems();
1369
-
1370
- return this;
1371
- }
1372
-
1373
- /**
1374
- * @returns {number}
1375
- */
1376
- getFilterThrottleWindow() {
1377
- return this._p.filterThrottleWindow;
1378
- }
1379
-
1380
- /**
1381
- * @param {boolean} value
1382
- * @returns {DropList}
1383
- */
1384
- setFilterOnEmptyTerm(value) {
1385
- const p = this._p;
1386
- if (p.filterOnEmptyTerm === value)
1387
- return this;
1388
- p.filterOnEmptyTerm = value;
1389
- p.throttledRefilterItems();
1390
- return this;
1391
- }
1392
-
1393
- /**
1394
- * @returns {boolean}
1395
- */
1396
- getFilterOnEmptyTerm() {
1397
- return this._p.filterOnEmptyTerm;
1398
- }
1399
-
1400
- /**
1401
- * @param {boolean} value
1402
- * @returns {DropList}
1403
- */
1404
- setFilterGroups(value) {
1405
- const p = this._p;
1406
- if (p.filterGroups === value)
1407
- return this;
1408
- p.filterGroups = value;
1409
- p.throttledRefilterItems();
1410
- return this;
1411
- }
1412
-
1413
- /**
1414
- * @returns {boolean}
1415
- */
1416
- getFilterGroups() {
1417
- return this._p.filterGroups;
1418
- }
1419
-
1420
- /**
1421
- * @param {boolean} value
1422
- * @returns {DropList}
1423
- */
1424
- setFilterEmptyGroups(value) {
1425
- const p = this._p;
1426
- if (p.filterEmptyGroups === value)
1427
- return this;
1428
- p.filterEmptyGroups = value;
1429
- p.throttledRefilterItems();
1430
- return this;
1431
- }
1432
-
1433
- /**
1434
- * @returns {boolean}
1435
- */
1436
- getFilterEmptyGroups() {
1437
- return this._p.filterEmptyGroups;
1438
- }
1439
-
1440
- /**
1441
- * @param {function(items: DropList.ItemBase[], term: string):(DropList.ItemBase[]|null)} fn
1442
- * @returns {DropList}
1443
- */
1444
- setFilterFn(fn) {
1445
- const p = this._p;
1446
- if (p.filterFn === fn)
1447
- return this;
1448
- p.filterFn = fn;
1449
- p.throttledRefilterItems();
1450
- return this;
1451
- }
1452
-
1453
- /**
1454
- * @returns {function(items: DropList.ItemBase[], term: string):(DropList.ItemBase[]|null)}
1455
- */
1456
- getFilterFn() {
1457
- return this._p.filterFn;
1458
- }
1459
-
1460
- /**
1461
- *
1462
- * @param {DropList.PositionOptions} [positionOptions]
1463
- * @returns {DropList}
1464
- * @public
1465
- */
1466
- relayout(positionOptions) {
1467
- const p = this._p, el = p.el, menuEl = p.menuEl;
1468
-
1469
- if (!this.isVisible()) return this;
1470
-
1471
- let w = window;
1472
-
1473
- if (!positionOptions)
1474
- positionOptions = p.positionOptionsProvider?.() ?? p.lastPositionOptions;
1475
-
1476
- // Supply some default for extreme cases, no crashing
1477
- if (!positionOptions) {
1478
- positionOptions = {
1479
- targetOffset: {
1480
- left: window.innerWidth / 2,
1481
- top: window.innerHeight / 2,
1482
- },
1483
- targetWidth: 0,
1484
- targetHeight: 0,
1485
- position: { x: 'center', y: 'center' },
1486
- anchor: { x: 'center', y: 'center' },
1487
- targetRtl: getComputedStyle(document.body).direction === 'rtl',
1488
- };
1489
- }
1490
-
1491
- let targetBox = {};
1492
-
1493
- let offset = positionOptions.targetOffset || getElementOffset(positionOptions.target);
1494
- targetBox.left = offset.left;
1495
- targetBox.top = offset.top;
1496
- targetBox.height = positionOptions.targetHeight == null
1497
- ? getElementHeight(positionOptions.target, true, true)
1498
- : positionOptions.targetHeight;
1499
- targetBox.width = positionOptions.targetWidth == null
1500
- ? getElementWidth(positionOptions.target, true, true)
1501
- : positionOptions.targetWidth;
1502
- targetBox.bottom = targetBox.top + targetBox.height;
1503
-
1504
- let viewport = {};
1505
- viewport.top = w.pageYOffset;
1506
- viewport.left = w.pageXOffset;
1507
- viewport.width = w.innerWidth;
1508
- viewport.height = w.innerHeight;
1509
- viewport.bottom = viewport.top + viewport.height;
1510
- viewport.right = viewport.left + viewport.width;
1511
-
1512
- let defaultVerticalDirection = (positionOptions.position && positionOptions.position.y === 'bottom')
1513
- ? 'above'
1514
- : 'below';
1515
-
1516
- // Reset dropdown width
1517
- el.style.width = '';
1518
-
1519
- // Make estimations
1520
- if (p.estimateWidth ||
1521
- p.virtualListHelper.isVirtual()) {
1522
- this._measureItem();
1523
- }
1524
-
1525
- // Calculate virtual viewport size
1526
- if (p.virtualListHelper.isVirtual()) {
1527
- // Avoid extremely high size which will cause laying out the whole list
1528
- menuEl.style.height = Math.min(el.clientHeight, document.body.clientHeight) + 'px';
1529
- p.virtualListHelper.render();
1530
- }
1531
-
1532
- // Now set the width of the dropdown
1533
- if (positionOptions.updateWidth || typeof positionOptions.updateWidth === 'number') {
1534
- this._updateWidth(positionOptions);
1535
- } else {
1536
- this._updateWidth();
1537
- }
1538
-
1539
- // Update estimated item heights after width is set
1540
- if (p.virtualListHelper.isVirtual()) {
1541
- p.virtualListHelper.render();
1542
- }
1543
-
1544
- // How much space is there above, and how much below?
1545
- let roomAbove = targetBox.top - viewport.top;
1546
- let roomBelow = viewport.bottom - targetBox.bottom;
1547
-
1548
- // Calculate height for dropdown
1549
-
1550
- let maxViewHeight;
1551
-
1552
- const elComputedStyle = getComputedStyle(el);
1553
-
1554
- let isBoxing = elComputedStyle.boxSizing === 'border-box';
1555
- let verticalPadding = (parseFloat(elComputedStyle.paddingTop) || 0) +
1556
- (parseFloat(elComputedStyle.paddingBottom) || 0);
1557
- let verticalBorderWidth = (parseFloat(elComputedStyle.borderTopWidth) || 0) +
1558
- (parseFloat(elComputedStyle.borderBottomWidth) || 0);
1559
-
1560
- let headerHeight = 0;
1561
- if (p.headerEl) {
1562
- headerHeight = getElementHeight(p.headerEl, true, true);
1563
- }
1564
-
1565
- let footerHeight = 0;
1566
- if (p.footerEl) {
1567
- footerHeight = getElementHeight(p.footerEl, true, true);
1568
- }
1569
-
1570
- if (p.virtualListHelper.isVirtual()) {
1571
- maxViewHeight =
1572
- p.virtualListHelper.estimateFullHeight() +
1573
- verticalPadding +
1574
- verticalBorderWidth +
1575
- headerHeight +
1576
- footerHeight;
1577
- } else {
1578
- // Another method to calculate height is measuring the whole thing at once.
1579
- // This causes relayout of course.
1580
- el.style.height = '';
1581
- menuEl.style.height = '';
1582
- el.style.top = '-9999px';
1583
-
1584
- maxViewHeight = Math.max(getElementHeight(p.el), menuEl.scrollHeight);
1585
- maxViewHeight += verticalPadding + verticalBorderWidth;
1586
- }
1587
-
1588
- // Consider css max-height
1589
-
1590
- let maxHeight = parseFloat(elComputedStyle.maxHeight);
1591
- if (!isNaN(maxHeight)) {
1592
- if (!isBoxing) {
1593
- maxHeight += verticalPadding + verticalBorderWidth;
1594
- }
1595
-
1596
- maxViewHeight = Math.min(maxViewHeight, maxHeight);
1597
- }
1598
-
1599
- // Figure out the direction
1600
-
1601
- let enoughRoomAbove = roomAbove >= maxViewHeight;
1602
- let enoughRoomBelow = roomBelow >= maxViewHeight;
1603
-
1604
- let newDirection = p.currentDirection || defaultVerticalDirection;
1605
- if (newDirection === 'above' && !enoughRoomAbove && enoughRoomBelow) {
1606
- newDirection = 'below';
1607
- } else if (newDirection === 'below' && !enoughRoomBelow && enoughRoomAbove) {
1608
- newDirection = 'above';
1609
- } else if (enoughRoomAbove && enoughRoomBelow) {
1610
- if (newDirection !== defaultVerticalDirection &&
1611
- ((defaultVerticalDirection === 'above' && roomAbove >= roomBelow) ||
1612
- (defaultVerticalDirection === 'below' && roomBelow >= roomAbove))) {
1613
- newDirection = defaultVerticalDirection;
1614
- }
1615
- } else if (!enoughRoomAbove && !enoughRoomBelow) {
1616
- if (roomAbove > roomBelow) {
1617
- newDirection = 'above';
1618
- } else if (roomBelow > roomAbove) {
1619
- newDirection = 'below';
1620
- }
1621
- }
1622
- p.currentDirection = newDirection;
1623
-
1624
- // Figure out that final view size
1625
- let viewSize = {
1626
- width: getElementWidth(el, true, true),
1627
- height: Math.min(maxViewHeight, Math.max(roomAbove, roomBelow, 0)),
1628
- };
1629
-
1630
- let isTargetRtl = positionOptions.targetRtl !== undefined ?
1631
- positionOptions.targetRtl :
1632
- (positionOptions.target == null ? false : getComputedStyle(positionOptions.target).direction === 'rtl');
1633
- let isRtlDocument = getComputedStyle(document.documentElement).direction === 'rtl';
1634
-
1635
- let anchor = anchoredPosition(positionOptions.target,
1636
- positionOptions.anchor ? positionOptions.anchor.x : 'start',
1637
- positionOptions.anchor ? positionOptions.anchor.y : 'bottom',
1638
- targetBox, isTargetRtl);
1639
- let position = anchoredPosition(el,
1640
- positionOptions.position ? positionOptions.position.x : 'start',
1641
- positionOptions.position ? positionOptions.position.y : 'top',
1642
- viewSize, isTargetRtl);
1643
-
1644
- // If it's not in the direction that the user expected, invert it
1645
- let invertYPos =
1646
- (position.ySpec === 'top' && newDirection === 'above') ||
1647
- (position.ySpec === 'bottom' && newDirection === 'below') ||
1648
- (position.ySpec !== 'bottom' && position.ySpec !== 'top' && newDirection === 'above');
1649
-
1650
- let scrollLeft =
1651
- (w.pageXOffset !== undefined) ?
1652
- w.pageXOffset :
1653
- (document.documentElement || document.body.parentNode || document.body).scrollLeft;
1654
- scrollLeft = Math.abs(scrollLeft);
1655
- if (isRtlDocument) {
1656
- scrollLeft = document.documentElement.scrollWidth - scrollLeft - document.documentElement.clientWidth;
1657
- }
1658
-
1659
- let minX = scrollLeft,
1660
- maxX = document.documentElement.clientWidth + scrollLeft - viewSize.width;
1661
-
1662
- let viewCss = {
1663
- 'position': 'absolute',
1664
- 'left': targetBox.left,
1665
- 'top': targetBox.top + (invertYPos ? (anchor.bottom - position.bottom) : (anchor.top - position.top)),
1666
- };
1667
-
1668
- if (isRtlDocument) {
1669
- viewCss.left -= document.documentElement.clientWidth - document.documentElement.scrollWidth;
1670
- }
1671
-
1672
- viewCss.left += anchor.left - position.left;
1673
-
1674
- if (positionOptions.offset) {
1675
- if (positionOptions.offset.y) {
1676
- if (invertYPos) {
1677
- viewCss.top -= positionOptions.offset.y;
1678
- } else {
1679
- viewCss.top += positionOptions.offset.y;
1680
- }
1681
- }
1682
-
1683
- if (positionOptions.offset.x) {
1684
- let rtl = elComputedStyle.direction === 'rtl';
1685
- viewCss.left += rtl
1686
- ? -positionOptions.offset.x
1687
- : positionOptions.offset.x;
1688
- }
1689
- }
1690
-
1691
- if (p.autoFlipDirection) {
1692
- if ((position.xSpec === 'right' &&
1693
- viewCss.left < minX &&
1694
- (Math.max(viewCss.left, minX) + viewSize.width - targetBox.left) / targetBox.width > 0.5) ||
1695
- (position.xSpec === 'left' &&
1696
- viewCss.left > maxX &&
1697
- (Math.min(viewCss.left, maxX) - targetBox.left) / targetBox.width < 0.5)) {
1698
- viewCss.left -= anchor.left - position.left;
1699
- viewCss.left += anchor.right - position.right;
1700
- }
1701
- }
1702
-
1703
- // Constrain to the window if required
1704
- if (p.constrainToWindow) {
1705
- for (let which of (isRtlDocument ? ['min', 'max'] : ['max', 'min'])) {
1706
- if (which === 'min' && viewCss.left < minX)
1707
- viewCss.left = minX;
1708
- else if (which === 'max' && viewCss.left > maxX)
1709
- viewCss.left = maxX;
1710
- }
1711
- }
1712
-
1713
- // Set position CSS
1714
- viewCss.left += 'px';
1715
- viewCss.top += 'px';
1716
- setCssProps(el, viewCss);
1717
- setElementHeight(el, viewSize.height, true, true);
1718
-
1719
- if (menuEl !== el) {
1720
- let menuHeight = viewSize.height - headerHeight - footerHeight - verticalBorderWidth - verticalPadding;
1721
- setElementHeight(menuEl, menuHeight, true, true);
1722
- }
1723
-
1724
- // Update the scroll position for virtual lists
1725
- p.virtualListHelper.render();
1726
-
1727
- // Update position classes
1728
- if (positionOptions && positionOptions.target) {
1729
- p.lastPositionTarget = positionOptions.target;
1730
-
1731
- toggleClass(positionOptions.target, `has_${p.baseClassName}`, true);
1732
- toggleClass(positionOptions.target, `has_${p.baseClassName}_below`, newDirection === 'below');
1733
- toggleClass(positionOptions.target, `has_${p.baseClassName}_above`, newDirection === 'above');
1734
-
1735
- toggleClass(el, `${p.baseClassName}__is_below`, newDirection === 'below');
1736
- toggleClass(el, `${p.baseClassName}__is_above`, newDirection === 'above');
1737
- }
1738
-
1739
- return this;
1740
- }
1741
-
1742
- /**
1743
- * Set the checked mode of a specific value.
1744
- * @public
1745
- * @param {*} value - array of values to check
1746
- * @param {boolean} checked - will the value be checked?
1747
- * @returns {DropList} self
1748
- */
1749
- setItemChecked(value, checked) {
1750
- const p = this._p;
1751
-
1752
- checked = !!checked;
1753
-
1754
- let index = this.itemIndexByValue(value);
1755
- if (index === -1) return this;
1756
-
1757
- let li = p.virtualListHelper.getItemElementAt(index);
1758
- if (!li) return this;
1759
-
1760
- let item = li[ItemSymbol];
1761
-
1762
- checked = checked && !item._nocheck;
1763
-
1764
- if (item._checked !== checked) {
1765
- item._checked = checked;
1766
-
1767
- toggleClass(li, `${p.baseClassName}__item_checked`, item._checked);
1768
-
1769
- this._updateGroupStateForItem(item);
1770
- }
1771
-
1772
- return this;
1773
- }
1774
-
1775
- /**
1776
- * Set the checked values. All the other values will be unchecked,
1777
- * @public
1778
- * @param {Array<*>} values - array of values to check
1779
- * @returns {DropList} self
1780
- */
1781
- setCheckedValues(values) {
1782
- const p = this._p;
1783
-
1784
- this.rushRefilter();
1785
-
1786
- let groupIndexes = [];
1787
-
1788
- for (let i = 0, count = p.items.length; i < count; i++) {
1789
- let item = p.items[i];
1790
- let checked = !item._nocheck && values.indexOf(item.value) !== -1;
1791
-
1792
- let itemIndex = p.filteredItems ? p.filteredItems.indexOf(item) : i;
1793
-
1794
- if (item._group && itemIndex !== -1) {
1795
- groupIndexes.push(itemIndex);
1796
- }
1797
-
1798
- if (item._checked === checked) continue;
1799
-
1800
- item._checked = checked;
1801
-
1802
- if (itemIndex === -1) continue;
1803
-
1804
- let li = p.virtualListHelper.getItemElementAt(itemIndex);
1805
- if (!li) continue;
1806
-
1807
- toggleClass(li, `${p.baseClassName}__item_checked`, item._checked);
1808
- }
1809
-
1810
- if (p.autoCheckGroupChildren) {
1811
- for (let i = 0, count = groupIndexes.length; i < count; i++) {
1812
- this._updateGroupCheckedState(groupIndexes[i], false);
1813
- }
1814
- }
1815
-
1816
- return this;
1817
- }
1818
-
1819
- /**
1820
- * Get all checked values. Returns array of item values.
1821
- * @public
1822
- * @param {boolean} excludeGroups=false Exclude group items
1823
- * @returns {Array<*>} self
1824
- */
1825
- getCheckedValues(excludeGroups) {
1826
- const p = this._p;
1827
-
1828
- excludeGroups = excludeGroups && p.groupCount > 0;
1829
-
1830
- let values = [];
1831
-
1832
- for (let i = 0, count = p.items.length; i < count; i++) {
1833
- let item = p.items[i];
1834
- if (!item._checked) continue;
1835
- if (excludeGroups && item._group) continue;
1836
- values.push(item.value);
1837
- }
1838
-
1839
- return values;
1840
- }
1841
-
1842
- /**
1843
- * Get all checked items. Returns array of actual item data object.
1844
- * @public
1845
- * @param {boolean} excludeGroups=false Exclude group items
1846
- * @returns {DropList.Item[]}
1847
- */
1848
- getCheckedItems(excludeGroups) {
1849
- const p = this._p;
1850
-
1851
- excludeGroups = excludeGroups && p.groupCount > 0;
1852
-
1853
- const items = [];
1854
-
1855
- for (let i = 0, count = p.items.length; i < count; i++) {
1856
- let item = p.items[i];
1857
- if (!item._checked) continue;
1858
- if (excludeGroups && item._group) continue;
1859
- items.push(item[ItemSymbol]);
1860
- }
1861
-
1862
- return items;
1863
- }
1864
-
1865
- /**
1866
- *
1867
- * @param {DropList.PositionOptions?} [positionOptions]
1868
- * @returns {DropList}
1869
- * @public
1870
- */
1871
- show(positionOptions) {
1872
- const p = this._p;
1873
-
1874
- p.hiding = false;
1875
-
1876
- if (!this.isVisible()) {
1877
- this._trigger('show:before');
1878
- }
1879
-
1880
- p.mouseHandled = false;
1881
-
1882
- setTimeout(() => { // Skip the end of a 'click' event
1883
- if (this[DestroyedSymbol]) return;
1884
-
1885
- if (!p.onDocumentMouseDown) {
1886
- // Detect mouse tap outside of the droplist, to blur the focused item
1887
- p.sink.add(document, 'mousedown', p.onDocumentMouseDown = (event) => {
1888
- if (!this.elContains(event.target, true))
1889
- this._delayBlurItemOnBlur();
1890
- });
1891
- }
1892
- });
1893
-
1894
- this.rushRefilter();
1895
-
1896
- const el = p.el;
1897
- el.style.position = 'absolute';
1898
- el.classList.remove(`${p.baseClassName}__is-hiding`);
1899
- document.body.appendChild(el);
1900
-
1901
- p.visible = true;
1902
-
1903
- p.el.style.display = '';
1904
- if (getComputedStyle(p.el).display === 'none')
1905
- p.el.style.display = 'block';
1906
-
1907
- p.lastPositionOptions = null;
1908
-
1909
- if (positionOptions === undefined) {
1910
- positionOptions = p.positionOptionsProvider?.() ?? p.lastPositionOptions;
1911
- } else {
1912
- p.lastPositionOptions = positionOptions;
1913
- }
1914
-
1915
- if (positionOptions) {
1916
- const elComputedStyle = getComputedStyle(el);
1917
-
1918
- // Set max height to avoid adding scrollbars to page
1919
- const originalMaxHeight = el.style.maxHeight;
1920
- let maxHeight = document.body.clientHeight -
1921
- (parseFloat(elComputedStyle.marginTop) || 0) -
1922
- (parseFloat(elComputedStyle.marginBottom) || 0) -
1923
- (elComputedStyle.boxSizing === 'border-box'
1924
- ? 0
1925
- : ((parseFloat(elComputedStyle.borderTopWidth) || 0) +
1926
- (parseFloat(elComputedStyle.borderBottomWidth) || 0)));
1927
-
1928
- el.style.maxHeight = Math.min(maxHeight, parseFloat(elComputedStyle.maxHeight) || maxHeight) + 'px';
1929
-
1930
- this.relayout(positionOptions);
1931
-
1932
- // Restore original max-height
1933
- el.style.maxHeight = originalMaxHeight;
1934
- } else {
1935
- // Calculate virtual viewport size
1936
- if (p.virtualListHelper.isVirtual()) {
1937
- p.virtualListHelper.render();
1938
- }
1939
- }
1940
-
1941
- if (this.isVisible()) {
1942
- this._trigger('show');
1943
- }
1944
-
1945
- return this;
1946
- }
1947
-
1948
- hide() {
1949
- const p = this._p, el = p.el;
1950
-
1951
- if (p.onDocumentMouseDown) {
1952
- p.sink.remove(document, 'mousedown', p.onDocumentMouseDown);
1953
- p.onDocumentMouseDown = null;
1954
- }
1955
-
1956
- if (this.isVisible()) {
1957
- this._trigger('hide:before');
1958
-
1959
- p.hiding = true;
1960
-
1961
- if (this.isFilterPending()) {
1962
- p.throttledRefilterItems.cancel();
1963
- p.needsRefilter = true;
1964
- }
1965
-
1966
- if (el) {
1967
-
1968
- el.classList.add(`${p.baseClassName}__is-hiding`);
1969
-
1970
- // support for hide transition in css
1971
- const maxTransitionDuration = parseTransition(getComputedStyle(p.el).transition)
1972
- .reduce((p, v) => Math.max(p, v.delay + v.duration), 0);
1973
-
1974
- if (maxTransitionDuration > 0) {
1975
- setTimeout(() => {
1976
- if (this[DestroyedSymbol]) return;
1977
-
1978
- if (this._p && el.parentNode && p.hiding) {
1979
- remove(el);
1980
- el.classList.remove(`${p.baseClassName}__is-hiding`);
1981
- p.visible = false;
1982
- this._trigger('hide:after');
1983
- }
1984
- });
1985
- } else {
1986
- if (el.parentNode)
1987
- remove(el);
1988
- el.classList.remove(`${p.baseClassName}__is-hiding`);
1989
- }
1990
- }
1991
-
1992
- p.visible = false;
1993
-
1994
- this.blurFocusedItem();
1995
- this._trigger('hide');
1996
-
1997
- if (this[DestroyedSymbol]) return;
1998
- this._trigger('hide:after');
1999
-
2000
- if (p.currentSubDropList) {
2001
- this._hideSublist();
2002
- }
2003
- }
2004
-
2005
- if (p.lastPositionTarget) {
2006
- p.lastPositionTarget.classList.remove(
2007
- `has_${p.baseClassName}`,
2008
- `has_${p.baseClassName}_above`,
2009
- `has_${p.baseClassName}_below`);
2010
- delete p.lastPositionTarget;
2011
- }
2012
-
2013
- return this;
2014
- }
2015
-
2016
- isVisible() {
2017
- const p = this._p;
2018
- if (!p.visible)
2019
- return false;
2020
- return p.el.parentNode && getComputedStyle(p.el).display !== 'none';
2021
- }
2022
-
2023
- /**
2024
- * Change visibility of the header element
2025
- * You should probably call `relayout()` after this.
2026
- * @param {boolean} visible
2027
- */
2028
- setHeaderVisible(visible) {
2029
- let isVisible = this.isHeaderVisible();
2030
- if (isVisible === !!visible)
2031
- return;
2032
-
2033
- if (visible) {
2034
- this._p.el.insertBefore(this._p.headerEl, this._p.el.firstChild ?? null);
2035
- } else {
2036
- this._p.headerEl.remove();
2037
- }
2038
- }
2039
-
2040
- /**
2041
- * Is the header element visible?
2042
- * @returns {boolean}
2043
- */
2044
- isHeaderVisible() {
2045
- return !!this._p.headerEl.parentNode;
2046
- }
2047
-
2048
- /**
2049
- * Get a reference to the header element in order to add custom content.
2050
- * @returns {Element}
2051
- */
2052
- getHeaderElement() {
2053
- return this._p.headerEl;
2054
- }
2055
-
2056
- /**
2057
- * Change visibility of the footer element
2058
- * You should probably call `relayout()` after this.
2059
- * @param {boolean} visible
2060
- */
2061
- setFooterVisible(visible) {
2062
- let isVisible = this.isFooterVisible();
2063
- if (isVisible === !!visible)
2064
- return;
2065
-
2066
- if (visible) {
2067
- this._p.el.appendChild(this._p.footerEl);
2068
- } else {
2069
- this._p.footerEl.remove();
2070
- }
2071
- }
2072
-
2073
- /**
2074
- * Is the footer element visible?
2075
- * @returns {boolean}
2076
- */
2077
- isFooterVisible() {
2078
- return !!this._p.footerEl.parentNode;
2079
- }
2080
-
2081
- /**
2082
- * Get a reference to the footer element in order to add custom content.
2083
- * @returns {Element}
2084
- */
2085
- getFooterElement() {
2086
- return this._p.footerEl;
2087
- }
2088
-
2089
- /**
2090
- * Set inline search visibility
2091
- * You should probably call `relayout()` after this.
2092
- * @param {boolean} searchable
2093
- */
2094
- setSearchable(searchable) {
2095
- const p = this._p;
2096
-
2097
- if (!!p.searchInput === !!searchable)
2098
- return;
2099
-
2100
- if (searchable) {
2101
- p.searchInput = createElement('input', {
2102
- type: 'search',
2103
- role: 'searchbox',
2104
- tabindex: '0',
2105
- autocorrect: 'off',
2106
- autocomplete: 'off',
2107
- autocapitalize: 'off',
2108
- spellcheck: 'false',
2109
- 'aria-autocomplete': 'list',
2110
- placeholder: p.searchPlaceholder || '',
2111
- });
2112
-
2113
- p.headerEl.appendChild(p.searchInput);
2114
- } else {
2115
- if (p.searchInput.parentNode)
2116
- p.searchInput.remove();
2117
- p.searchInput = null;
2118
- }
2119
-
2120
- this.setHeaderVisible(searchable);
2121
- }
2122
-
2123
- /**
2124
- * Set the placeholder text of the inline search box
2125
- * @param {string} placeholder
2126
- */
2127
- setSearchPlaceholder(placeholder) {
2128
- const p = this._p;
2129
-
2130
- p.searchPlaceholder = placeholder || '';
2131
-
2132
- if (p.searchInput) {
2133
- p.searchInput.placeholder = p.searchPlaceholder;
2134
- }
2135
- }
2136
-
2137
- hasFocusedItem() {
2138
- return this._p.focusItemIndex > -1 && this._p.focusItemIndex < this._p.items.length;
2139
- }
2140
-
2141
- getFocusedItemIndex() {
2142
- if (!this.hasFocusedItem())
2143
- return -1;
2144
- return this._p.focusItemIndex;
2145
- }
2146
-
2147
- setFocusedItemAtIndex(itemIndex) {
2148
- const p = this._p;
2149
-
2150
- this.rushRefilter();
2151
-
2152
- if (p.filteredItems) {
2153
- const item = p.filteredItems[itemIndex];
2154
- itemIndex = p.items.indexOf(item);
2155
- }
2156
-
2157
- p.focusItemIndex = itemIndex;
2158
-
2159
- const items = p.filteredItems ?? p.items;
2160
-
2161
- let item = null;
2162
- if (itemIndex > -1)
2163
- item = items[itemIndex];
2164
- if (item && item._nointeraction)
2165
- item = null;
2166
- if (itemIndex > -1) {
2167
- this._scrollItemIndexIntoView(itemIndex);
2168
- }
2169
- let itemElement = item ? p.virtualListHelper.getItemElementAt(itemIndex) : null;
2170
-
2171
- if (p.focusItemEl !== itemElement) {
2172
- if (p.focusItemEl) {
2173
- p.focusItemEl.classList.remove(`${p.baseClassName}__item_focus`);
2174
- p.focusItemEl = null;
2175
- }
2176
-
2177
- if (itemElement) {
2178
- itemElement.classList.add(`${p.baseClassName}__item_focus`);
2179
- p.focusItemEl = itemElement;
2180
-
2181
- const item = itemElement[ItemSymbol];
2182
-
2183
- this._trigger('itemfocus', {
2184
- value: item.value,
2185
- item: item[ItemSymbol] ?? item,
2186
- event: null,
2187
- el: itemElement,
2188
- });
2189
-
2190
- this._showSublist(item, itemElement);
2191
- }
2192
- }
2193
-
2194
- return this;
2195
- }
2196
-
2197
- _showSublist(item, itemElement) {
2198
- if (!item._subitems?.length) return;
2199
-
2200
- const p = this._p;
2201
- if (p.currentSubDropList?.item === item)
2202
- return;
2203
-
2204
- const droplist = new DropList({
2205
- baseClassName: p.baseClassName,
2206
- additionalClasses: p.additionalClasses,
2207
- direction: p.direction,
2208
- autoItemBlur: p.autoItemBlur,
2209
- autoItemBlurDelay: p.autoItemBlurDelay,
2210
- capturesFocus: p.capturesFocus,
2211
- multi: p.multi,
2212
- keyDownHandler: p.keyDownHandler,
2213
- autoCheckGroupChildren: p.autoCheckGroupChildren,
2214
- useExactTargetWidth: p.useExactTargetWidth,
2215
- constrainToWindow: p.constrainToWindow,
2216
- autoFlipDirection: p.autoFlipDirection,
2217
- estimatedItemHeight: p.estimatedItemHeight,
2218
- estimateWidth: p.estimateWidth,
2219
- virtualMinItems: p.virtualMinItems,
2220
- singleSelectedValue: p.singleSelectedValue,
2221
- labelProp: p.labelProp,
2222
- valueProp: p.valueProp,
2223
- renderItem: p.renderItem,
2224
- unrenderItem: p.unrenderItem,
2225
- positionOptionsProvider: () => p.currentSubDropList.showOptions,
2226
- });
2227
-
2228
- let onBlur = event => {
2229
- if (this[DestroyedSymbol]) return;
2230
-
2231
- if (event.relatedTarget && this.elContains(event.relatedTarget, true))
2232
- return;
2233
-
2234
- this._delayBlurItemOnBlur();
2235
- this._trigger('subitems:blur', event);
2236
- };
2237
-
2238
- droplist
2239
- .on('select', event => {
2240
- this._trigger('subitems:select', event);
2241
- })
2242
- .on('subitems:select', event => {
2243
- this._trigger('subitems:select', event);
2244
- })
2245
- .on('show_subitems', event => {
2246
- this._trigger('show_subitems', event);
2247
- })
2248
- .on('hide_subitems', event => {
2249
- this._trigger('hide_subitems', event);
2250
- })
2251
- .on('blur', onBlur)
2252
- .on('subitems:blur', onBlur)
2253
- .on('_back_key_pressed', () => {
2254
- this._hideSublist();
2255
- });
2256
-
2257
- droplist.setItems(item._subitems);
2258
-
2259
- this._trigger('show_subitems', {
2260
- value: item.value,
2261
- item: item[ItemSymbol] ?? item,
2262
- el: itemElement,
2263
- droplist: droplist,
2264
- });
2265
-
2266
- p.currentSubDropList = {
2267
- item: item,
2268
- itemElement: itemElement,
2269
- droplist: droplist,
2270
- showOptions: {
2271
- target: itemElement,
2272
- position: { x: 'start', y: 'top' },
2273
- anchor: { x: 'end', y: 'top' },
2274
- offset: { x: 0, y: 0 },
2275
- updateWidth: false,
2276
- },
2277
- };
2278
-
2279
- droplist.show();
2280
-
2281
- droplist.el.focus();
2282
- }
2283
-
2284
- _hideSublist() {
2285
- const p = this._p;
2286
-
2287
- if (!p.currentSubDropList)
2288
- return;
2289
-
2290
- const data = p.currentSubDropList;
2291
-
2292
- let subHadFocus = !!document.activeElement && data.droplist.elContains(document.activeElement, true);
2293
-
2294
- data.droplist.hide();
2295
- data.droplist.destroy();
2296
- p.currentSubDropList = null;
2297
-
2298
- if (subHadFocus && !this[DestroyedSymbol]) {
2299
- this.el.focus();
2300
- }
2301
-
2302
- this._trigger('hide_subitems', {
2303
- value: data.item.value,
2304
- item: data.item,
2305
- el: data.itemElement,
2306
- droplist: data.droplist,
2307
- });
2308
- }
2309
-
2310
- /**
2311
- * Updates the current open sublist with new subitems if changed
2312
- */
2313
- updateSublist() {
2314
- const p = this._p;
2315
-
2316
- if (!p.currentSubDropList)
2317
- return;
2318
-
2319
- const originalItem = p.currentSubDropList.item;
2320
-
2321
- const data = p.currentSubDropList;
2322
- const newItem = p.items.find(x => x === originalItem) ||
2323
- p.items.find(x => x.value === data.item.value);
2324
- if (newItem) {
2325
- p.currentSubDropList.item = newItem;
2326
- const itemElement = p.virtualListHelper.getItemElementAt(this._getItemIndex(newItem));
2327
- p.currentSubDropList.itemElement = itemElement;
2328
-
2329
- if (newItem._subitems) {
2330
- p.currentSubDropList.droplist.setItems(newItem._subitems);
2331
-
2332
- if (itemElement) {
2333
- p.currentSubDropList.showOptions.target = itemElement;
2334
- p.currentSubDropList.droplist.relayout();
2335
- }
2336
- }
2337
- }
2338
- }
2339
-
2340
- setFocusedItem(item) {
2341
- const p = this._p;
2342
-
2343
- let itemIndex = item._nointeraction ? -1 : this._getItemIndex(item);
2344
-
2345
- const items = p.items;
2346
- if (itemIndex > -1 && items[itemIndex]._nointeraction)
2347
- itemIndex = -1;
2348
-
2349
- return this.setFocusedItemAtIndex(itemIndex);
2350
- }
2351
-
2352
- setFocusedItemByValue(value) {
2353
- return this.setFocusedItemAtIndex(this.itemIndexByValue(value));
2354
- }
2355
-
2356
- setSingleSelectedItemAtIndex(itemIndex, value) {
2357
- const p = this._p;
2358
-
2359
- this.rushRefilter();
2360
-
2361
- let itemEl = null;
2362
- let item;
2363
-
2364
- if (itemIndex > -1 && !p.items[itemIndex]._nointeraction) {
2365
- item = p.items[itemIndex];
2366
- value = item.value;
2367
-
2368
- if (p.filteredItems) {
2369
- itemIndex = p.filteredItems.indexOf(item);
2370
- }
2371
-
2372
- if (itemIndex > -1) {
2373
- itemEl = p.virtualListHelper.getItemElementAt(itemIndex);
2374
- }
2375
- }
2376
-
2377
- this._setSingleSelectedItemEl(itemEl, value);
2378
-
2379
- return this;
2380
- }
2381
-
2382
- setSingleSelectedItem(item) {
2383
- const p = this._p;
2384
-
2385
- let itemIndex = item._nointeraction ? -1 : this._getItemIndex(item);
2386
-
2387
- const items = p.items;
2388
- if (itemIndex > -1 && items[itemIndex]._nointeraction)
2389
- itemIndex = -1;
2390
-
2391
- return this.setSingleSelectedItemAtIndex(itemIndex);
2392
- }
2393
-
2394
- setSingleSelectedItemByValue(value) {
2395
- return this.setSingleSelectedItemAtIndex(this.itemIndexByValue(value), value);
2396
- }
2397
-
2398
- next(event) {
2399
- this._move('next', event);
2400
- }
2401
-
2402
- previous(event) {
2403
- this._move('prev', event);
2404
- }
2405
-
2406
- isFirstItem() {
2407
- const p = this._p;
2408
- const items = p.filteredItems ?? p.items;
2409
- return p.focusItemIndex === 0 && p.focusItemIndex < items.length;
2410
- }
2411
-
2412
- isLastItem() {
2413
- const p = this._p;
2414
- const items = p.filteredItems ?? p.items;
2415
- return p.focusItemIndex > -1 && p.focusItemIndex === items.length - 1;
2416
- }
2417
-
2418
- scrollItemIndexIntoView(itemIndex) {
2419
- const p = this._p;
2420
-
2421
- if (this._hasScroll()) {
2422
- if (p.filteredItems) {
2423
- const item = p.items[itemIndex];
2424
- itemIndex = p.items.indexOf(item);
2425
- }
2426
-
2427
- if (itemIndex !== -1) {
2428
- this._scrollItemIndexIntoView(itemIndex);
2429
- }
2430
- }
2431
-
2432
- return this;
2433
- }
2434
-
2435
- _scrollItemIndexIntoView(itemIndex) {
2436
- const p = this._p;
2437
-
2438
- if (this._hasScroll()) {
2439
- const menuEl = p.menuEl, scrollTop = menuEl.scrollTop;
2440
-
2441
- let itemPos, previousPos = -1;
2442
- let maxIterations = 30; // Some zoom/scroll issues can make it so that it takes almost forever
2443
-
2444
- while (maxIterations-- > 0) {
2445
- itemPos = p.virtualListHelper.getItemPosition(itemIndex);
2446
-
2447
- if (itemPos === previousPos)
2448
- break;
2449
-
2450
- previousPos = itemPos;
2451
-
2452
- let itemSize = p.virtualListHelper.getItemSize(itemIndex);
2453
-
2454
- let listHeight = menuEl.clientHeight;
2455
-
2456
- if (itemPos < scrollTop) {
2457
- menuEl.scrollTop = itemPos;
2458
- } else if (itemPos + itemSize > scrollTop + listHeight) {
2459
- menuEl.scrollTop = itemPos + itemSize - listHeight;
2460
- }
2461
-
2462
- // force update items, until the positions and sizes are final
2463
- p.virtualListHelper.render();
2464
- }
2465
- }
2466
- }
2467
-
2468
- /**
2469
- * Register an event handler
2470
- * @param {(string|'*')?} event
2471
- * @param {function(any)} handler
2472
- * @returns {DropList}
2473
- */
2474
- on(/**string|'*'*/event, /**Function?*/handler) {
2475
- this._p.mitt.on(event, handler);
2476
- return this;
2477
- }
2478
-
2479
- /**
2480
- * Register a one time event handler
2481
- * @param {(string|'*')?} event
2482
- * @param {function(any)} handler
2483
- * @returns {DropList}
2484
- */
2485
- once(/**string|'*'*/event, /**Function?*/handler) {
2486
- let wrapped = (value) => {
2487
- this._p.mitt.off(event, wrapped);
2488
- handler(value);
2489
- };
2490
- this._p.mitt.on(event, wrapped);
2491
- return this;
2492
- }
2493
-
2494
- /**
2495
- * Remove an `handler` for `event`, all events for `event`, or all events completely.
2496
- * @param {(string|'*')?} event
2497
- * @param {function(any)} handler
2498
- * @returns {DropList}
2499
- */
2500
- off(/**(string|'*')?*/event, /**Function?*/handler) {
2501
- if (!event && !event) {
2502
- this._p.mitt.all.clear();
2503
- } else {
2504
- this._p.mitt.off(event, handler);
2505
- }
2506
- return this;
2507
- }
2508
-
2509
- /**
2510
- * Emit an event
2511
- * @param {string} event
2512
- * @param {any} value
2513
- * @returns {DropList}
2514
- */
2515
- emit(/**string|'*'*/event, /**any?*/value) {
2516
- this._p.mitt.emit(event, value);
2517
- return this;
2518
- }
2519
-
2520
- _getItemIndex(item) {
2521
- const p = this._p;
2522
-
2523
- let itemIndex = -1;
2524
-
2525
- if (item) {
2526
- const items = p.filteredItems ?? p.items;
2527
- itemIndex = items.indexOf(item);
2528
- if (itemIndex === -1) {
2529
- let value = (item && item.value !== undefined) ? item.value : item;
2530
- let label = (item && item.label) ? item.label : value;
2531
- itemIndex = this.itemIndexByValueOrLabel(value, label);
2532
- }
2533
- }
2534
-
2535
- return itemIndex;
2536
- }
2537
-
2538
- _setSingleSelectedItemEl(itemEl, value) {
2539
- const p = this._p;
2540
-
2541
- if (p.singleSelectedItemEl) {
2542
- p.singleSelectedItemEl.classList.remove(`${p.baseClassName}__item_selected`);
2543
- p.singleSelectedItemEl = null;
2544
- }
2545
-
2546
- p.singleSelectedValue = value;
2547
-
2548
- if (itemEl && value !== undefined) {
2549
- itemEl.classList.add(`${p.baseClassName}__item_selected`);
2550
- p.singleSelectedItemEl = itemEl;
2551
- }
2552
-
2553
- return this;
2554
- }
2555
-
2556
- /**
2557
- * @param {string} event
2558
- * @param {*} [data]
2559
- * @private
2560
- */
2561
- _trigger(event, data) {
2562
- const p = this._p;
2563
- if (p.on)
2564
- p.on(event, ...(data === undefined ? [] : [data]));
2565
- p.mitt.emit(event, data);
2566
- }
2567
-
2568
- _itemUpAction(event, itemEl) {
2569
- if (closestUntil(event.target, '.requires-pointer-events,button', itemEl)) return;
2570
-
2571
- let p = this._p;
2572
-
2573
- if (!this._mouseHandled) {
2574
-
2575
- this.triggerItemSelection(null, event);
2576
-
2577
- // If we are destroyed in response to a click/select, cease all actions
2578
- if (this[DestroyedSymbol])
2579
- return;
2580
-
2581
- if (document.activeElement !== this.el && p.focusItemEl) {
2582
- clearTimeout(p.blurTimer);
2583
- }
2584
-
2585
- setTimeout(() => {
2586
- this._mouseHandled = false;
2587
- }, 0);
2588
- }
2589
- }
2590
-
2591
- _hookMouseEvents() {
2592
- const p = this._p;
2593
-
2594
- p.sink
2595
- .add(p.el, 'mouseup', (event) => {
2596
- const li = closestUntil(event.target, 'li', event.currentTarget);
2597
- if (!li) return;
2598
-
2599
- if (event.button !== 0) return;
2600
-
2601
- this._itemUpAction(event, li);
2602
- })
2603
- .add(p.el, 'mouseover', (event) => {
2604
- const li = closestUntil(event.target, 'li', event.currentTarget);
2605
- if (!li) return;
2606
-
2607
- this._handleMouseOver(event, li);
2608
- });
2609
- }
2610
-
2611
- _handleMouseOver(event, itemEl) {
2612
- this._focus(event, itemEl, null, true);
2613
- }
2614
-
2615
- _hookTouchEvents() {
2616
- const p = this._p;
2617
-
2618
- let currentTouchId;
2619
-
2620
- p.sink.add(p.el, 'touchstart', (event) => {
2621
- const li = closestUntil(event.target, 'li', event.currentTarget);
2622
- if (!li) return;
2623
-
2624
- if (currentTouchId) return;
2625
- if (closestUntil(event.target, '.requires-pointer-events,button', li)) return;
2626
-
2627
- currentTouchId = event.changedTouches[0].identifier;
2628
-
2629
- // Simulate mouseover event
2630
- this._handleMouseOver(event, li);
2631
-
2632
- // Track scrolling
2633
- let didScroll = false;
2634
- let onScroll = () => {
2635
- didScroll = true;
2636
- };
2637
- let onTouchCancel = () => {
2638
- currentTouchId = null;
2639
- p.sink.remove(null, '.dropdown_touchextra');
2640
- };
2641
-
2642
- let elToTrackScroll = li.parentNode;
2643
- while (elToTrackScroll) {
2644
- p.sink.add(elToTrackScroll, 'scroll.dropdown_touchextra', onScroll);
2645
- elToTrackScroll = elToTrackScroll.parentNode;
2646
- }
2647
- p.sink.add(window, 'scroll.dropdown_touchextra', onScroll);
2648
-
2649
- p.sink.add(window, 'touchcancel.dropdown_touchextra', onTouchCancel);
2650
-
2651
- p.sink.add(p.el, 'touchend.dropdown_touchextra', (event) => {
2652
- const li = closestUntil(event.target, 'li', event.currentTarget);
2653
- if (!li) return onTouchCancel();
2654
-
2655
- let touch = Array.prototype.find.call(event.changedTouches, (touch) => {
2656
- return touch.identifier === currentTouchId;
2657
- });
2658
- if (!touch) return onTouchCancel();
2659
-
2660
- onTouchCancel();
2661
-
2662
- if (!didScroll) {
2663
- this._itemUpAction(event, li);
2664
- event.preventDefault();
2665
- }
2666
- });
2667
- });
2668
- }
2669
-
2670
- _hookFocusEvents() {
2671
- const p = this._p;
2672
-
2673
- p.sink
2674
- .add(p.el, 'focus', event => {
2675
- if (event.target === this.el && p.searchable)
2676
- p.searchInput.focus();
2677
-
2678
- if (event.relatedTarget &&
2679
- this.elContains(event.relatedTarget, true) &&
2680
- this.elContains(event.target, true))
2681
- return;
2682
-
2683
- let itemEl = p.focusItemEl || // focused item
2684
- p.el.firstChild; // or the first item
2685
-
2686
- this._focus(event, itemEl, null, false);
2687
- }, true)
2688
- .add(p.el, 'blur', event => {
2689
- if (event.relatedTarget &&
2690
- this.elContains(event.relatedTarget, true) &&
2691
- this.elContains(event.target, true))
2692
- return;
2693
-
2694
- setTimeout(() => {
2695
- if (this[DestroyedSymbol]) return;
2696
-
2697
- if (document.activeElement && this.elContains(document.activeElement, true)) {
2698
- return;
2699
- }
2700
-
2701
- this._delayBlurItemOnBlur();
2702
- this._trigger('blur', event);
2703
- });
2704
- }, true);
2705
- }
2706
-
2707
- _hookKeyEvents() {
2708
- const p = this._p;
2709
-
2710
- p.sink.add(p.el, 'keydown', evt => this._keydown(evt));
2711
- }
2712
-
2713
- _hookSearchEvents() {
2714
- const p = this._p;
2715
-
2716
- if (!p.searchInput)
2717
- return;
2718
-
2719
- p.sink.add(p.searchInput, 'input', () => {
2720
- p.filterTerm = p.searchInput.value.trim();
2721
- p.filteredItems = null;
2722
-
2723
- this._trigger('search', { value: p.searchInput.value });
2724
- p.throttledRefilterItems();
2725
- });
2726
- }
2727
-
2728
- _keydown(event) {
2729
- const p = this._p;
2730
-
2731
- if (p.keyDownHandler && p.keyDownHandler.call(this, event)) {
2732
- return;
2733
- }
2734
-
2735
- let preventDefault = true;
2736
-
2737
- switch (event.key) {
2738
- case VALUE_PAGE_UP:
2739
- case VALUE_PAGE_DOWN:
2740
- case VALUE_HOME:
2741
- case VALUE_END:
2742
- case VALUE_UP:
2743
- case VALUE_DOWN:
2744
- p.lastKeyWasChar = false;
2745
-
2746
- event.preventDefault();
2747
-
2748
- switch (event.key) {
2749
- case VALUE_PAGE_UP:
2750
- this.previousPage(event);
2751
- break;
2752
- case VALUE_PAGE_DOWN:
2753
- this.nextPage(event);
2754
- break;
2755
- case VALUE_HOME:
2756
- this._move('first', event);
2757
- break;
2758
- case VALUE_END:
2759
- this._move('last', event);
2760
- break;
2761
- case VALUE_UP:
2762
- this.previous(event);
2763
- break;
2764
- case VALUE_DOWN:
2765
- this.next(event);
2766
- break;
2767
- }
2768
- break;
2769
-
2770
- case VALUE_LEFT:
2771
- case VALUE_RIGHT:
2772
- p.lastKeyWasChar = false;
2773
- if (event.key === VALUE_RIGHT && getComputedStyle(event.target).direction !== 'rtl' ||
2774
- event.key === VALUE_LEFT && getComputedStyle(event.target).direction === 'rtl') {
2775
- const items = p.filteredItems ?? p.items;
2776
- let item = items[p.focusItemIndex];
2777
- if (p.focusItemIndex > -1 && item._subitems)
2778
- this._showSublist(item, p.focusItemEl);
2779
- } else {
2780
- if (p.currentSubDropList) {
2781
- this._hideSublist();
2782
- preventDefault = false;
2783
- } else {
2784
- this._trigger('_back_key_pressed');
2785
- }
2786
- }
2787
- break;
2788
-
2789
- case VALUE_ENTER:
2790
- p.lastKeyWasChar = false;
2791
- this.triggerItemSelection(null, event);
2792
- event.preventDefault();
2793
- break;
2794
-
2795
- case VALUE_SPACE:
2796
- if (event.target.tagName === 'BUTTON' ||
2797
- event.target.tagName === 'INPUT' && p.lastKeyWasChar) return;
2798
-
2799
- this.toggleFocusedItem();
2800
- event.preventDefault();
2801
- break;
2802
-
2803
- case VALUE_ESCAPE:
2804
- p.lastKeyWasChar = false;
2805
- event.preventDefault();
2806
- this.hide();
2807
- break;
2808
-
2809
- default: {
2810
- if (event.target.tagName === 'INPUT' ||
2811
- event.target.tagName === 'TEXTAREA') {
2812
- const character = event.key || String.fromCharCode(event.keyCode);
2813
- p.lastKeyWasChar = character.length === 1 || event.key === VALUE_BACK_SPACE;
2814
- }
2815
-
2816
- // Inline search box not available, then support typing to focus by first letters
2817
- if (!p.searchable)
2818
- this._keydownFreeType(event, !this.isVisible());
2819
-
2820
- preventDefault = false;
2821
- }
2822
- }
2823
- }
2824
-
2825
- _keydownFreeType(evt, autoSelect) {
2826
- const p = this._p;
2827
-
2828
- // noinspection JSDeprecatedSymbols
2829
- const character = evt.key || String.fromCharCode(evt.keyCode);
2830
- const isChar = character.length === 1;
2831
- p.lastKeyWasChar = isChar || evt.key === VALUE_BACK_SPACE;
2832
- if (!isChar) return;
2833
-
2834
- clearTimeout(p.filterTimer);
2835
-
2836
- // Accumulate text to find from keystrokes
2837
- let keyword = (p.previousFilter || '') + character;
2838
-
2839
- let regex = new RegExp(`^${escapeRegex(keyword)}`, 'i');
2840
-
2841
- let matchIndex = -1;
2842
- let item;
2843
-
2844
- let focusItemIndex = p.focusItemIndex;
2845
-
2846
- const items = p.filteredItems ?? p.items;
2847
-
2848
- // These are all the possible matches for the text typed in so far
2849
- for (let i = 0, count = items.length; i < count; i++) {
2850
- if (matchIndex !== -1 && i < focusItemIndex)
2851
- continue; // We are only interested in first match + match after the focused item
2852
-
2853
- item = items[i];
2854
- if (regex.test(item.label)) {
2855
- matchIndex = i;
2856
- if (focusItemIndex === -1 || i >= focusItemIndex)
2857
- break;
2858
- }
2859
- }
2860
-
2861
- // Did we find anything?
2862
- if (matchIndex === -1) {
2863
- // No... So start over with this character as the only one.
2864
- keyword = character;
2865
- regex = new RegExp(`^${escapeRegex(keyword)}`, 'i');
2866
-
2867
- for (let i = 0, count = items.length; i < count; i++) {
2868
- if (matchIndex !== -1 && i < focusItemIndex)
2869
- continue; // We are only interested in first match + match after the focused item
2870
-
2871
- item = items[i];
2872
- if (regex.test(item.label)) {
2873
- matchIndex = i;
2874
- if (focusItemIndex === -1 || i >= focusItemIndex)
2875
- break;
2876
- }
2877
- }
2878
- }
2879
-
2880
- if (matchIndex > -1) {
2881
- let next = p.virtualListHelper.getItemElementAt(matchIndex);
2882
- this._focus(evt, next || null, matchIndex, true);
2883
-
2884
- if (autoSelect) {
2885
- this.triggerItemSelection(next ? null : items[matchIndex], evt);
2886
- }
2887
-
2888
- // Record the last filter used
2889
- p.previousFilter = keyword;
2890
-
2891
- // Clear the last filter - a second from now.
2892
- p.filterTimer = setTimeout(() => {
2893
- delete p.previousFilter;
2894
- }, 1000);
2895
-
2896
- } else {
2897
- delete p.previousFilter;
2898
- }
2899
- }
2900
-
2901
- _focus(event, itemEl, itemIndex, openSubitems) {
2902
- const p = this._p;
2903
-
2904
- if (p._isFocusingItem)
2905
- return;
2906
- p._isFocusingItem = true;
2907
-
2908
- if (!itemIndex && itemEl) {
2909
- itemIndex = p.virtualListHelper.getItemIndexFromElement(itemEl);
2910
- }
2911
-
2912
- if (itemIndex > -1 && itemEl?.[ItemSymbol]?.[ItemSymbol] === NoResultsItemSymbol) {
2913
- itemIndex = undefined;
2914
- }
2915
-
2916
- if (itemIndex > -1) {
2917
- this.scrollItemIndexIntoView(itemIndex);
2918
- } else if (itemIndex === undefined) {
2919
- itemEl = null;
2920
- }
2921
-
2922
- let focusItemEl = itemEl || p.virtualListHelper.getItemElementAt(itemIndex);
2923
- if (!focusItemEl || focusItemEl[ItemSymbol]._nointeraction) {
2924
- p._isFocusingItem = false;
2925
- this.blurFocusedItem();
2926
- return;
2927
- }
2928
-
2929
- if (focusItemEl === p.focusItemEl) {
2930
- p._isFocusingItem = false;
2931
- clearTimeout(p.blurTimer);
2932
- return;
2933
- }
2934
-
2935
- this.blurFocusedItem();
2936
-
2937
- focusItemEl.classList.add(`${p.baseClassName}__item_focus`);
2938
- p.focusItemEl = focusItemEl;
2939
- p.focusItemIndex = itemIndex;
2940
-
2941
- const items = p.filteredItems ?? p.items;
2942
- const item = items[itemIndex];
2943
- this._trigger('itemfocus', {
2944
- value: item.value,
2945
- item: item[ItemSymbol] ?? item,
2946
- event: event,
2947
- el: focusItemEl,
2948
- });
2949
-
2950
- p._isFocusingItem = false;
2951
-
2952
- if (openSubitems)
2953
- this._showSublist(item, focusItemEl);
2954
- }
2955
-
2956
- _delayBlurItemOnBlur() {
2957
- if (this[DestroyedSymbol])
2958
- return;
2959
-
2960
- const p = this._p;
2961
-
2962
- if (!p.autoItemBlur)
2963
- return;
2964
-
2965
- clearTimeout(p.blurTimer);
2966
-
2967
- p.blurTimer = setTimeout(() => {
2968
- if (this[DestroyedSymbol]) return;
2969
- this.blurFocusedItem();
2970
- }, p.autoItemBlurDelay);
2971
- }
2972
-
2973
- _move(direction, event) {
2974
- const p = this._p;
2975
-
2976
- let next, nextIndex, directionUp;
2977
- const items = p.filteredItems ?? p.items;
2978
-
2979
- if (direction === 'first') {
2980
- nextIndex = 0;
2981
- directionUp = false;
2982
- } else if (direction === 'last') {
2983
- nextIndex = items.length - 1;
2984
- directionUp = true;
2985
- } else if (direction === 'prev') {
2986
- if (!this.hasFocusedItem())
2987
- return this._move('last', event);
2988
-
2989
- nextIndex = p.focusItemIndex - 1;
2990
- if (nextIndex === -1) {
2991
- nextIndex = items.length - 1;
2992
- }
2993
-
2994
- directionUp = true;
2995
- } else if (direction === 'next') {
2996
- if (!this.hasFocusedItem())
2997
- return this._move('first', event);
2998
-
2999
- nextIndex = p.focusItemIndex + 1;
3000
- if (nextIndex === items.length) {
3001
- nextIndex = 0;
3002
- }
3003
-
3004
- directionUp = false;
3005
- } else if (direction === 'prev_page' || direction === 'next_page') {
3006
-
3007
- if (!this.hasFocusedItem()) {
3008
- return this._move(direction === 'prev_page' ? 'prev' : 'next', event);
3009
- }
3010
-
3011
- if ((direction === 'prev_page' && this.isFirstItem()) ||
3012
- (direction === 'next_page' && this.isLastItem())) return;
3013
-
3014
- if (this._hasScroll()) {
3015
-
3016
- if (p.virtualListHelper.isVirtual()) {
3017
- let visibleItemCount = p.virtualListHelper.getVisibleItemCount();
3018
-
3019
- nextIndex = p.focusItemIndex;
3020
-
3021
- if (direction === 'prev_page') {
3022
- nextIndex -= visibleItemCount;
3023
- } else {
3024
- nextIndex += visibleItemCount;
3025
- }
3026
-
3027
- if (nextIndex < 0) {
3028
- nextIndex = 0;
3029
- } else if (nextIndex >= items.length) {
3030
- nextIndex = items.length;
3031
- }
3032
- } else if (p.focusItemEl) {
3033
- let base = getElementOffset(p.focusItemEl).top;
3034
- let height = getElementHeight(p.el, true);
3035
-
3036
- while (true) {
3037
- next = p.focusItemEl.nextElementSibling;
3038
- if (!next) return;
3039
- if (next.tagName !== 'LI') continue;
3040
-
3041
- if (direction === 'prev_page') {
3042
- if (getElementOffset(next).top - base + height <= 0)
3043
- break;
3044
- } else {
3045
- if (getElementOffset(next).top - base - height >= 0)
3046
- break;
3047
- }
3048
- }
3049
-
3050
- if (next) {
3051
- nextIndex = p.virtualListHelper.getItemIndexFromElement(next);
3052
-
3053
- if (nextIndex === undefined)
3054
- nextIndex = -1;
3055
- }
3056
- }
3057
-
3058
- } else {
3059
- return this._move(direction === 'prev_page' ? 'first' : 'last', event);
3060
- }
3061
-
3062
- directionUp = direction === 'prev_page';
3063
- } else {
3064
- return;
3065
- }
3066
-
3067
- let itemCount = items.length;
3068
-
3069
- if (nextIndex >= itemCount) {
3070
- return;
3071
- }
3072
-
3073
- let item = items[nextIndex];
3074
- // noinspection UnnecessaryLocalVariableJS
3075
- let startedAtIndex = nextIndex;
3076
-
3077
- while (item && item._nointeraction) {
3078
- if (directionUp) {
3079
- nextIndex--;
3080
- if (nextIndex === -1) {
3081
- nextIndex = itemCount;
3082
- }
3083
- } else {
3084
- nextIndex++;
3085
- if (nextIndex === itemCount) {
3086
- nextIndex = 0;
3087
- }
3088
- }
3089
-
3090
- item = items[nextIndex];
3091
-
3092
- if (nextIndex === startedAtIndex) {
3093
- break;
3094
- }
3095
- }
3096
-
3097
- next = p.virtualListHelper.getItemElementAt(nextIndex);
3098
- this._focus(event, next || null, nextIndex, false);
3099
-
3100
- if (!this.isVisible()) {
3101
- this.triggerItemSelection(item, event);
3102
- }
3103
- }
3104
-
3105
- _hasScroll() {
3106
- const p = this._p;
3107
- const menuEl = p.menuEl;
3108
- return menuEl.clientHeight < menuEl.scrollHeight;
3109
- }
3110
-
3111
- _updateGroupStateForItem(item) {
3112
- const p = this._p;
3113
-
3114
- if (!p.multi)
3115
- return this;
3116
-
3117
- if (item._group) {
3118
- // Now loop through children below the group
3119
-
3120
- let affectedCount = 0;
3121
-
3122
- if (p.autoCheckGroupChildren) {
3123
- const items = p.filteredItems ?? p.items;
3124
- let groupIndex = items.indexOf(item);
3125
- const groupLevel = item._level;
3126
-
3127
- for (let i = groupIndex + 1, len = items.length; i < len; i++) {
3128
- let next = items[i];
3129
-
3130
- // Hit the next group, break out
3131
- if ((!next._child && items[i - 1]._child) ||
3132
- (groupLevel === undefined ? next._group || next._level !== undefined : next._level <= groupLevel))
3133
- break;
3134
-
3135
- // No change, skip
3136
- if (!!next._checked === item._checked)
3137
- continue;
3138
-
3139
- // Update state
3140
- next._checked = item._checked;
3141
-
3142
- affectedCount++;
3143
-
3144
- // Update DOM
3145
- let nextEl = p.virtualListHelper.getItemElementAt(i);
3146
- if (nextEl) {
3147
- toggleClass(nextEl, `${p.baseClassName}__item_checked`, item._checked);
3148
- }
3149
-
3150
- // Fire event
3151
- this._trigger('check', {
3152
- value: next.value,
3153
- item: next[ItemSymbol] ?? next,
3154
- checked: next._checked,
3155
- isGroup: next._group,
3156
- isCheckingGroup: true,
3157
- });
3158
- }
3159
- }
3160
-
3161
- // Fire event
3162
- this._trigger('groupcheck', {
3163
- value: item.value,
3164
- item: item[ItemSymbol] ?? item,
3165
- affectedCount: affectedCount,
3166
- });
3167
- } else if (p.groupCount > 0 && p.autoCheckGroupChildren) {
3168
- const items = p.filteredItems ?? p.items;
3169
- let itemIndex = items.indexOf(item);
3170
- let groupIndex = -1;
3171
-
3172
- // Find the group index
3173
- for (let i = itemIndex - 1; i >= 0; i--) {
3174
- if (items[i]._group) {
3175
- groupIndex = i;
3176
- break;
3177
- }
3178
- }
3179
-
3180
- if (groupIndex > -1) {
3181
- this._updateGroupCheckedState(groupIndex, true);
3182
- }
3183
- }
3184
-
3185
- return this;
3186
- }
3187
-
3188
- _updateGroupCheckedState(groupIndex, fireEvents) {
3189
- const p = this._p;
3190
-
3191
- if (!(p.multi && p.autoCheckGroupChildren && groupIndex > -1))
3192
- return this;
3193
-
3194
- const items = p.filteredItems ?? p.items;
3195
- let groupItem = items[groupIndex];
3196
-
3197
- if (!groupItem || !groupItem._group) return this;
3198
-
3199
- let next, hasChecked = false, hasUnchecked = false;
3200
-
3201
- const groupLevel = groupItem._level;
3202
-
3203
- for (let i = groupIndex + 1, len = items.length; i < len; i++) {
3204
- next = items[i];
3205
-
3206
- // Hit the next group, break out
3207
- if ((!next._child && items[i - 1]._child) ||
3208
- (groupLevel === undefined ? next._group || next._level !== undefined : next._level <= groupLevel))
3209
- break;
3210
-
3211
- if (next._checked) {
3212
- hasChecked = true;
3213
- } else if (!next._checked) {
3214
- hasUnchecked = true;
3215
- }
3216
- }
3217
-
3218
- if (!hasChecked && !hasUnchecked) {
3219
- // No items to check or uncheck, keep current state
3220
- return this;
3221
- }
3222
-
3223
- let shouldCheckGroup = hasChecked && !hasUnchecked;
3224
- if (!!groupItem._checked !== shouldCheckGroup) {
3225
- // Update state
3226
- groupItem._checked = shouldCheckGroup;
3227
-
3228
- // Update DOM
3229
- let nextEl = p.virtualListHelper.getItemElementAt(groupIndex);
3230
- if (nextEl) {
3231
- toggleClass(nextEl, `${p.baseClassName}__item_checked`, groupItem._checked);
3232
- }
3233
-
3234
- if (fireEvents) {
3235
- // Fire event
3236
- this._trigger('check', {
3237
- value: groupItem.value,
3238
- item: groupItem[ItemSymbol] ?? groupItem,
3239
- checked: groupItem._checked,
3240
- isGroup: groupItem._group,
3241
- isCheckingGroup: false,
3242
- });
3243
- }
3244
- }
3245
-
3246
- return this;
3247
- }
3248
-
3249
- /**
3250
- * @private
3251
- * @returns {DropList} self
3252
- */
3253
- _measureItem() {
3254
- const p = this._p;
3255
-
3256
- if (p.lastMeasureItemCount !== p.items.length) {
3257
- let longestLabel = p.lastMeasureLongestLabel || 1,
3258
- longestLabelText = p.lastMeasureLongestLabelText || '';
3259
-
3260
- for (let i = 0, items = p.items, count = items.length;
3261
- i < count;
3262
- i++) {
3263
-
3264
- const item = items[i];
3265
- let text = item.label;
3266
- if (text == null)
3267
- text = item.value;
3268
- if (text == null)
3269
- text = '';
3270
-
3271
- let length = text.length;
3272
- if (length > longestLabel) {
3273
- longestLabel = length;
3274
- longestLabelText = text;
3275
- }
3276
- }
3277
-
3278
- p.lastMeasureItemCount = p.items.length;
3279
- p.lastMeasureLongestLabel = longestLabel;
3280
- p.lastMeasureLongestLabelText = longestLabelText;
3281
- }
3282
-
3283
- if (p.estimateWidth || p.virtualListHelper.isVirtual()) {
3284
- p.virtualListHelper.createGhostItemElement(GhostSymbol, true, itemEl => {
3285
- let measureScroll = createElement('span', {
3286
- css: {
3287
- display: 'block',
3288
- width: '100px',
3289
- height: '100px',
3290
- overflow: 'scroll',
3291
- position: 'absolute',
3292
- },
3293
- });
3294
- let measureScrollParent = createElement('span', {
3295
- css: {
3296
- display: 'block',
3297
- position: 'relative',
3298
- width: '0',
3299
- height: '0',
3300
- overflow: 'hidden',
3301
- },
3302
- }, [measureScroll]);
3303
- itemEl.appendChild(measureScrollParent);
3304
- let vertScrollBarWidth = measureScroll.offsetWidth - measureScroll.clientWidth;
3305
- itemEl.removeChild(measureScrollParent);
3306
-
3307
- p.lastMeasureItemWidth = getElementWidth(itemEl, true, true) + vertScrollBarWidth;
3308
- });
3309
- }
3310
-
3311
- return this;
3312
- }
3313
-
3314
- /**
3315
- * Determines whether the list should be in virtual mode, depending on the item count.
3316
- * @param {number?} targetItemCount - item count we are expecting. Defaults to current item count
3317
- * @returns {DropList}
3318
- * @private
3319
- */
3320
- _determineVirtualMode(targetItemCount) {
3321
- const p = this._p;
3322
-
3323
- const items = p.filteredItems ?? p.items;
3324
- if (targetItemCount === undefined) {
3325
- targetItemCount = items.length;
3326
- }
3327
-
3328
- let shouldBeVirtual = targetItemCount >= p.virtualMinItems;
3329
-
3330
- if (shouldBeVirtual !== p.virtualListHelper.isVirtual()) {
3331
- p.virtualListHelper.setVirtual(shouldBeVirtual).render();
3332
- }
3333
-
3334
- return this;
3335
- }
3336
-
3337
- _renderItemContent(item, itemEl) {
3338
- const p = this._p;
3339
-
3340
- // NOTE: a "measure" item will not have full data of original item.
3341
- // so for a custom renderer - we try to send original item, and fallback to our private list item.
3342
-
3343
- const originalItem = item[ItemSymbol];
3344
-
3345
- if (originalItem === NoResultsItemSymbol) {
3346
- if (p.renderNoResultsItem && p.renderNoResultsItem(item, itemEl) !== false) {
3347
- return true;
3348
- }
3349
-
3350
- itemEl.appendChild(createElement('div', {
3351
- class: 'droplist-no-results-content',
3352
- textContent: p.noResultsText,
3353
- }));
3354
- return;
3355
- }
3356
-
3357
- if (!p.renderItem || p.renderItem(originalItem || item, itemEl) === false) {
3358
- itemEl.appendChild(createElement('span', {
3359
- class: `${p.baseClassName}__item_label`,
3360
- textContent: item.label,
3361
- }));
3362
-
3363
- if (p.multi) {
3364
- if (!item._nocheck) {
3365
- itemEl.insertBefore(
3366
- createElement('span', { class: 'checkbox' }),
3367
- itemEl.firstChild,
3368
- );
3369
- }
3370
- }
3371
- }
3372
- }
3373
-
3374
- /**
3375
- *
3376
- * @param {DropList.PositionOptions} [positionOptions=undefined]
3377
- * @returns {number} new outer width
3378
- * @private
3379
- */
3380
- _updateWidth(positionOptions) {
3381
- const p = this._p, el = p.el;
3382
-
3383
- let targetWidth = 0;
3384
-
3385
- if (positionOptions) {
3386
- if (typeof positionOptions.updateWidth === 'number') {
3387
- // Set from width specified
3388
- targetWidth = positionOptions.updateWidth;
3389
- } else if (positionOptions.targetWidth != null) {
3390
- // Set from simulated target width
3391
- targetWidth = positionOptions.updateWidth;
3392
- } else {
3393
- // Measure target
3394
- targetWidth = getElementWidth(positionOptions.target, true, true);
3395
- }
3396
- }
3397
-
3398
- let autoWidth = 0;
3399
- if (!p.useExactTargetWidth || !targetWidth) {
3400
- if (p.estimateWidth || p.virtualListHelper.isVirtual()) {
3401
- autoWidth = p.lastMeasureItemWidth;
3402
- } else {
3403
- el.style.width = ''; // Reset width
3404
- autoWidth = getElementWidth(el, true, true);
3405
- }
3406
- }
3407
-
3408
- let newOuterWidth = Math.max(autoWidth, targetWidth);
3409
-
3410
- setElementWidth(el, newOuterWidth, true, true);
3411
-
3412
- const elComputedStyle = getComputedStyle(el);
3413
- let extraElWidth = (parseFloat(elComputedStyle.borderLeftWidth) || 0) +
3414
- (parseFloat(elComputedStyle.borderRightWidth) || 0)+
3415
- (parseFloat(elComputedStyle.paddingLeft) || 0)+
3416
- (parseFloat(elComputedStyle.paddingRight) || 0);
3417
- let scrollWidth = el.scrollWidth + extraElWidth;
3418
- if (scrollWidth > newOuterWidth) {
3419
- // consider scrollWidth delta
3420
- let delta = scrollWidth - newOuterWidth;
3421
- el.style.width = `${parseFloat(el.style.width) + delta}px`;
3422
- newOuterWidth = scrollWidth;
3423
- }
3424
-
3425
- return newOuterWidth;
3426
- }
3427
- }
3428
-
3429
- export default DropList;
3430
- export { ItemSymbol };
1
+ export { DropList as default, DropListDefaultOptions as DefaultOptions, ItemSymbol } from '../dist/lib.es6.js';