-
Notifications
You must be signed in to change notification settings - Fork 13.5k
/
modal.tsx
1025 lines (899 loc) · 32.9 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
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
import type { ComponentInterface, EventEmitter } from '@stencil/core';
import { Component, Element, Event, Host, Method, Prop, State, Watch, h, writeTask } from '@stencil/core';
import { findIonContent, printIonContentErrorMsg } from '@utils/content';
import { CoreDelegate, attachComponent, detachComponent } from '@utils/framework-delegate';
import { raf, inheritAttributes, hasLazyBuild } from '@utils/helpers';
import type { Attributes } from '@utils/helpers';
import { createLockController } from '@utils/lock-controller';
import { printIonWarning } from '@utils/logging';
import { Style as StatusBarStyle, StatusBar } from '@utils/native/status-bar';
import {
GESTURE,
BACKDROP,
dismiss,
eventMethod,
prepareOverlay,
present,
createTriggerController,
setOverlayId,
FOCUS_TRAP_DISABLE_CLASS,
} from '@utils/overlays';
import { getClassMap } from '@utils/theme';
import { deepReady, waitForMount } from '@utils/transition';
import { config } from '../../global/config';
import { getIonMode } from '../../global/ionic-global';
import type {
Animation,
AnimationBuilder,
ComponentProps,
ComponentRef,
FrameworkDelegate,
Gesture,
OverlayInterface,
} from '../../interface';
import { KEYBOARD_DID_OPEN } from '../../utils/keyboard/keyboard';
import type { OverlayEventDetail } from '../../utils/overlays-interface';
import { iosEnterAnimation } from './animations/ios.enter';
import { iosLeaveAnimation } from './animations/ios.leave';
import { mdEnterAnimation } from './animations/md.enter';
import { mdLeaveAnimation } from './animations/md.leave';
import type { MoveSheetToBreakpointOptions } from './gestures/sheet';
import { createSheetGesture } from './gestures/sheet';
import { createSwipeToCloseGesture } from './gestures/swipe-to-close';
import type { ModalBreakpointChangeEventDetail, ModalHandleBehavior } from './modal-interface';
import { setCardStatusBarDark, setCardStatusBarDefault } from './utils';
// TODO(FW-2832): types
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot - Content is placed inside of the `.modal-content` element.
*
* @part backdrop - The `ion-backdrop` element.
* @part content - The wrapper element for the default slot.
* @part handle - The handle that is displayed at the top of the sheet modal when `handle="true"`.
*/
@Component({
tag: 'ion-modal',
styleUrls: {
ios: 'modal.ios.scss',
md: 'modal.md.scss',
},
shadow: true,
})
export class Modal implements ComponentInterface, OverlayInterface {
private readonly lockController = createLockController();
private readonly triggerController = createTriggerController();
private gesture?: Gesture;
private coreDelegate: FrameworkDelegate = CoreDelegate();
private sheetTransition?: Promise<any>;
private isSheetModal = false;
private currentBreakpoint?: number;
private wrapperEl?: HTMLElement;
private backdropEl?: HTMLIonBackdropElement;
private sortedBreakpoints?: number[];
private keyboardOpenCallback?: () => void;
private moveSheetToBreakpoint?: (options: MoveSheetToBreakpointOptions) => Promise<void>;
private inheritedAttributes: Attributes = {};
private statusBarStyle?: StatusBarStyle;
private inline = false;
private workingDelegate?: FrameworkDelegate;
// Reference to the user's provided modal content
private usersElement?: HTMLElement;
// Whether or not modal is being dismissed via gesture
private gestureAnimationDismissing = false;
lastFocus?: HTMLElement;
animation?: Animation;
@State() presented = false;
@Element() el!: HTMLIonModalElement;
/** @internal */
@Prop() hasController = false;
/** @internal */
@Prop() overlayIndex!: number;
/** @internal */
@Prop() delegate?: FrameworkDelegate;
/**
* If `true`, the keyboard will be automatically dismissed when the overlay is presented.
*/
@Prop() keyboardClose = true;
/**
* Animation to use when the modal is presented.
*/
@Prop() enterAnimation?: AnimationBuilder;
/**
* Animation to use when the modal is dismissed.
*/
@Prop() leaveAnimation?: AnimationBuilder;
/**
* The breakpoints to use when creating a sheet modal. Each value in the
* array must be a decimal between 0 and 1 where 0 indicates the modal is fully
* closed and 1 indicates the modal is fully open. Values are relative
* to the height of the modal, not the height of the screen. One of the values in this
* array must be the value of the `initialBreakpoint` property.
* For example: [0, .25, .5, 1]
*/
@Prop() breakpoints?: number[];
/**
* A decimal value between 0 and 1 that indicates the
* initial point the modal will open at when creating a
* sheet modal. This value must also be listed in the
* `breakpoints` array.
*/
@Prop() initialBreakpoint?: number;
/**
* A decimal value between 0 and 1 that indicates the
* point after which the backdrop will begin to fade in
* when using a sheet modal. Prior to this point, the
* backdrop will be hidden and the content underneath
* the sheet can be interacted with. This value is exclusive
* meaning the backdrop will become active after the value
* specified.
*/
@Prop() backdropBreakpoint = 0;
/**
* The horizontal line that displays at the top of a sheet modal. It is `true` by default when
* setting the `breakpoints` and `initialBreakpoint` properties.
*/
@Prop() handle?: boolean;
/**
* The interaction behavior for the sheet modal when the handle is pressed.
*
* Defaults to `"none"`, which means the modal will not change size or position when the handle is pressed.
* Set to `"cycle"` to let the modal cycle between available breakpoints when pressed.
*
* Handle behavior is unavailable when the `handle` property is set to `false` or
* when the `breakpoints` property is not set (using a fullscreen or card modal).
*/
@Prop() handleBehavior?: ModalHandleBehavior = 'none';
/**
* The component to display inside of the modal.
* @internal
*/
@Prop() component?: ComponentRef;
/**
* The data to pass to the modal component.
* @internal
*/
@Prop() componentProps?: ComponentProps;
/**
* Additional classes to apply for custom CSS. If multiple classes are
* provided they should be separated by spaces.
* @internal
*/
@Prop() cssClass?: string | string[];
/**
* If `true`, the modal will be dismissed when the backdrop is clicked.
*/
@Prop() backdropDismiss = true;
/**
* If `true`, a backdrop will be displayed behind the modal.
* This property controls whether or not the backdrop
* darkens the screen when the modal is presented.
* It does not control whether or not the backdrop
* is active or present in the DOM.
*/
@Prop() showBackdrop = true;
/**
* If `true`, the modal will animate.
*/
@Prop() animated = true;
/**
* The element that presented the modal. This is used for card presentation effects
* and for stacking multiple modals on top of each other. Only applies in iOS mode.
*/
@Prop() presentingElement?: HTMLElement;
/**
* Additional attributes to pass to the modal.
*/
@Prop() htmlAttributes?: { [key: string]: any };
/**
* If `true`, the modal will open. If `false`, the modal will close.
* Use this if you need finer grained control over presentation, otherwise
* just use the modalController or the `trigger` property.
* Note: `isOpen` will not automatically be set back to `false` when
* the modal dismisses. You will need to do that in your code.
*/
@Prop() isOpen = false;
@Watch('isOpen')
onIsOpenChange(newValue: boolean, oldValue: boolean) {
if (newValue === true && oldValue === false) {
this.present();
} else if (newValue === false && oldValue === true) {
this.dismiss();
}
}
/**
* An ID corresponding to the trigger element that
* causes the modal to open when clicked.
*/
@Prop() trigger: string | undefined;
@Watch('trigger')
triggerChanged() {
const { trigger, el, triggerController } = this;
if (trigger) {
triggerController.addClickListener(el, trigger);
}
}
/**
* If `true`, the component passed into `ion-modal` will
* automatically be mounted when the modal is created. The
* component will remain mounted even when the modal is dismissed.
* However, the component will be destroyed when the modal is
* destroyed. This property is not reactive and should only be
* used when initially creating a modal.
*
* Note: This feature only applies to inline modals in JavaScript
* frameworks such as Angular, React, and Vue.
*/
@Prop() keepContentsMounted = false;
/**
* If `true`, focus will not be allowed to move outside of this overlay.
* If `false`, focus will be allowed to move outside of the overlay.
*
* In most scenarios this property should remain set to `true`. Setting
* this property to `false` can cause severe accessibility issues as users
* relying on assistive technologies may be able to move focus into
* a confusing state. We recommend only setting this to `false` when
* absolutely necessary.
*
* Developers may want to consider disabling focus trapping if this
* overlay presents a non-Ionic overlay from a 3rd party library.
* Developers would disable focus trapping on the Ionic overlay
* when presenting the 3rd party overlay and then re-enable
* focus trapping when dismissing the 3rd party overlay and moving
* focus back to the Ionic overlay.
*/
@Prop() focusTrap = true;
/**
* Determines whether or not a modal can dismiss
* when calling the `dismiss` method.
*
* If the value is `true` or the value's function returns `true`, the modal will close when trying to dismiss.
* If the value is `false` or the value's function returns `false`, the modal will not close when trying to dismiss.
*
* See https://ionicframework.com/docs/troubleshooting/runtime#accessing-this
* if you need to access `this` from within the callback.
*/
@Prop() canDismiss: boolean | ((data?: any, role?: string) => Promise<boolean>) = true;
/**
* Emitted after the modal has presented.
*/
@Event({ eventName: 'ionModalDidPresent' }) didPresent!: EventEmitter<void>;
/**
* Emitted before the modal has presented.
*/
@Event({ eventName: 'ionModalWillPresent' }) willPresent!: EventEmitter<void>;
/**
* Emitted before the modal has dismissed.
*/
@Event({ eventName: 'ionModalWillDismiss' }) willDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the modal has dismissed.
*/
@Event({ eventName: 'ionModalDidDismiss' }) didDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the modal breakpoint has changed.
*/
@Event() ionBreakpointDidChange!: EventEmitter<ModalBreakpointChangeEventDetail>;
/**
* Emitted after the modal has presented.
* Shorthand for ionModalDidPresent.
*/
@Event({ eventName: 'didPresent' }) didPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the modal has presented.
* Shorthand for ionModalWillPresent.
*/
@Event({ eventName: 'willPresent' }) willPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the modal has dismissed.
* Shorthand for ionModalWillDismiss.
*/
@Event({ eventName: 'willDismiss' }) willDismissShorthand!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the modal has dismissed.
* Shorthand for ionModalDidDismiss.
*/
@Event({ eventName: 'didDismiss' }) didDismissShorthand!: EventEmitter<OverlayEventDetail>;
/**
* Emitted before the modal has presented, but after the component
* has been mounted in the DOM.
* This event exists so iOS can run the entering
* transition properly
*
* @internal
*/
@Event() ionMount!: EventEmitter<void>;
breakpointsChanged(breakpoints: number[] | undefined) {
if (breakpoints !== undefined) {
this.sortedBreakpoints = breakpoints.sort((a, b) => a - b);
}
}
connectedCallback() {
const { el } = this;
prepareOverlay(el);
this.triggerChanged();
}
disconnectedCallback() {
this.triggerController.removeClickListener();
}
componentWillLoad() {
const { breakpoints, initialBreakpoint, el, htmlAttributes } = this;
const isSheetModal = (this.isSheetModal = breakpoints !== undefined && initialBreakpoint !== undefined);
const attributesToInherit = ['aria-label', 'role'];
this.inheritedAttributes = inheritAttributes(el, attributesToInherit);
/**
* When using a controller modal you can set attributes
* using the htmlAttributes property. Since the above attributes
* need to be inherited inside of the modal, we need to look
* and see if these attributes are being set via htmlAttributes.
*
* We could alternatively move this to componentDidLoad to simplify the work
* here, but we'd then need to make inheritedAttributes a State variable,
* thus causing another render to always happen after the first render.
*/
if (htmlAttributes !== undefined) {
attributesToInherit.forEach((attribute) => {
const attributeValue = htmlAttributes[attribute];
if (attributeValue) {
/**
* If an attribute we need to inherit was
* set using htmlAttributes then add it to
* inheritedAttributes and remove it from htmlAttributes.
* This ensures the attribute is inherited and not
* set on the host.
*
* In this case, if an inherited attribute is set
* on the host element and using htmlAttributes then
* htmlAttributes wins, but that's not a pattern that we recommend.
* The only time you'd need htmlAttributes is when using modalController.
*/
this.inheritedAttributes = {
...this.inheritedAttributes,
[attribute]: htmlAttributes[attribute],
};
delete htmlAttributes[attribute];
}
});
}
if (isSheetModal) {
this.currentBreakpoint = this.initialBreakpoint;
}
if (breakpoints !== undefined && initialBreakpoint !== undefined && !breakpoints.includes(initialBreakpoint)) {
printIonWarning('Your breakpoints array must include the initialBreakpoint value.');
}
if (!this.htmlAttributes?.id) {
setOverlayId(this.el);
}
}
componentDidLoad() {
/**
* If modal was rendered with isOpen="true"
* then we should open modal immediately.
*/
if (this.isOpen === true) {
raf(() => this.present());
}
this.breakpointsChanged(this.breakpoints);
/**
* When binding values in frameworks such as Angular
* it is possible for the value to be set after the Web Component
* initializes but before the value watcher is set up in Stencil.
* As a result, the watcher callback may not be fired.
* We work around this by manually calling the watcher
* callback when the component has loaded and the watcher
* is configured.
*/
this.triggerChanged();
}
/**
* Determines whether or not an overlay
* is being used inline or via a controller/JS
* and returns the correct delegate.
* By default, subsequent calls to getDelegate
* will use a cached version of the delegate.
* This is useful for calling dismiss after
* present so that the correct delegate is given.
*/
private getDelegate(force = false) {
if (this.workingDelegate && !force) {
return {
delegate: this.workingDelegate,
inline: this.inline,
};
}
/**
* If using overlay inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps.
* If a developer has presented this component
* via a controller, then we can assume
* the component is already in the
* correct place.
*/
const parentEl = this.el.parentNode as HTMLElement | null;
const inline = (this.inline = parentEl !== null && !this.hasController);
const delegate = (this.workingDelegate = inline ? this.delegate || this.coreDelegate : this.delegate);
return { inline, delegate };
}
/**
* Determines whether or not the
* modal is allowed to dismiss based
* on the state of the canDismiss prop.
*/
private async checkCanDismiss(data?: any, role?: string) {
const { canDismiss } = this;
if (typeof canDismiss === 'function') {
return canDismiss(data, role);
}
return canDismiss;
}
/**
* Present the modal overlay after it has been created.
*/
@Method()
async present(): Promise<void> {
const unlock = await this.lockController.lock();
if (this.presented) {
unlock();
return;
}
const { presentingElement, el } = this;
/**
* If the modal is presented multiple times (inline modals), we
* need to reset the current breakpoint to the initial breakpoint.
*/
this.currentBreakpoint = this.initialBreakpoint;
const { inline, delegate } = this.getDelegate(true);
/**
* Emit ionMount so JS Frameworks have an opportunity
* to add the child component to the DOM. The child
* component will be assigned to this.usersElement below.
*/
this.ionMount.emit();
this.usersElement = await attachComponent(delegate, el, this.component, ['ion-page'], this.componentProps, inline);
/**
* When using the lazy loaded build of Stencil, we need to wait
* for every Stencil component instance to be ready before presenting
* otherwise there can be a flash of unstyled content. With the
* custom elements bundle we need to wait for the JS framework
* mount the inner contents of the overlay otherwise WebKit may
* get the transition incorrect.
*/
if (hasLazyBuild(el)) {
await deepReady(this.usersElement);
/**
* If keepContentsMounted="true" then the
* JS Framework has already mounted the inner
* contents so there is no need to wait.
* Otherwise, we need to wait for the JS
* Framework to mount the inner contents
* of this component.
*/
} else if (!this.keepContentsMounted) {
await waitForMount();
}
writeTask(() => this.el.classList.add('show-modal'));
const hasCardModal = presentingElement !== undefined;
/**
* We need to change the status bar at the
* start of the animation so that it completes
* by the time the card animation is done.
*/
if (hasCardModal && getIonMode(this) === 'ios') {
// Cache the original status bar color before the modal is presented
this.statusBarStyle = await StatusBar.getStyle();
setCardStatusBarDark();
}
await present<ModalPresentOptions>(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation, {
presentingEl: presentingElement,
currentBreakpoint: this.initialBreakpoint,
backdropBreakpoint: this.backdropBreakpoint,
});
/* tslint:disable-next-line */
if (typeof window !== 'undefined') {
/**
* This needs to be setup before any
* non-transition async work so it can be dereferenced
* in the dismiss method. The dismiss method
* only waits for the entering transition
* to finish. It does not wait for all of the `present`
* method to resolve.
*/
this.keyboardOpenCallback = () => {
if (this.gesture) {
/**
* When the native keyboard is opened and the webview
* is resized, the gesture implementation will become unresponsive
* and enter a free-scroll mode.
*
* When the keyboard is opened, we disable the gesture for
* a single frame and re-enable once the contents have repositioned
* from the keyboard placement.
*/
this.gesture.enable(false);
raf(() => {
if (this.gesture) {
this.gesture.enable(true);
}
});
}
};
window.addEventListener(KEYBOARD_DID_OPEN, this.keyboardOpenCallback);
}
if (this.isSheetModal) {
this.initSheetGesture();
} else if (hasCardModal) {
this.initSwipeToClose();
}
unlock();
}
private initSwipeToClose() {
if (getIonMode(this) !== 'ios') {
return;
}
const { el } = this;
// All of the elements needed for the swipe gesture
// should be in the DOM and referenced by now, except
// for the presenting el
const animationBuilder = this.leaveAnimation || config.get('modalLeave', iosLeaveAnimation);
const ani = (this.animation = animationBuilder(el, { presentingEl: this.presentingElement }));
const contentEl = findIonContent(el);
if (!contentEl) {
printIonContentErrorMsg(el);
return;
}
const statusBarStyle = this.statusBarStyle ?? StatusBarStyle.Default;
this.gesture = createSwipeToCloseGesture(el, ani, statusBarStyle, () => {
/**
* While the gesture animation is finishing
* it is possible for a user to tap the backdrop.
* This would result in the dismiss animation
* being played again. Typically this is avoided
* by setting `presented = false` on the overlay
* component; however, we cannot do that here as
* that would prevent the element from being
* removed from the DOM.
*/
this.gestureAnimationDismissing = true;
/**
* Reset the status bar style as the dismiss animation
* starts otherwise the status bar will be the wrong
* color for the duration of the dismiss animation.
* The dismiss method does this as well, but
* in this case it's only called once the animation
* has finished.
*/
setCardStatusBarDefault(this.statusBarStyle);
this.animation!.onFinish(async () => {
await this.dismiss(undefined, GESTURE);
this.gestureAnimationDismissing = false;
});
});
this.gesture.enable(true);
}
private initSheetGesture() {
const { wrapperEl, initialBreakpoint, backdropBreakpoint } = this;
if (!wrapperEl || initialBreakpoint === undefined) {
return;
}
const animationBuilder = this.enterAnimation || config.get('modalEnter', iosEnterAnimation);
const ani: Animation = (this.animation = animationBuilder(this.el, {
presentingEl: this.presentingElement,
currentBreakpoint: initialBreakpoint,
backdropBreakpoint,
}));
ani.progressStart(true, 1);
const { gesture, moveSheetToBreakpoint } = createSheetGesture(
this.el,
this.backdropEl!,
wrapperEl,
initialBreakpoint,
backdropBreakpoint,
ani,
this.sortedBreakpoints,
() => this.currentBreakpoint ?? 0,
() => this.sheetOnDismiss(),
(breakpoint: number) => {
if (this.currentBreakpoint !== breakpoint) {
this.currentBreakpoint = breakpoint;
this.ionBreakpointDidChange.emit({ breakpoint });
}
}
);
this.gesture = gesture;
this.moveSheetToBreakpoint = moveSheetToBreakpoint;
this.gesture.enable(true);
}
private sheetOnDismiss() {
/**
* While the gesture animation is finishing
* it is possible for a user to tap the backdrop.
* This would result in the dismiss animation
* being played again. Typically this is avoided
* by setting `presented = false` on the overlay
* component; however, we cannot do that here as
* that would prevent the element from being
* removed from the DOM.
*/
this.gestureAnimationDismissing = true;
this.animation!.onFinish(async () => {
this.currentBreakpoint = 0;
this.ionBreakpointDidChange.emit({ breakpoint: this.currentBreakpoint });
await this.dismiss(undefined, GESTURE);
this.gestureAnimationDismissing = false;
});
}
/**
* Dismiss the modal overlay after it has been presented.
*
* @param data Any data to emit in the dismiss events.
* @param role The role of the element that is dismissing the modal. For example, 'cancel' or 'backdrop'.
*
* This is a no-op if the overlay has not been presented yet. If you want
* to remove an overlay from the DOM that was never presented, use the
* [remove](https://developer.mozilla.org/en-US/docs/Web/API/Element/remove) method.
*/
@Method()
async dismiss(data?: any, role?: string): Promise<boolean> {
if (this.gestureAnimationDismissing && role !== GESTURE) {
return false;
}
/**
* Because the canDismiss check below is async,
* we need to claim a lock before the check happens,
* in case the dismiss transition does run.
*/
const unlock = await this.lockController.lock();
/**
* If a canDismiss handler is responsible
* for calling the dismiss method, we should
* not run the canDismiss check again.
*/
if (role !== 'handler' && !(await this.checkCanDismiss(data, role))) {
unlock();
return false;
}
const { presentingElement } = this;
/**
* We need to start the status bar change
* before the animation so that the change
* finishes when the dismiss animation does.
*/
const hasCardModal = presentingElement !== undefined;
if (hasCardModal && getIonMode(this) === 'ios') {
setCardStatusBarDefault(this.statusBarStyle);
}
/* tslint:disable-next-line */
if (typeof window !== 'undefined' && this.keyboardOpenCallback) {
window.removeEventListener(KEYBOARD_DID_OPEN, this.keyboardOpenCallback);
this.keyboardOpenCallback = undefined;
}
const dismissed = await dismiss<ModalDismissOptions>(
this,
data,
role,
'modalLeave',
iosLeaveAnimation,
mdLeaveAnimation,
{
presentingEl: presentingElement,
currentBreakpoint: this.currentBreakpoint ?? this.initialBreakpoint,
backdropBreakpoint: this.backdropBreakpoint,
}
);
if (dismissed) {
const { delegate } = this.getDelegate();
await detachComponent(delegate, this.usersElement);
writeTask(() => this.el.classList.remove('show-modal'));
if (this.animation) {
this.animation.destroy();
}
if (this.gesture) {
this.gesture.destroy();
}
}
this.currentBreakpoint = undefined;
this.animation = undefined;
unlock();
return dismissed;
}
/**
* Returns a promise that resolves when the modal did dismiss.
*/
@Method()
onDidDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionModalDidDismiss');
}
/**
* Returns a promise that resolves when the modal will dismiss.
*/
@Method()
onWillDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionModalWillDismiss');
}
/**
* Move a sheet style modal to a specific breakpoint. The breakpoint value must
* be a value defined in your `breakpoints` array.
*/
@Method()
async setCurrentBreakpoint(breakpoint: number): Promise<void> {
if (!this.isSheetModal) {
printIonWarning('setCurrentBreakpoint is only supported on sheet modals.');
return;
}
if (!this.breakpoints!.includes(breakpoint)) {
printIonWarning(
`Attempted to set invalid breakpoint value ${breakpoint}. Please double check that the breakpoint value is part of your defined breakpoints.`
);
return;
}
const { currentBreakpoint, moveSheetToBreakpoint, canDismiss, breakpoints, animated } = this;
if (currentBreakpoint === breakpoint) {
return;
}
if (moveSheetToBreakpoint) {
this.sheetTransition = moveSheetToBreakpoint({
breakpoint,
breakpointOffset: 1 - currentBreakpoint!,
canDismiss: canDismiss !== undefined && canDismiss !== true && breakpoints![0] === 0,
animated,
});
await this.sheetTransition;
this.sheetTransition = undefined;
}
}
/**
* Returns the current breakpoint of a sheet style modal
*/
@Method()
async getCurrentBreakpoint(): Promise<number | undefined> {
return this.currentBreakpoint;
}
private async moveToNextBreakpoint() {
const { breakpoints, currentBreakpoint } = this;
if (!breakpoints || currentBreakpoint == null) {
/**
* If the modal does not have breakpoints and/or the current
* breakpoint is not set, we can't move to the next breakpoint.
*/
return false;
}
const allowedBreakpoints = breakpoints.filter((b) => b !== 0);
const currentBreakpointIndex = allowedBreakpoints.indexOf(currentBreakpoint);
const nextBreakpointIndex = (currentBreakpointIndex + 1) % allowedBreakpoints.length;
const nextBreakpoint = allowedBreakpoints[nextBreakpointIndex];
/**
* Sets the current breakpoint to the next available breakpoint.
* If the current breakpoint is the last breakpoint, we set the current
* breakpoint to the first non-zero breakpoint to avoid dismissing the sheet.
*/
await this.setCurrentBreakpoint(nextBreakpoint);
return true;
}
private onHandleClick = () => {
const { sheetTransition, handleBehavior } = this;
if (handleBehavior !== 'cycle' || sheetTransition !== undefined) {
/**
* The sheet modal should not advance to the next breakpoint
* if the handle behavior is not `cycle` or if the handle
* is clicked while the sheet is moving to a breakpoint.
*/
return;
}
this.moveToNextBreakpoint();
};
private onBackdropTap = () => {
const { sheetTransition } = this;
if (sheetTransition !== undefined) {
/**
* When the handle is double clicked at the largest breakpoint,
* it will start to move to the first breakpoint. While transitioning,
* the backdrop will often receive the second click. We prevent the
* backdrop from dismissing the modal while moving between breakpoints.
*/
return;
}
this.dismiss(undefined, BACKDROP);
};
private onLifecycle = (modalEvent: CustomEvent) => {
const el = this.usersElement;
const name = LIFECYCLE_MAP[modalEvent.type];
if (el && name) {
const ev = new CustomEvent(name, {
bubbles: false,
cancelable: false,
detail: modalEvent.detail,
});
el.dispatchEvent(ev);
}
};
render() {
const { handle, isSheetModal, presentingElement, htmlAttributes, handleBehavior, inheritedAttributes, focusTrap } =
this;
const showHandle = handle !== false && isSheetModal;
const mode = getIonMode(this);
const isCardModal = presentingElement !== undefined && mode === 'ios';
const isHandleCycle = handleBehavior === 'cycle';
return (
<Host
no-router
tabindex="-1"
{...(htmlAttributes as any)}
style={{
zIndex: `${20000 + this.overlayIndex}`,
}}
class={{
[mode]: true,
['modal-default']: !isCardModal && !isSheetModal,
[`modal-card`]: isCardModal,
[`modal-sheet`]: isSheetModal,
'overlay-hidden': true,
[FOCUS_TRAP_DISABLE_CLASS]: focusTrap === false,
...getClassMap(this.cssClass),
}}
onIonBackdropTap={this.onBackdropTap}
onIonModalDidPresent={this.onLifecycle}
onIonModalWillPresent={this.onLifecycle}
onIonModalWillDismiss={this.onLifecycle}
onIonModalDidDismiss={this.onLifecycle}
>
<ion-backdrop
ref={(el) => (this.backdropEl = el)}
visible={this.showBackdrop}
tappable={this.backdropDismiss}
part="backdrop"
/>
{mode === 'ios' && <div class="modal-shadow"></div>}
<div
/*
role and aria-modal must be used on the
same element. They must also be set inside the
shadow DOM otherwise ion-button will not be highlighted
when using VoiceOver: https://bugs.webkit.org/show_bug.cgi?id=247134
*/
role="dialog"
{...inheritedAttributes}
aria-modal="true"
class="modal-wrapper ion-overlay-wrapper"
part="content"
ref={(el) => (this.wrapperEl = el)}
>
{showHandle && (
<button
class="modal-handle"
// Prevents the handle from receiving keyboard focus when it does not cycle
tabIndex={!isHandleCycle ? -1 : 0}
aria-label="Activate to adjust the size of the dialog overlaying the screen"
onClick={isHandleCycle ? this.onHandleClick : undefined}
part="handle"
></button>
)}
<slot></slot>
</div>
</Host>
);
}
}