/
cta-modal.ts
937 lines (747 loc) · 23.6 KB
/
cta-modal.ts
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
// ===========================
// START: if "customElements".
// ===========================
if ('customElements' in window) {
// ==========
// Constants.
// ==========
const ACTIVE = 'active';
const ANIMATED = 'animated';
const ANIMATION_DURATION = 250;
const ARIA_LABEL = 'aria-label';
const BLOCK = 'block';
const CLICK = 'click';
const CLOSE = 'close';
const CLOSE_TITLE = 'Close';
const DATA_HIDE = 'data-cta-modal-hide';
const DATA_SHOW = 'data-cta-modal-show';
const EMPTY_STRING = '';
const ENTER = 'enter';
const ESCAPE = 'escape';
const FALSE = 'false';
const FOCUSIN = 'focusin';
const FUNCTION = 'function';
const HIDDEN = 'hidden';
const KEYDOWN = 'keydown';
const MODAL_LABEL_FALLBACK = 'modal';
const NONE = 'none';
const PREFERS_REDUCED_MOTION = '(prefers-reduced-motion: reduce)';
const SPACE = ' ';
const SPACE_REGEX = /\s+/g;
const STATIC = 'static';
const TAB = 'tab';
const TEMPLATE = 'template';
const TRUE = 'true';
const FOCUSABLE_SELECTORS = [
'[contenteditable]',
'[tabindex="0"]:not([disabled])',
'a[href]',
'audio[controls]',
'button:not([disabled])',
'iframe',
"input:not([disabled]):not([type='hidden'])",
'select:not([disabled])',
'summary',
'textarea:not([disabled])',
'video[controls]',
].join(',');
// ======
// Style.
// ======
const STYLE = `
<style>
*,
*:after,
*:before {
box-sizing: border-box;
margin: 0;
padding: 0;
}
@media ${PREFERS_REDUCED_MOTION} {
*,
*:after,
*:before {
animation: none !important;
transition: none !important;
}
}
@keyframes SHOW-OVERLAY {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes SHOW-DIALOG {
0% {
transform: scale(0.95);
}
100% {
transform: scale(1);
}
}
@keyframes HIDE-OVERLAY {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes HIDE-DIALOG {
0% {
transform: scale(1);
}
100% {
transform: scale(0.95);
}
}
.cta-modal__focus-trap {
opacity: 0;
overflow: hidden;
width: 0;
height: 0;
position: fixed;
top: 0;
left: 0;
}
.cta-modal__scroll {
overflow-x: hidden;
overflow-y: auto;
width: 100%;
height: 100%;
z-index: var(--cta-modal-overlay-z-index, 100000);
position: fixed;
top: 0;
left: 0;
}
.cta-modal__overlay {
background-color: var(--cta-modal-overlay-background-color, rgba(0, 0, 0, 0.5));
display: flex;
align-items: center;
justify-content: center;
padding-top: var(--cta-modal-overlay-padding-top, 20px);
padding-left: var(--cta-modal-overlay-padding-left, 20px);
padding-right: var(--cta-modal-overlay-padding-right, 20px);
padding-bottom: var(--cta-modal-overlay-padding-bottom, 20px);
width: 100%;
min-height: 100%;
}
.cta-modal__dialog {
background-color: var(--cta-modal-dialog-background-color, #fff);
border-radius: var(--cta-modal-dialog-border-radius, 5px);
box-shadow: var(--cta-modal-dialog-box-shadow, 0 2px 5px 0 rgba(0, 0, 0, 0.5));
padding-top: var(--cta-modal-dialog-padding-top, 20px);
padding-left: var(--cta-modal-dialog-padding-left, 20px);
padding-right: var(--cta-modal-dialog-padding-right, 20px);
padding-bottom: var(--cta-modal-dialog-padding-bottom, 20px);
width: var(--cta-modal-dialog-width, 500px);
max-width: 100%;
position: relative;
}
[${DATA_SHOW}='true'] .cta-modal__overlay {
animation-duration: ${ANIMATION_DURATION}ms;
animation-name: SHOW-OVERLAY;
}
[${DATA_SHOW}='true'] .cta-modal__dialog {
animation-duration: ${ANIMATION_DURATION}ms;
animation-name: SHOW-DIALOG;
}
[${DATA_HIDE}='true'] .cta-modal__overlay {
animation-duration: ${ANIMATION_DURATION}ms;
animation-name: HIDE-OVERLAY;
opacity: 0;
}
[${DATA_HIDE}='true'] .cta-modal__dialog {
animation-duration: ${ANIMATION_DURATION}ms;
animation-name: HIDE-DIALOG;
transform: scale(0.95);
}
.cta-modal__close {
appearance: none;
touch-action: none;
user-select: none;
border: 0;
padding: 0;
color: var(--cta-modal-close-color, #fff);
background-color: var(--cta-modal-close-background-color, #000);
border-radius: var(--cta-modal-close-border-radius, 50%);
box-shadow: var(--cta-modal-close-box-shadow, 0 0 0 1px #fff);
display: var(--cta-modal-close-display, block);
cursor: pointer;
font-family: var(--cta-modal-close-font-family, 'Arial', sans-serif);
font-size: var(--cta-modal-close-font-size, 23px);
text-align: center;
line-height: var(--cta-modal-close-line-height, 26px);
width: var(--cta-modal-close-width, 26px);
transform: translate(40%, -40%);
position: absolute;
top: 0;
right: 0;
}
.cta-modal__close:hover {
color: var(--cta-modal-close-color-hover, #000);
background-color: var(--cta-modal-close-background-color-hover, #fff);
box-shadow: var(--cta-modal-close-box-shadow-hover, 0 0 0 1px #000);
}
@supports selector(:focus-visible) {
.cta-modal__close:focus-visible {
color: var(--cta-modal-close-color-hover, #000);
background-color: var(--cta-modal-close-background-color-hover, #fff);
box-shadow: var(--cta-modal-close-box-shadow-hover, 0 0 0 1px #000);
}
}
@supports not selector(:focus-visible) {
.cta-modal__close:focus {
color: var(--cta-modal-close-color-hover, #000);
background-color: var(--cta-modal-close-background-color-hover, #fff);
box-shadow: var(--cta-modal-close-box-shadow-hover, 0 0 0 1px #000);
}
}
</style>
`;
// =========
// Template.
// =========
const FOCUS_TRAP = `
<span
aria-hidden='true'
class='cta-modal__focus-trap'
tabindex='0'
></span>
`;
const MODAL = `
<slot name='button'></slot>
<div class='cta-modal__scroll' style='display:none'>
${FOCUS_TRAP}
<div class='cta-modal__overlay'>
<div
aria-modal='true'
class='cta-modal__dialog'
role='dialog'
tabindex='-1'
>
<button
class='cta-modal__close'
type='button'
>×</button>
<slot name='modal'></slot>
</div>
</div>
${FOCUS_TRAP}
</div>
`;
// Get markup.
const markup = [STYLE, MODAL].join(EMPTY_STRING).trim().replace(SPACE_REGEX, SPACE);
// Get template.
const template = document.createElement(TEMPLATE);
template.innerHTML = markup;
// ==========
// Component.
// ==========
class CtaModal extends HTMLElement {
// Read-only types.
readonly _buttonClose: HTMLElement;
readonly _heading: HTMLElement | null;
readonly _modal: HTMLElement;
readonly _modalOverlay: HTMLElement;
readonly _modalScroll: HTMLElement;
readonly _shadow: ShadowRoot;
readonly _slotForButton: HTMLElement | null;
readonly _slotForModal: HTMLElement | null;
// Normal types.
_activeElement: HTMLElement | null = null;
_focusTrapList: NodeListOf<HTMLElement>;
_isActive = false;
_isAnimated = true;
_isHideShow = false;
_isStatic = false;
_timerForHide: number | undefined;
_timerForShow: number | undefined;
// =======================
// Lifecycle: constructor.
// =======================
constructor() {
// Parent constructor.
super();
// Bind context.
this._bind();
// Shadow DOM.
this._shadow = this.attachShadow({ mode: 'closed' });
// Add template.
this._shadow.append(
// Clone node.
template.content.cloneNode(true)
);
// Get slots.
this._slotForButton = this.querySelector("[slot='button']");
this._slotForModal = this.querySelector("[slot='modal']");
// Get elements.
this._heading = this.querySelector('h1, h2, h3, h4, h5, h6');
// Get shadow elements.
this._buttonClose = this._shadow.querySelector('.cta-modal__close') as HTMLElement;
this._focusTrapList = this._shadow.querySelectorAll('.cta-modal__focus-trap');
this._modal = this._shadow.querySelector('.cta-modal__dialog') as HTMLElement;
this._modalOverlay = this._shadow.querySelector('.cta-modal__overlay') as HTMLElement;
this._modalScroll = this._shadow.querySelector('.cta-modal__scroll') as HTMLElement;
// Missing slot?
if (!this._slotForModal) {
window.console.error('Required [slot="modal"] not found inside cta-modal.');
}
// Set animation flag.
this._setAnimationFlag();
// Set close title.
this._setCloseTitle();
// Set modal label.
this._setModalLabel();
// Set static flag.
this._setStaticFlag();
/*
=====
NOTE:
=====
We set this flag last, because the UI visuals within
are contingent on some of the other flags being set.
*/
// Set active flag.
this._setActiveFlag();
}
// ============================
// Lifecycle: watch attributes.
// ============================
static get observedAttributes() {
return [ACTIVE, ANIMATED, CLOSE, STATIC];
}
// ==============================
// Lifecycle: attributes changed.
// ==============================
attributeChangedCallback(name: string, oldValue: string, newValue: string) {
// Different old/new values?
if (oldValue !== newValue) {
// Changed [active="…"] value?
if (name === ACTIVE) {
this._setActiveFlag();
}
// Changed [animated="…"] value?
if (name === ANIMATED) {
this._setAnimationFlag();
}
// Changed [close="…"] value?
if (name === CLOSE) {
this._setCloseTitle();
}
// Changed [static="…"] value?
if (name === STATIC) {
this._setStaticFlag();
}
}
}
// ===========================
// Lifecycle: component mount.
// ===========================
connectedCallback() {
this._addEvents();
}
// =============================
// Lifecycle: component unmount.
// =============================
disconnectedCallback() {
this._removeEvents();
}
// ============================
// Helper: bind `this` context.
// ============================
_bind() {
// Get property names.
const propertyNames = Object.getOwnPropertyNames(
// Get prototype.
Object.getPrototypeOf(this)
) as (keyof CtaModal)[];
// Loop through.
propertyNames.forEach((name) => {
// Bind functions.
if (typeof this[name] === FUNCTION) {
/*
=====
NOTE:
=====
Why use "@ts-expect-error" here?
Calling `*.bind(this)` is a standard practice
when using JavaScript classes. It is necessary
for functions that might change context because
they are interacting directly with DOM elements.
Basically, I am telling TypeScript:
"Let me live my life!"
😎
*/
// @ts-expect-error bind
this[name] = this[name].bind(this);
}
});
}
// ===================
// Helper: add events.
// ===================
_addEvents() {
// Prevent doubles.
this._removeEvents();
document.addEventListener(FOCUSIN, this._handleFocusIn);
document.addEventListener(KEYDOWN, this._handleKeyDown);
this._buttonClose.addEventListener(CLICK, this._handleClickToggle);
this._modalOverlay.addEventListener(CLICK, this._handleClickOverlay);
if (this._slotForButton) {
this._slotForButton.addEventListener(CLICK, this._handleClickToggle);
this._slotForButton.addEventListener(KEYDOWN, this._handleClickToggle);
}
if (this._slotForModal) {
this._slotForModal.addEventListener(CLICK, this._handleClickToggle);
this._slotForModal.addEventListener(KEYDOWN, this._handleClickToggle);
}
}
// ======================
// Helper: remove events.
// ======================
_removeEvents() {
document.removeEventListener(FOCUSIN, this._handleFocusIn);
document.removeEventListener(KEYDOWN, this._handleKeyDown);
this._buttonClose.removeEventListener(CLICK, this._handleClickToggle);
this._modalOverlay.removeEventListener(CLICK, this._handleClickOverlay);
if (this._slotForButton) {
this._slotForButton.removeEventListener(CLICK, this._handleClickToggle);
this._slotForButton.removeEventListener(KEYDOWN, this._handleClickToggle);
}
if (this._slotForModal) {
this._slotForModal.removeEventListener(CLICK, this._handleClickToggle);
this._slotForModal.removeEventListener(KEYDOWN, this._handleClickToggle);
}
}
// ===========================
// Helper: set animation flag.
// ===========================
_setAnimationFlag() {
this._isAnimated = this.getAttribute(ANIMATED) !== FALSE;
}
// ========================
// Helper: add close title.
// ========================
_setCloseTitle() {
// Get title.
const title = this.getAttribute(CLOSE) || CLOSE_TITLE;
// Set title.
this._buttonClose.title = title;
this._buttonClose.setAttribute(ARIA_LABEL, title);
}
// ========================
// Helper: add modal label.
// ========================
_setModalLabel() {
// Set later.
let label = MODAL_LABEL_FALLBACK;
// Heading exists?
if (this._heading) {
// Get text.
label = this._heading.textContent || label;
label = label.trim().replace(SPACE_REGEX, SPACE);
}
// Set label.
this._modal.setAttribute(ARIA_LABEL, label);
}
// ========================
// Helper: set active flag.
// ========================
_setActiveFlag() {
// Get flag.
const isActive = this.getAttribute(ACTIVE) === TRUE;
// Set flag.
this._isActive = isActive;
// Set display.
this._toggleModalDisplay(() => {
// Focus modal?
if (this._isActive) {
this._focusModal();
}
});
}
// ========================
// Helper: set static flag.
// ========================
_setStaticFlag() {
this._isStatic = this.getAttribute(STATIC) === TRUE;
}
// ======================
// Helper: focus element.
// ======================
_focusElement(element: HTMLElement) {
window.requestAnimationFrame(() => {
if (typeof element.focus === FUNCTION) {
element.focus();
}
});
}
// ====================
// Helper: focus modal.
// ====================
_focusModal() {
window.requestAnimationFrame(() => {
this._modal.focus();
this._modalScroll.scrollTo(0, 0);
});
}
// =============================
// Helper: detect outside modal.
// =============================
_isOutsideModal(element?: HTMLElement) {
// Early exit.
if (!this._isActive || !element) {
return false;
}
// Has element?
const hasElement = this.contains(element) || this._modal.contains(element);
// Get boolean.
const bool = !hasElement;
// Expose boolean.
return bool;
}
// ===========================
// Helper: detect motion pref.
// ===========================
_isMotionOkay() {
// Get pref.
const { matches } = window.matchMedia(PREFERS_REDUCED_MOTION);
// Expose boolean.
return this._isAnimated && !matches;
}
// =====================
// Helper: toggle modal.
// =====================
_toggleModalDisplay(callback: () => void) {
// @ts-expect-error boolean
this.setAttribute(ACTIVE, this._isActive);
// Get booleans.
const isModalVisible = this._modalScroll.style.display === BLOCK;
const isMotionOkay = this._isMotionOkay();
// Get delay.
const delay = isMotionOkay ? ANIMATION_DURATION : 0;
// Get scrollbar width.
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
// Get active element.
const activeElement = document.activeElement as HTMLElement;
// Cache active element?
if (this._isActive && activeElement) {
this._activeElement = activeElement;
}
// =============
// Modal active?
// =============
if (this._isActive) {
// Show modal.
this._modalScroll.style.display = BLOCK;
// Hide scrollbar.
document.documentElement.style.overflow = HIDDEN;
// Add placeholder?
if (scrollbarWidth) {
document.documentElement.style.paddingRight = `${scrollbarWidth}px`;
}
// Set flag.
if (isMotionOkay) {
this._isHideShow = true;
this._modalScroll.setAttribute(DATA_SHOW, TRUE);
}
// Fire callback.
callback();
// Await CSS animation.
this._timerForShow = window.setTimeout(() => {
// Clear.
clearTimeout(this._timerForShow);
// Remove flag.
this._isHideShow = false;
this._modalScroll.removeAttribute(DATA_SHOW);
// Delay.
}, delay);
/*
=====
NOTE:
=====
We want to ensure that the modal is currently
visible, because we do not want to put scroll
back on the `<html>` element unnecessarily.
The reason is that another `<cta-modal>` in
the page might have been pre-rendered with an
[active="true"] attribute. If so, we want to
leave the page's overflow value alone.
*/
} else if (isModalVisible) {
// Set flag.
if (isMotionOkay) {
this._isHideShow = true;
this._modalScroll.setAttribute(DATA_HIDE, TRUE);
}
// Fire callback?
callback();
// Await CSS animation.
this._timerForHide = window.setTimeout(() => {
// Clear.
clearTimeout(this._timerForHide);
// Remove flag.
this._isHideShow = false;
this._modalScroll.removeAttribute(DATA_HIDE);
// Hide modal.
this._modalScroll.style.display = NONE;
// Show scrollbar.
document.documentElement.style.overflow = EMPTY_STRING;
// Remove placeholder.
document.documentElement.style.paddingRight = EMPTY_STRING;
// Delay.
}, delay);
}
}
// =====================
// Event: overlay click.
// =====================
_handleClickOverlay(event: MouseEvent) {
// Early exit.
if (this._isHideShow || this._isStatic) {
return;
}
// Get layer.
const target = event.target as HTMLElement;
// Outside modal?
if (target.classList.contains('cta-modal__overlay')) {
this._handleClickToggle();
}
}
// ====================
// Event: toggle modal.
// ====================
_handleClickToggle(event?: MouseEvent | KeyboardEvent) {
// Set later.
let key = EMPTY_STRING;
let target = null;
// Event exists?
if (event) {
if (event.target) {
target = event.target as HTMLElement;
}
// Get key.
if ((event as KeyboardEvent).key) {
key = (event as KeyboardEvent).key;
key = key.toLowerCase();
}
}
// Set later.
let button;
// Target exists?
if (target) {
// Direct click.
if (target.classList.contains('cta-modal__close')) {
button = target as HTMLButtonElement;
// Delegated click.
} else if (typeof target.closest === FUNCTION) {
button = target.closest('.cta-modal-toggle') as HTMLButtonElement;
}
}
// Get booleans.
const isValidEvent = event && typeof event.preventDefault === FUNCTION;
const isValidClick = button && isValidEvent && !key;
const isValidKey = button && isValidEvent && [ENTER, SPACE].includes(key);
const isButtonDisabled = button && button.disabled;
const isButtonMissing = isValidEvent && !button;
const isWrongKeyEvent = key && !isValidKey;
// Early exit.
if (isButtonDisabled || isButtonMissing || isWrongKeyEvent) {
return;
}
// Prevent default?
if (isValidKey || isValidClick) {
event.preventDefault();
}
// Set flag.
this._isActive = !this._isActive;
// Set display.
this._toggleModalDisplay(() => {
// Focus modal?
if (this._isActive) {
this._focusModal();
// Return focus?
} else if (this._activeElement) {
this._focusElement(this._activeElement);
}
});
}
// =========================
// Event: focus in document.
// =========================
_handleFocusIn() {
// Early exit.
if (!this._isActive) {
return;
}
// prettier-ignore
const activeElement = (
// Get active element.
this._shadow.activeElement ||
document.activeElement
) as HTMLElement;
// Get booleans.
const isFocusTrap1 = activeElement === this._focusTrapList[0];
const isFocusTrap2 = activeElement === this._focusTrapList[1];
// Set later.
let focusListReal: HTMLElement[] = [];
// Slot exists?
if (this._slotForModal) {
// Get "real" elements.
focusListReal = Array.from(
this._slotForModal.querySelectorAll(FOCUSABLE_SELECTORS)
) as HTMLElement[];
}
// Get "shadow" elements.
const focusListShadow = Array.from(
this._modal.querySelectorAll(FOCUSABLE_SELECTORS)
) as HTMLElement[];
// Get "total" elements.
const focusListTotal = focusListShadow.concat(focusListReal);
// Get first & last items.
const focusItemFirst = focusListTotal[0];
const focusItemLast = focusListTotal[focusListTotal.length - 1];
// Focus trap: above?
if (isFocusTrap1 && focusItemLast) {
this._focusElement(focusItemLast);
// Focus trap: below?
} else if (isFocusTrap2 && focusItemFirst) {
this._focusElement(focusItemFirst);
// Outside modal?
} else if (this._isOutsideModal(activeElement)) {
this._focusModal();
}
}
// =================
// Event: key press.
// =================
_handleKeyDown({ key }: KeyboardEvent) {
// Early exit.
if (!this._isActive) {
return;
}
// Get key.
key = key.toLowerCase();
// Escape key?
if (key === ESCAPE && !this._isHideShow && !this._isStatic) {
this._handleClickToggle();
}
// Tab key?
if (key === TAB) {
this._handleFocusIn();
}
}
}
// ===============
// Define element.
// ===============
window.addEventListener('DOMContentLoaded', () => {
window.customElements.define('cta-modal', CtaModal);
});
}
// =========================
// END: if "customElements".
// =========================