forked from Dogfalo/materialize
-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathmaterialize.mjs
8211 lines (8178 loc) · 309 KB
/
materialize.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Materialize v2.2.2 (https://materializeweb.com)
* Copyright 2014-2025 Materialize
* MIT License (https://raw.githubusercontent.com/materializecss/materialize/master/LICENSE)
*/
/**
* Class with utilitary functions for global usage.
*/
class Utils {
/** Specifies wether tab is pressed or not. */
static tabPressed = false;
/** Specifies wether there is a key pressed. */
static keyDown = false;
/**
* Key maps.
*/
static keys = {
TAB: ['Tab'],
ENTER: ['Enter'],
ESC: ['Escape', 'Esc'],
BACKSPACE: ['Backspace'],
ARROW_UP: ['ArrowUp', 'Up'],
ARROW_DOWN: ['ArrowDown', 'Down'],
ARROW_LEFT: ['ArrowLeft', 'Left'],
ARROW_RIGHT: ['ArrowRight', 'Right'],
DELETE: ['Delete', 'Del']
};
/**
* Detects when a key is pressed.
* @param e Event instance.
*/
static docHandleKeydown(e) {
Utils.keyDown = true;
if ([...Utils.keys.TAB, ...Utils.keys.ARROW_DOWN, ...Utils.keys.ARROW_UP].includes(e.key)) {
Utils.tabPressed = true;
}
}
/**
* Detects when a key is released.
* @param e Event instance.
*/
static docHandleKeyup(e) {
Utils.keyDown = false;
if ([...Utils.keys.TAB, ...Utils.keys.ARROW_DOWN, ...Utils.keys.ARROW_UP].includes(e.key)) {
Utils.tabPressed = false;
}
}
/**
* Detects when document is focused.
* @param e Event instance.
*/
/* eslint-disabled as of required event type condition check */
/* eslint-disable-next-line */
static docHandleFocus(e) {
if (Utils.keyDown) {
document.body.classList.add('keyboard-focused');
}
}
/**
* Detects when document is not focused.
* @param e Event instance.
*/
/* eslint-disabled as of required event type condition check */
/* eslint-disable-next-line */
static docHandleBlur(e) {
document.body.classList.remove('keyboard-focused');
}
/**
* Generates a unique string identifier.
*/
static guid() {
const s4 = () => {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
/**
* Checks for exceeded edges
* @param container Container element.
* @param bounding Bounding rect.
* @param offset Element offset.
*/
static checkWithinContainer(container, bounding, offset) {
const edges = {
top: false,
right: false,
bottom: false,
left: false
};
const containerRect = container.getBoundingClientRect();
// If body element is smaller than viewport, use viewport height instead.
const containerBottom = container === document.body
? Math.max(containerRect.bottom, window.innerHeight)
: containerRect.bottom;
const scrollLeft = container.scrollLeft;
const scrollTop = container.scrollTop;
const scrolledX = bounding.left - scrollLeft;
const scrolledY = bounding.top - scrollTop;
// Check for container and viewport for each edge
if (scrolledX < containerRect.left + offset || scrolledX < offset) {
edges.left = true;
}
if (scrolledX + bounding.width > containerRect.right - offset ||
scrolledX + bounding.width > window.innerWidth - offset) {
edges.right = true;
}
if (scrolledY < containerRect.top + offset || scrolledY < offset) {
edges.top = true;
}
if (scrolledY + bounding.height > containerBottom - offset ||
scrolledY + bounding.height > window.innerHeight - offset) {
edges.bottom = true;
}
return edges;
}
/**
* Checks if element can be aligned in multiple directions.
* @param el Element to be inspected.
* @param container Container element.
* @param bounding Bounding rect.
* @param offset Element offset.
*/
static checkPossibleAlignments(el, container, bounding, offset) {
const canAlign = {
top: true,
right: true,
bottom: true,
left: true,
spaceOnTop: null,
spaceOnRight: null,
spaceOnBottom: null,
spaceOnLeft: null
};
const containerAllowsOverflow = getComputedStyle(container).overflow === 'visible';
const containerRect = container.getBoundingClientRect();
const containerHeight = Math.min(containerRect.height, window.innerHeight);
const containerWidth = Math.min(containerRect.width, window.innerWidth);
const elOffsetRect = el.getBoundingClientRect();
const scrollLeft = container.scrollLeft;
const scrollTop = container.scrollTop;
const scrolledX = bounding.left - scrollLeft;
const scrolledYTopEdge = bounding.top - scrollTop;
const scrolledYBottomEdge = bounding.top + elOffsetRect.height - scrollTop;
// Check for container and viewport for left
canAlign.spaceOnRight = !containerAllowsOverflow
? containerWidth - (scrolledX + bounding.width)
: window.innerWidth - (elOffsetRect.left + bounding.width);
if (canAlign.spaceOnRight < 0) {
canAlign.left = false;
}
// Check for container and viewport for Right
canAlign.spaceOnLeft = !containerAllowsOverflow
? scrolledX - bounding.width + elOffsetRect.width
: elOffsetRect.right - bounding.width;
if (canAlign.spaceOnLeft < 0) {
canAlign.right = false;
}
// Check for container and viewport for Top
canAlign.spaceOnBottom = !containerAllowsOverflow
? containerHeight - (scrolledYTopEdge + bounding.height + offset)
: window.innerHeight - (elOffsetRect.top + bounding.height + offset);
if (canAlign.spaceOnBottom < 0) {
canAlign.top = false;
}
// Check for container and viewport for Bottom
canAlign.spaceOnTop = !containerAllowsOverflow
? scrolledYBottomEdge - (bounding.height - offset)
: elOffsetRect.bottom - (bounding.height + offset);
if (canAlign.spaceOnTop < 0) {
canAlign.bottom = false;
}
return canAlign;
}
/**
* Retrieves target element id from trigger.
* @param trigger Trigger element.
*/
static getIdFromTrigger(trigger) {
let id = trigger.dataset.target;
if (!id) {
id = trigger.getAttribute('href');
return id ? id.slice(1) : '';
}
return id;
}
/**
* Retrieves document scroll postion from top.
*/
static getDocumentScrollTop() {
return window.scrollY || document.documentElement.scrollTop || document.body.scrollTop || 0;
}
/**
* Retrieves document scroll postion from left.
*/
static getDocumentScrollLeft() {
return window.scrollX || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
}
/**
* Fires the given function after a certain ammount of time.
* @param func Function to be fired.
* @param wait Wait time.
* @param options Additional options.
*/
static throttle(func, wait, options = {}) {
let context, args, result, timeout = null, previous = 0;
const later = () => {
previous = options.leading === false ? 0 : new Date().getTime();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return (...args) => {
const now = new Date().getTime();
if (!previous && options.leading === false)
previous = now;
const remaining = wait - (now - previous);
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(this, args);
}
else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
/**
* Renders confirm/close buttons with callback function
*/
static createConfirmationContainer(container, confirmText, cancelText, onConfirm, onCancel) {
const confirmationButtonsContainer = document.createElement('div');
confirmationButtonsContainer.classList.add('confirmation-btns');
container.append(confirmationButtonsContainer);
this.createButton(confirmationButtonsContainer, cancelText, ['btn-cancel'], true, onCancel);
this.createButton(confirmationButtonsContainer, confirmText, ['btn-confirm'], true, onConfirm);
}
/**
* Renders a button with optional callback function
*/
static createButton(container, text, className = [], visibility = true, callback = null) {
className = className.concat(['btn', 'waves-effect', 'text']);
const button = document.createElement('button');
button.className = className.join(' ');
button.style.visibility = visibility ? 'visible' : 'hidden';
button.type = 'button';
button.tabIndex = !!visibility ? 0 : -1;
button.innerText = text;
button.addEventListener('click', callback);
button.addEventListener('keypress', (e) => {
if (Utils.keys.ENTER.includes(e.key))
callback(e);
});
container.append(button);
}
static _setAbsolutePosition(origin, container, position, margin, transitionMovement, align = 'center') {
const originHeight = origin.offsetHeight, originWidth = origin.offsetWidth, containerHeight = container.offsetHeight, containerWidth = container.offsetWidth;
let xMovement = 0, yMovement = 0, targetTop = origin.getBoundingClientRect().top + Utils.getDocumentScrollTop(), targetLeft = origin.getBoundingClientRect().left + Utils.getDocumentScrollLeft();
if (position === 'top') {
targetTop += -containerHeight - margin;
if (align === 'center') {
targetLeft += originWidth / 2 - containerWidth / 2; // This is center align
}
yMovement = -transitionMovement;
}
else if (position === 'right') {
targetTop += originHeight / 2 - containerHeight / 2;
targetLeft = originWidth + margin;
xMovement = transitionMovement;
}
else if (position === 'left') {
targetTop += originHeight / 2 - containerHeight / 2;
targetLeft = -containerWidth - margin;
xMovement = -transitionMovement;
}
else {
targetTop += originHeight + margin;
if (align === 'center') {
targetLeft += originWidth / 2 - containerWidth / 2; // This is center align
}
yMovement = transitionMovement;
}
if (align === 'right') {
targetLeft += originWidth - containerWidth - margin;
}
const newCoordinates = Utils._repositionWithinScreen(targetLeft, targetTop, containerWidth, containerHeight, margin, transitionMovement, align);
container.style.top = newCoordinates.y + 'px';
container.style.left = newCoordinates.x + 'px';
return { x: xMovement, y: yMovement };
}
static _repositionWithinScreen(x, y, width, height, margin, transitionMovement, align) {
const scrollLeft = Utils.getDocumentScrollLeft();
const scrollTop = Utils.getDocumentScrollTop();
let newX = x - scrollLeft;
let newY = y - scrollTop;
const bounding = {
left: newX,
top: newY,
width: width,
height: height
};
let offset;
if (align === 'left' || align == 'center') {
offset = margin + transitionMovement;
}
else if (align === 'right') {
offset = margin - transitionMovement;
}
const edges = Utils.checkWithinContainer(document.body, bounding, offset);
if (edges.left) {
newX = offset;
}
else if (edges.right) {
newX -= newX + width - window.innerWidth;
}
if (edges.top) {
newY = offset;
}
else if (edges.bottom) {
newY -= newY + height - window.innerHeight;
}
return {
x: newX + scrollLeft,
y: newY + scrollTop
};
}
}
/**
* Base class implementation for Materialize components.
*/
class Component {
/**
* The DOM element the plugin was initialized with.
*/
el;
/**
* The options the instance was initialized with.
*/
options;
/**
* Constructs component instance and set everything up.
*/
constructor(el, options, classDef) {
// Display error if el is not a valid HTML Element
if (!(el instanceof HTMLElement)) {
console.error(Error(el + ' is not an HTML Element'));
}
// If exists, destroy and reinitialize in child
const ins = classDef.getInstance(el);
if (!!ins) {
ins.destroy();
}
this.el = el;
}
/**
* Initializes component instances.
* @param els HTML elements.
* @param options Component options.
* @param classDef Class definition.
*/
static init(els, options, classDef) {
let instances = null;
if (els instanceof Element) {
instances = new classDef(els, options);
}
else if (!!els && els.length) {
instances = [];
for (let i = 0; i < els.length; i++) {
instances.push(new classDef(els[i], options));
}
}
return instances;
}
/**
* @returns default options for component instance.
*/
static get defaults() {
return {};
}
/**
* Retrieves component instance for the given element.
* @param el Associated HTML Element.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
static getInstance(el) {
throw new Error('This method must be implemented.');
}
/**
* Destroy plugin instance and teardown.
*/
destroy() {
throw new Error('This method must be implemented.');
}
}
const _defaults$n = {
alignment: 'left',
autoFocus: true,
constrainWidth: true,
container: null,
coverTrigger: true,
closeOnClick: true,
hover: false,
inDuration: 150,
outDuration: 250,
onOpenStart: null,
onOpenEnd: null,
onCloseStart: null,
onCloseEnd: null,
onItemClick: null
};
class Dropdown extends Component {
static _dropdowns = [];
/** ID of the dropdown element. */
id;
/** The DOM element of the dropdown. */
dropdownEl;
/** If the dropdown is open. */
isOpen;
/** If the dropdown content is scrollable. */
isScrollable;
isTouchMoving;
/** The index of the item focused. */
focusedIndex;
filterQuery;
filterTimeout;
constructor(el, options) {
super(el, options, Dropdown);
this.el['M_Dropdown'] = this;
Dropdown._dropdowns.push(this);
this.id = Utils.getIdFromTrigger(el);
this.dropdownEl = document.getElementById(this.id);
this.options = {
...Dropdown.defaults,
...options
};
this.isOpen = false;
this.isScrollable = false;
this.isTouchMoving = false;
this.focusedIndex = -1;
this.filterQuery = [];
this.el.ariaExpanded = 'false';
// Move dropdown-content after dropdown-trigger
this._moveDropdownToElement();
this._makeDropdownFocusable();
this._setupEventHandlers();
}
static get defaults() {
return _defaults$n;
}
/**
* Initializes instances of Dropdown.
* @param els HTML elements.
* @param options Component options.
*/
static init(els, options = {}) {
return super.init(els, options, Dropdown);
}
static getInstance(el) {
return el['M_Dropdown'];
}
destroy() {
this._resetDropdownStyles();
this._removeEventHandlers();
Dropdown._dropdowns.splice(Dropdown._dropdowns.indexOf(this), 1);
this.el['M_Dropdown'] = undefined;
}
_setupEventHandlers() {
// Trigger keydown handler
this.el.addEventListener('keydown', this._handleTriggerKeydown);
// Item click handler
this.dropdownEl?.addEventListener('click', this._handleDropdownClick);
// Hover event handlers
if (this.options.hover) {
this.el.addEventListener('mouseenter', this._handleMouseEnter);
this.el.addEventListener('mouseleave', this._handleMouseLeave);
this.dropdownEl.addEventListener('mouseleave', this._handleMouseLeave);
// Click event handlers
}
else {
this.el.addEventListener('click', this._handleClick);
}
}
_removeEventHandlers() {
this.el.removeEventListener('keydown', this._handleTriggerKeydown);
this.dropdownEl.removeEventListener('click', this._handleDropdownClick);
if (this.options.hover) {
this.el.removeEventListener('mouseenter', this._handleMouseEnter);
this.el.removeEventListener('mouseleave', this._handleMouseLeave);
this.dropdownEl.removeEventListener('mouseleave', this._handleMouseLeave);
}
else {
this.el.removeEventListener('click', this._handleClick);
}
}
_setupTemporaryEventHandlers() {
document.body.addEventListener('click', this._handleDocumentClick);
document.body.addEventListener('touchmove', this._handleDocumentTouchmove);
this.dropdownEl.addEventListener('keydown', this._handleDropdownKeydown);
window.addEventListener('resize', this._handleWindowResize);
}
_removeTemporaryEventHandlers() {
document.body.removeEventListener('click', this._handleDocumentClick);
document.body.removeEventListener('touchmove', this._handleDocumentTouchmove);
this.dropdownEl.removeEventListener('keydown', this._handleDropdownKeydown);
window.removeEventListener('resize', this._handleWindowResize);
}
_handleClick = (e) => {
e.preventDefault();
//this._moveDropdown((<HTMLElement>e.target).closest('li'));
if (this.isOpen) {
this.close();
}
else {
this.open();
}
};
_handleMouseEnter = () => {
//this._moveDropdown((<HTMLElement>e.target).closest('li'));
this.open();
};
_handleMouseLeave = (e) => {
const toEl = e.relatedTarget;
const leaveToDropdownContent = !!toEl.closest('.dropdown-content');
let leaveToActiveDropdownTrigger = false;
const closestTrigger = toEl.closest('.dropdown-trigger');
if (closestTrigger && !!closestTrigger['M_Dropdown'] && closestTrigger['M_Dropdown'].isOpen) {
leaveToActiveDropdownTrigger = true;
}
// Close hover dropdown if mouse did not leave to either active dropdown-trigger or dropdown-content
if (!leaveToActiveDropdownTrigger && !leaveToDropdownContent) {
this.close();
}
};
_handleDocumentClick = (e) => {
const target = e.target;
if (this.options.closeOnClick && target.closest('.dropdown-content') && !this.isTouchMoving) {
// isTouchMoving to check if scrolling on mobile.
this.close();
}
else if (!target.closest('.dropdown-content')) {
// Do this one frame later so that if the element clicked also triggers _handleClick
// For example, if a label for a select was clicked, that we don't close/open the dropdown
setTimeout(() => {
if (this.isOpen) {
this.close();
}
}, 0);
}
this.isTouchMoving = false;
};
_handleTriggerKeydown = (e) => {
// ARROW DOWN OR ENTER WHEN SELECT IS CLOSED - open Dropdown
const arrowDownOrEnter = Utils.keys.ARROW_DOWN.includes(e.key) || Utils.keys.ENTER.includes(e.key);
if (arrowDownOrEnter && !this.isOpen) {
e.preventDefault();
this.open();
}
};
_handleDocumentTouchmove = (e) => {
const target = e.target;
if (target.closest('.dropdown-content')) {
this.isTouchMoving = true;
}
};
_handleDropdownClick = (e) => {
// onItemClick callback
if (typeof this.options.onItemClick === 'function') {
const itemEl = e.target.closest('li');
this.options.onItemClick.call(this, itemEl);
}
};
_handleDropdownKeydown = (e) => {
const arrowUpOrDown = Utils.keys.ARROW_DOWN.includes(e.key) || Utils.keys.ARROW_UP.includes(e.key);
if (Utils.keys.TAB.includes(e.key)) {
e.preventDefault();
this.close();
}
// Navigate down dropdown list
else if (arrowUpOrDown && this.isOpen) {
e.preventDefault();
const direction = Utils.keys.ARROW_DOWN.includes(e.key) ? 1 : -1;
let newFocusedIndex = this.focusedIndex;
let hasFoundNewIndex = false;
do {
newFocusedIndex = newFocusedIndex + direction;
if (!!this.dropdownEl.children[newFocusedIndex] &&
this.dropdownEl.children[newFocusedIndex].tabIndex !== -1) {
hasFoundNewIndex = true;
break;
}
} while (newFocusedIndex < this.dropdownEl.children.length && newFocusedIndex >= 0);
if (hasFoundNewIndex) {
// Remove active class from old element
if (this.focusedIndex >= 0)
this.dropdownEl.children[this.focusedIndex].classList.remove('active');
this.focusedIndex = newFocusedIndex;
this._focusFocusedItem();
}
}
// ENTER selects choice on focused item
else if (Utils.keys.ENTER.includes(e.key) && this.isOpen) {
// Search for <a> and <button>
const focusedElement = this.dropdownEl.children[this.focusedIndex];
const activatableElement = focusedElement?.querySelector('a, button');
// Click a or button tag if exists, otherwise click li tag
if (!!activatableElement) {
activatableElement.click();
}
else if (!!focusedElement) {
if (focusedElement instanceof HTMLElement) {
focusedElement.click();
}
}
}
// Close dropdown on ESC
else if (Utils.keys.ESC.includes(e.key) && this.isOpen) {
e.preventDefault();
this.close();
}
// CASE WHEN USER TYPE LTTERS
const keyText = e.key.toLowerCase();
const isLetter = /[a-zA-Z0-9-_]/.test(keyText);
const specialKeys = [
...Utils.keys.ARROW_DOWN,
...Utils.keys.ARROW_UP,
...Utils.keys.ENTER,
...Utils.keys.ESC,
...Utils.keys.TAB
];
if (isLetter && !specialKeys.includes(e.key)) {
this.filterQuery.push(keyText);
const string = this.filterQuery.join('');
const newOptionEl = Array.from(this.dropdownEl.querySelectorAll('li')).find((el) => el.innerText.toLowerCase().indexOf(string) === 0);
if (newOptionEl) {
this.focusedIndex = [...newOptionEl.parentNode.children].indexOf(newOptionEl);
this._focusFocusedItem();
}
}
this.filterTimeout = setTimeout(this._resetFilterQuery, 1000);
};
_handleWindowResize = () => {
// Only re-place the dropdown if it's still visible
// Accounts for elements hiding via media queries
if (this.el.offsetParent) {
this.recalculateDimensions();
}
};
_resetFilterQuery = () => {
this.filterQuery = [];
};
_resetDropdownStyles() {
this.dropdownEl.style.display = '';
this._resetDropdownPositioningStyles();
this.dropdownEl.style.transform = '';
this.dropdownEl.style.opacity = '';
}
_resetDropdownPositioningStyles() {
this.dropdownEl.style.width = '';
this.dropdownEl.style.height = '';
this.dropdownEl.style.left = '';
this.dropdownEl.style.top = '';
this.dropdownEl.style.transformOrigin = '';
}
_moveDropdownToElement(containerEl = null) {
if (this.options.container) {
this.options.container.append(this.dropdownEl);
return;
}
if (containerEl) {
if (!containerEl.contains(this.dropdownEl))
containerEl.append(this.dropdownEl);
return;
}
this.el.after(this.dropdownEl);
}
_makeDropdownFocusable() {
if (!this.dropdownEl)
return;
this.dropdownEl.popover = '';
// Needed for arrow key navigation
this.dropdownEl.tabIndex = 0;
// Only set tabindex if it hasn't been set by user
Array.from(this.dropdownEl.children).forEach((el) => {
if (!el.getAttribute('tabindex'))
el.setAttribute('tabindex', '0');
});
}
_focusFocusedItem() {
if (this.focusedIndex >= 0 &&
this.focusedIndex < this.dropdownEl.children.length &&
this.options.autoFocus) {
this.dropdownEl.children[this.focusedIndex].focus({
preventScroll: true
});
this.dropdownEl.children[this.focusedIndex].scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'nearest'
});
}
}
_getDropdownPosition(closestOverflowParent) {
// const offsetParentBRect = this.el.offsetParent.getBoundingClientRect();
const triggerBRect = this.el.getBoundingClientRect();
const dropdownBRect = this.dropdownEl.getBoundingClientRect();
let idealHeight = dropdownBRect.height;
let idealWidth = dropdownBRect.width;
let idealXPos = triggerBRect.left - dropdownBRect.left;
let idealYPos = triggerBRect.top - dropdownBRect.top;
const dropdownBounds = {
left: idealXPos,
top: idealYPos,
height: idealHeight,
width: idealWidth
};
const alignments = Utils.checkPossibleAlignments(this.el, closestOverflowParent, dropdownBounds, this.options.coverTrigger ? 0 : triggerBRect.height);
let verticalAlignment = 'top';
let horizontalAlignment = this.options.alignment;
idealYPos += this.options.coverTrigger ? 0 : triggerBRect.height;
// Reset isScrollable
this.isScrollable = false;
if (!alignments.top) {
if (alignments.bottom) {
verticalAlignment = 'bottom';
if (!this.options.coverTrigger) {
idealYPos -= triggerBRect.height;
}
}
else {
this.isScrollable = true;
// Determine which side has most space and cutoff at correct height
idealHeight -= 20; // Add padding when cutoff
if (alignments.spaceOnTop > alignments.spaceOnBottom) {
verticalAlignment = 'bottom';
idealHeight += alignments.spaceOnTop;
idealYPos -= this.options.coverTrigger
? alignments.spaceOnTop - 20
: alignments.spaceOnTop - 20 + triggerBRect.height;
}
else {
idealHeight += alignments.spaceOnBottom;
}
}
}
// If preferred horizontal alignment is possible
if (!alignments[horizontalAlignment]) {
const oppositeAlignment = horizontalAlignment === 'left' ? 'right' : 'left';
if (alignments[oppositeAlignment]) {
horizontalAlignment = oppositeAlignment;
}
else {
// Determine which side has most space and cutoff at correct height
if (alignments.spaceOnLeft > alignments.spaceOnRight) {
horizontalAlignment = 'right';
idealWidth += alignments.spaceOnLeft;
idealXPos -= alignments.spaceOnLeft;
}
else {
horizontalAlignment = 'left';
idealWidth += alignments.spaceOnRight;
}
}
}
if (verticalAlignment === 'bottom') {
idealYPos =
idealYPos - dropdownBRect.height + (this.options.coverTrigger ? triggerBRect.height : 0);
}
if (horizontalAlignment === 'right') {
idealXPos = idealXPos - dropdownBRect.width + triggerBRect.width;
}
return {
x: idealXPos,
y: idealYPos,
verticalAlignment: verticalAlignment,
horizontalAlignment: horizontalAlignment,
height: idealHeight,
width: idealWidth
};
}
_animateIn() {
const duration = this.options.inDuration;
this.dropdownEl.style.transition = 'none';
// from
this.dropdownEl.style.opacity = '0';
this.dropdownEl.style.transform = 'scale(0.3, 0.3)';
setTimeout(() => {
// easeOutQuad (opacity) & easeOutQuint
this.dropdownEl.style.transition = `opacity ${duration}ms ease, transform ${duration}ms ease`;
// to
this.dropdownEl.style.opacity = '1';
this.dropdownEl.style.transform = 'scale(1, 1)';
}, 1);
setTimeout(() => {
if (this.options.autoFocus)
this.dropdownEl.focus();
if (typeof this.options.onOpenEnd === 'function')
this.options.onOpenEnd.call(this, this.el);
}, duration);
}
_animateOut() {
const duration = this.options.outDuration;
// easeOutQuad (opacity) & easeOutQuint
this.dropdownEl.style.transition = `opacity ${duration}ms ease, transform ${duration}ms ease`;
// to
this.dropdownEl.style.opacity = '0';
this.dropdownEl.style.transform = 'scale(0.3, 0.3)';
setTimeout(() => {
this._resetDropdownStyles();
if (typeof this.options.onCloseEnd === 'function')
this.options.onCloseEnd.call(this, this.el);
}, duration);
}
_getClosestAncestor(el, condition) {
let ancestor = el.parentNode;
while (ancestor !== null && ancestor !== document) {
if (condition(ancestor)) {
return ancestor;
}
ancestor = ancestor.parentElement;
}
return null;
}
_placeDropdown() {
// Container here will be closest ancestor with overflow: hidden
let closestOverflowParent = this._getClosestAncestor(this.dropdownEl, (ancestor) => {
return (!['HTML', 'BODY'].includes(ancestor.tagName) &&
getComputedStyle(ancestor).overflow !== 'visible');
});
// Fallback
if (!closestOverflowParent) {
closestOverflowParent = ((!!this.dropdownEl.offsetParent ? this.dropdownEl.offsetParent : this.dropdownEl.parentNode));
}
if (getComputedStyle(closestOverflowParent).position === 'static')
closestOverflowParent.style.position = 'relative';
//this._moveDropdown(closestOverflowParent);
// Set width before calculating positionInfo
const idealWidth = this.options.constrainWidth
? this.el.getBoundingClientRect().width
: this.dropdownEl.getBoundingClientRect().width;
this.dropdownEl.style.width = idealWidth + 'px';
const positionInfo = this._getDropdownPosition(closestOverflowParent);
this.dropdownEl.style.left = positionInfo.x + 'px';
this.dropdownEl.style.top = positionInfo.y + 'px';
this.dropdownEl.style.height = positionInfo.height + 'px';
this.dropdownEl.style.width = positionInfo.width + 'px';
this.dropdownEl.style.transformOrigin = `${positionInfo.horizontalAlignment === 'left' ? '0' : '100%'} ${positionInfo.verticalAlignment === 'top' ? '0' : '100%'}`;
}
/**
* Open dropdown.
*/
open = () => {
if (this.isOpen)
return;
this.isOpen = true;
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, this.el);
}
// Reset styles
this._resetDropdownStyles();
this.dropdownEl.style.display = 'block';
this._placeDropdown();
this._animateIn();
// Do this one frame later so that we don't bind an event handler that's immediately
// called when the event bubbles up to the document and closes the dropdown
setTimeout(() => this._setupTemporaryEventHandlers(), 0);
this.el.ariaExpanded = 'true';
};
/**
* Close dropdown.
*/
close = () => {
if (!this.isOpen)
return;
this.isOpen = false;
this.focusedIndex = -1;
// onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, this.el);
}
this._animateOut();
this._removeTemporaryEventHandlers();
if (this.options.autoFocus) {
this.el.focus();
}
this.el.ariaExpanded = 'false';
};
/**
* While dropdown is open, you can recalculate its dimensions if its contents have changed.
*/
recalculateDimensions = () => {
if (this.isOpen) {
this._resetDropdownPositioningStyles();
this._placeDropdown();
}
};
}
const _defaults$m = {
data: [], // Autocomplete data set
onAutocomplete: null, // Callback for when autocompleted
dropdownOptions: {
// Default dropdown options
autoFocus: false,
closeOnClick: false,
coverTrigger: false
},
minLength: 1, // Min characters before autocomplete starts
isMultiSelect: false,
onSearch: (text, autocomplete) => {
const normSearch = text.toLocaleLowerCase();
autocomplete.setMenuItems(autocomplete.options.data.filter((option) => option.id.toString().toLocaleLowerCase().includes(normSearch)
|| option.text?.toLocaleLowerCase().includes(normSearch)));
},
maxDropDownHeight: '300px',
allowUnsafeHTML: false,
selected: []
};
class Autocomplete extends Component {
/** If the autocomplete is open. */
isOpen;
/** Number of matching autocomplete options. */
count;
/** Index of the current selected option. */
activeIndex;
oldVal;
$active;
_mousedown;
container;
/** Instance of the dropdown plugin for this autocomplete. */
dropdown;
static _keydown;
selectedValues;
menuItems;
constructor(el, options) {
super(el, options, Autocomplete);
this.el['M_Autocomplete'] = this;
this.options = {
...Autocomplete.defaults,
...options
};
this.isOpen = false;
this.count = 0;
this.activeIndex = -1;
this.oldVal = '';
this.selectedValues = this.selectedValues || this.options.selected.map((value) => ({ id: value })) || [];
this.menuItems = this.options.data || [];
this.$active = null;
this._mousedown = false;
this._setupDropdown();
this._setupEventHandlers();
}
static get defaults() {
return _defaults$m;
}
/**
* Initializes instances of Autocomplete.
* @param els HTML elements.
* @param options Component options.
*/
static init(els, options = {}) {
return super.init(els, options, Autocomplete);
}
static getInstance(el) {
return el['M_Autocomplete'];
}
destroy() {
this._removeEventHandlers();
this._removeDropdown();
this.el['M_Autocomplete'] = undefined;
}
_setupEventHandlers() {
this.el.addEventListener('blur', this._handleInputBlur);
this.el.addEventListener('keyup', this._handleInputKeyup);
this.el.addEventListener('focus', this._handleInputFocus);
this.el.addEventListener('keydown', this._handleInputKeydown);
this.el.addEventListener('click', this._handleInputClick);
this.container.addEventListener('mousedown', this._handleContainerMousedownAndTouchstart);
this.container.addEventListener('mouseup', this._handleContainerMouseupAndTouchend);
if (typeof window.ontouchstart !== 'undefined') {
this.container.addEventListener('touchstart', this._handleContainerMousedownAndTouchstart);
this.container.addEventListener('touchend', this._handleContainerMouseupAndTouchend);
}
}
_removeEventHandlers() {
this.el.removeEventListener('blur', this._handleInputBlur);
this.el.removeEventListener('keyup', this._handleInputKeyup);
this.el.removeEventListener('focus', this._handleInputFocus);
this.el.removeEventListener('keydown', this._handleInputKeydown);
this.el.removeEventListener('click', this._handleInputClick);
this.container.removeEventListener('mousedown', this._handleContainerMousedownAndTouchstart);
this.container.removeEventListener('mouseup', this._handleContainerMouseupAndTouchend);
if (typeof window.ontouchstart !== 'undefined') {
this.container.removeEventListener('touchstart', this._handleContainerMousedownAndTouchstart);
this.container.removeEventListener('touchend', this._handleContainerMouseupAndTouchend);