@danielgindi/selectbox 2.0.56 → 2.0.58

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