-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathmodal.tsx
638 lines (526 loc) · 19.2 KB
/
modal.tsx
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
// @ts-strict-ignore
import { PropertyValues } from "lit";
import { createRef } from "lit-html/directives/ref.js";
import {
createEvent,
h,
JsxNode,
LitElement,
method,
property,
setAttribute,
state,
} from "@arcgis/lumina";
import { getNearestOverflowAncestor } from "@floating-ui/utils/dom";
import {
ensureId,
focusFirstTabbable,
slotChangeGetAssignedElements,
slotChangeHasAssignedElement,
} from "../../utils/dom";
import {
activateFocusTrap,
connectFocusTrap,
deactivateFocusTrap,
FocusTrap,
FocusTrapComponent,
updateFocusTrapElements,
} from "../../utils/focusTrapComponent";
import {
componentFocusable,
LoadableComponent,
setComponentLoaded,
setUpLoadableComponent,
} from "../../utils/loadable";
import { createObserver } from "../../utils/observers";
import { onToggleOpenCloseComponent, OpenCloseComponent } from "../../utils/openCloseComponent";
import { Kind, Scale } from "../interfaces";
import { getIconScale } from "../../utils/component";
import { logger } from "../../utils/logger";
import { useT9n } from "../../controllers/useT9n";
import T9nStrings from "./assets/t9n/messages.en.json";
import { CSS, ICONS, SLOTS } from "./resources";
import { styles } from "./modal.scss";
declare global {
interface DeclareElements {
"calcite-modal": Modal;
}
}
let totalOpenModals: number = 0;
let initialDocumentOverflowStyle: string = "";
/**
* @deprecated Use the `calcite-dialog` component instead.
* @slot header - A slot for adding header text.
* @slot content - A slot for adding the component's content.
* @slot content-top - A slot for adding content to the component's sticky header, where content remains at the top of the component when scrolling up and down.
* @slot content-bottom - A slot for adding content to the component's sticky footer, where content remains at the bottom of the component when scrolling up and down.
* @slot primary - A slot for adding a primary button.
* @slot secondary - A slot for adding a secondary button.
* @slot back - A slot for adding a back button.
*/
export class Modal
extends LitElement
implements OpenCloseComponent, FocusTrapComponent, LoadableComponent
{
// #region Static Members
static override styles = styles;
// #endregion
// #region Private Properties
private closeButtonEl = createRef<HTMLButtonElement>();
private contentId: string;
private cssVarObserver: MutationObserver = createObserver("mutation", () => {
this.updateSizeCssVars();
});
focusTrap: FocusTrap;
private ignoreOpenChange = false;
private modalContent = createRef<HTMLDivElement>();
private mutationObserver: MutationObserver = createObserver("mutation", () =>
this.updateFocusTrapElements(),
);
private _open = false;
private openEnd = (): void => {
this.setFocus();
this.el.removeEventListener(
"calciteModalOpen",
this.openEnd,
) /* TODO: [MIGRATION] If possible, refactor to use on* JSX prop or this.listen()/this.listenOn() utils - they clean up event listeners automatically, thus prevent memory leaks */;
};
openProp = "opened";
transitionProp = "opacity" as const;
private titleId: string;
transitionEl: HTMLDivElement;
// #endregion
// #region State Properties
@state() contentEl: HTMLElement;
@state() cssHeight: string | number;
@state() cssWidth: string | number;
@state() hasBack = false;
@state() hasContentBottom = false;
@state() hasContentTop = false;
@state() hasFooter = false;
@state() hasPrimary = false;
@state() hasSecondary = false;
@state() titleEl: HTMLElement;
// #endregion
// #region Public Properties
/** Passes a function to run before the component closes. */
@property() beforeClose: (el: Modal["el"]) => Promise<void>;
/** When `true`, disables the component's close button. */
@property({ reflect: true }) closeButtonDisabled = false;
/** When `true`, prevents the component from expanding to the entire screen on mobile devices. */
@property({ reflect: true }) docked: boolean;
/** When `true`, disables the default close on escape behavior. */
@property({ reflect: true }) escapeDisabled = false;
/** When `true`, prevents focus trapping. */
@property({ reflect: true }) focusTrapDisabled = false;
/** Sets the component to always be fullscreen. Overrides `widthScale` and `--calcite-modal-width` / `--calcite-modal-height`. */
@property({ reflect: true }) fullscreen: boolean;
/** Specifies the kind of the component, which will apply to top border. */
@property({ reflect: true }) kind: Extract<
"brand" | "danger" | "info" | "success" | "warning",
Kind
>;
/** Use this property to override individual strings used by the component. */
@property() messageOverrides?: typeof this.messages._overrides;
/**
* Made into a prop for testing purposes only
*
* @private
*/
messages = useT9n<typeof T9nStrings>();
/** When `true`, displays and positions the component. */
@property({ reflect: true })
get open(): boolean {
return this._open;
}
set open(open: boolean) {
const oldOpen = this._open;
if (open !== oldOpen) {
this._open = open;
this.toggleModal(open);
}
}
/**
* We use an internal property to handle styles for when a modal is actually opened, not just when the open attribute is applied. This is a property because we need to apply styles to the host element and to keep the styles present while beforeClose is.
*
* @private
*/
@property({ reflect: true }) opened = false;
/** When `true`, disables the closing of the component when clicked outside. */
@property({ reflect: true }) outsideCloseDisabled = false;
/** Specifies the size of the component. */
@property({ reflect: true }) scale: Scale = "m";
/** Specifies the width of the component. */
@property({ reflect: true }) widthScale: Scale = "m";
// #endregion
// #region Public Methods
/**
* Sets the scroll top of the component's content.
*
* @param top
* @param left
*/
@method()
async scrollContent(top = 0, left = 0): Promise<void> {
if (this.modalContent.value) {
if (this.modalContent.value.scrollTo) {
this.modalContent.value.scrollTo({ top, left, behavior: "smooth" });
} else {
this.modalContent.value.scrollTop = top;
this.modalContent.value.scrollLeft = left;
}
}
}
/** Sets focus on the component's "close" button (the first focusable item). */
@method()
async setFocus(): Promise<void> {
await componentFocusable(this);
focusFirstTabbable(this.el);
}
/** Updates the element(s) that are used within the focus-trap of the component. */
@method()
async updateFocusTrapElements(): Promise<void> {
updateFocusTrapElements(this);
}
// #endregion
// #region Events
/** Fires when the component is requested to be closed and before the closing transition begins. */
calciteModalBeforeClose = createEvent({ cancelable: false });
/** Fires when the component is added to the DOM but not rendered, and before the opening transition begins. */
calciteModalBeforeOpen = createEvent({ cancelable: false });
/** Fires when the component is closed and animation is complete. */
calciteModalClose = createEvent({ cancelable: false });
/** Fires when the component is open and animation is complete. */
calciteModalOpen = createEvent({ cancelable: false });
// #endregion
// #region Lifecycle
constructor() {
super();
this.listen("keydown", this.keyDownHandler);
}
override connectedCallback(): void {
this.mutationObserver?.observe(this.el, { childList: true, subtree: true });
this.cssVarObserver?.observe(this.el, { attributeFilter: ["style"] });
this.updateSizeCssVars();
connectFocusTrap(this, {
focusTrapOptions: {
// scrim closes on click, so we let it take over
clickOutsideDeactivates: false,
escapeDeactivates: (event) => {
if (!event.defaultPrevented && !this.escapeDisabled) {
this.open = false;
event.preventDefault();
}
return false;
},
},
});
}
async load(): Promise<void> {
logger.deprecated("component", {
name: "modal",
removalVersion: 4,
suggested: "dialog",
});
setUpLoadableComponent(this);
// when modal initially renders, if active was set we need to open as watcher doesn't fire
if (this.open) {
this.openModal();
}
}
override willUpdate(changes: PropertyValues<this>): void {
/* TODO: [MIGRATION] First time Lit calls willUpdate(), changes will include not just properties provided by the user, but also any default values your component set.
To account for this semantics change, the checks for (this.hasUpdated || value != defaultValue) was added in this method
Please refactor your code to reduce the need for this check.
Docs: https://qawebgis.esri.com/arcgis-components/?path=/docs/lumina-transition-from-stencil--docs#watching-for-property-changes */
if (changes.has("focusTrapDisabled") && (this.hasUpdated || this.focusTrapDisabled !== false)) {
this.handleFocusTrapDisabled(this.focusTrapDisabled);
}
if (
(changes.has("hasBack") && (this.hasUpdated || this.hasBack !== false)) ||
(changes.has("hasPrimary") && (this.hasUpdated || this.hasPrimary !== false)) ||
(changes.has("hasSecondary") && (this.hasUpdated || this.hasSecondary !== false))
) {
this.hasFooter = this.hasBack || this.hasPrimary || this.hasSecondary;
}
if (changes.has("opened") && (this.hasUpdated || this.opened !== false)) {
this.handleOpenedChange(this.opened);
}
}
loaded(): void {
setComponentLoaded(this);
}
override disconnectedCallback(): void {
this.removeOverflowHiddenClass();
this.mutationObserver?.disconnect();
this.cssVarObserver?.disconnect();
deactivateFocusTrap(this);
}
// #endregion
// #region Private Methods
private keyDownHandler = (event: KeyboardEvent): void => {
const { defaultPrevented, key } = event;
if (
!defaultPrevented &&
this.focusTrapDisabled &&
this.open &&
!this.escapeDisabled &&
key === "Escape"
) {
event.preventDefault();
this.open = false;
}
};
private handleFocusTrapDisabled(focusTrapDisabled: boolean): void {
if (!this.open) {
return;
}
if (focusTrapDisabled) {
deactivateFocusTrap(this);
} else {
activateFocusTrap(this);
}
}
private handleHeaderSlotChange(event: Event): void {
this.titleEl = slotChangeGetAssignedElements<HTMLElement>(event)[0];
}
private handleContentSlotChange(event: Event): void {
this.contentEl = slotChangeGetAssignedElements<HTMLElement>(event)[0];
}
private handleBackSlotChange(event: Event): void {
this.hasBack = slotChangeHasAssignedElement(event);
}
private handlePrimarySlotChange(event: Event): void {
this.hasPrimary = slotChangeHasAssignedElement(event);
}
private handleSecondarySlotChange(event: Event): void {
this.hasSecondary = slotChangeHasAssignedElement(event);
}
private setTransitionEl(el: HTMLDivElement): void {
this.transitionEl = el;
}
onBeforeOpen(): void {
this.transitionEl?.classList.add(CSS.openingActive);
this.calciteModalBeforeOpen.emit();
}
onOpen(): void {
this.transitionEl?.classList.remove(CSS.openingIdle, CSS.openingActive);
this.calciteModalOpen.emit();
activateFocusTrap(this);
}
onBeforeClose(): void {
this.transitionEl?.classList.add(CSS.closingActive);
this.calciteModalBeforeClose.emit();
}
onClose(): void {
this.transitionEl?.classList.remove(CSS.closingIdle, CSS.closingActive);
this.calciteModalClose.emit();
deactivateFocusTrap(this);
}
private toggleModal(value: boolean): void {
if (this.ignoreOpenChange) {
return;
}
if (value) {
this.openModal();
} else {
this.closeModal();
}
}
private handleOpenedChange(value: boolean): void {
const idleClass = value ? CSS.openingIdle : CSS.closingIdle;
this.transitionEl.classList.add(idleClass);
onToggleOpenCloseComponent(this);
}
private handleCloseClick() {
this.open = false;
}
private async openModal(): Promise<void> {
await this.componentOnReady();
this.el.addEventListener(
"calciteModalOpen",
this.openEnd,
) /* TODO: [MIGRATION] If possible, refactor to use on* JSX prop or this.listen()/this.listenOn() utils - they clean up event listeners automatically, thus prevent memory leaks */;
this.opened = true;
this.titleId = ensureId(this.titleEl);
this.contentId = ensureId(this.contentEl);
if (getNearestOverflowAncestor(this.el) === document.body) {
if (totalOpenModals === 0) {
initialDocumentOverflowStyle = document.documentElement.style.overflow;
}
totalOpenModals++;
// use an inline style instead of a utility class to avoid global class declarations.
document.documentElement.style.setProperty("overflow", "hidden");
}
}
private handleOutsideClose(): void {
if (this.outsideCloseDisabled) {
return;
}
this.open = false;
}
private async closeModal(): Promise<void> {
if (this.beforeClose) {
try {
await this.beforeClose(this.el);
} catch {
// close prevented
requestAnimationFrame(() => {
this.ignoreOpenChange = true;
this.open = true;
this.ignoreOpenChange = false;
});
return;
}
}
if (getNearestOverflowAncestor(this.el) === document.body) {
totalOpenModals--;
if (totalOpenModals === 0) {
this.removeOverflowHiddenClass();
}
}
this.opened = false;
}
private removeOverflowHiddenClass(): void {
document.documentElement.style.setProperty("overflow", initialDocumentOverflowStyle);
}
private updateSizeCssVars(): void {
this.cssWidth = getComputedStyle(this.el).getPropertyValue("--calcite-modal-width");
this.cssHeight = getComputedStyle(this.el).getPropertyValue("--calcite-modal-height");
}
private contentTopSlotChangeHandler(event: Event): void {
this.hasContentTop = slotChangeHasAssignedElement(event);
}
private contentBottomSlotChangeHandler(event: Event): void {
this.hasContentBottom = slotChangeHasAssignedElement(event);
}
// #endregion
// #region Rendering
override render(): JsxNode {
/* TODO: [MIGRATION] This used <Host> before. In Stencil, <Host> props overwrite user-provided props. If you don't wish to overwrite user-values, add a check for this.el.hasAttribute() before calling setAttribute() here */
setAttribute(this.el, "aria-describedby", this.contentId);
/* TODO: [MIGRATION] This used <Host> before. In Stencil, <Host> props overwrite user-provided props. If you don't wish to overwrite user-values, add a check for this.el.hasAttribute() before calling setAttribute() here */
setAttribute(this.el, "aria-labelledby", this.titleId);
/* TODO: [MIGRATION] This used <Host> before. In Stencil, <Host> props overwrite user-provided props. If you don't wish to overwrite user-values, replace "=" here with "??=" */
this.el.ariaModal = "true";
/* TODO: [MIGRATION] This used <Host> before. In Stencil, <Host> props overwrite user-provided props. If you don't wish to overwrite user-values, replace "=" here with "??=" */
this.el.role = "dialog";
return (
<div
class={{
[CSS.container]: true,
[CSS.containerOpen]: this.opened,
}}
>
<calcite-scrim class={CSS.scrim} onClick={this.handleOutsideClose} />
{this.renderStyle()}
<div
class={{
[CSS.modal]: true,
}}
ref={this.setTransitionEl}
>
<div class={CSS.header}>
{this.renderCloseButton()}
<header class={CSS.title}>
<slot name={CSS.header} onSlotChange={this.handleHeaderSlotChange} />
</header>
</div>
{this.renderContentTop()}
<div
class={{
[CSS.content]: true,
[CSS.contentNoFooter]: !this.hasFooter,
}}
ref={this.modalContent}
>
<slot name={SLOTS.content} onSlotChange={this.handleContentSlotChange} />
</div>
{this.renderContentBottom()}
{this.renderFooter()}
</div>
</div>
);
}
private renderFooter(): JsxNode {
return (
<div class={CSS.footer} hidden={!this.hasFooter} key="footer">
<span class={CSS.back}>
<slot name={SLOTS.back} onSlotChange={this.handleBackSlotChange} />
</span>
<span class={CSS.secondary}>
<slot name={SLOTS.secondary} onSlotChange={this.handleSecondarySlotChange} />
</span>
<span class={CSS.primary}>
<slot name={SLOTS.primary} onSlotChange={this.handlePrimarySlotChange} />
</span>
</div>
);
}
private renderContentTop(): JsxNode {
return (
<div class={CSS.contentTop} hidden={!this.hasContentTop}>
<slot name={SLOTS.contentTop} onSlotChange={this.contentTopSlotChangeHandler} />
</div>
);
}
private renderContentBottom(): JsxNode {
return (
<div class={CSS.contentBottom} hidden={!this.hasContentBottom}>
<slot name={SLOTS.contentBottom} onSlotChange={this.contentBottomSlotChangeHandler} />
</div>
);
}
private renderCloseButton(): JsxNode {
return !this.closeButtonDisabled ? (
<button
ariaLabel={this.messages.close}
class={CSS.close}
key="button"
onClick={this.handleCloseClick}
ref={this.closeButtonEl}
title={this.messages.close}
>
<calcite-icon icon={ICONS.close} scale={getIconScale(this.scale)} />
</button>
) : null;
}
private renderStyle(): JsxNode {
if (!this.fullscreen && (this.cssWidth || this.cssHeight)) {
return (
<style>
{`.${CSS.container} {
${this.docked && this.cssWidth ? `align-items: center !important;` : ""}
}
.${CSS.modal} {
block-size: ${this.cssHeight ? this.cssHeight : "auto"} !important;
${this.cssWidth ? `inline-size: ${this.cssWidth} !important;` : ""}
${this.cssWidth ? `max-inline-size: ${this.cssWidth} !important;` : ""}
${this.docked ? `border-radius: var(--calcite-border-radius) !important;` : ""}
}
@media screen and (max-width: ${this.cssWidth}) {
.${CSS.container} {
${this.docked ? `align-items: flex-end !important;` : ""}
}
.${CSS.modal} {
max-block-size: 100% !important;
inline-size: 100% !important;
max-inline-size: 100% !important;
min-inline-size: 100% !important;
margin: 0 !important;
${!this.docked ? `block-size: 100% !important;` : ""}
${!this.docked ? `border-radius: 0 !important;` : ""}
${
this.docked
? `border-radius: var(--calcite-border-radius) var(--calcite-border-radius) 0 0 !important;`
: ""
}
}
}
`}
</style>
);
}
}
// #endregion
}