/
popover.tsx
657 lines (561 loc) · 20.1 KB
/
popover.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
import type { ComponentInterface, EventEmitter } from '@stencil/core';
import { Component, Element, Event, Host, Method, Prop, State, Watch, h } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
import type {
AnimationBuilder,
ComponentProps,
ComponentRef,
FrameworkDelegate,
OverlayEventDetail,
PopoverAttributes,
PopoverInterface,
PopoverSize,
PositionAlign,
PositionReference,
PositionSide,
TriggerAction,
} from '../../interface';
import { CoreDelegate, attachComponent, detachComponent } from '../../utils/framework-delegate';
import { addEventListener, raf } from '../../utils/helpers';
import { BACKDROP, dismiss, eventMethod, focusFirstDescendant, prepareOverlay, present } from '../../utils/overlays';
import { isPlatform } from '../../utils/platform';
import { getClassMap } from '../../utils/theme';
import { deepReady } from '../../utils/transition';
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 { configureDismissInteraction, configureKeyboardInteraction, configureTriggerInteraction } from './utils';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot - Content is placed inside of the `.popover-content` element.
*
* @part backdrop - The `ion-backdrop` element.
* @part arrow - The arrow that points to the reference element. Only applies on `ios` mode.
* @part content - The wrapper element for the default slot.
*/
@Component({
tag: 'ion-popover',
styleUrls: {
ios: 'popover.ios.scss',
md: 'popover.md.scss',
},
shadow: true,
})
export class Popover implements ComponentInterface, PopoverInterface {
private usersElement?: HTMLElement;
private triggerEl?: HTMLElement | null;
private parentPopover: HTMLIonPopoverElement | null = null;
private popoverIndex = popoverIds++;
private popoverId?: string;
private coreDelegate: FrameworkDelegate = CoreDelegate();
private currentTransition?: Promise<any>;
private destroyTriggerInteraction?: () => void;
private destroyKeyboardInteraction?: () => void;
private destroyDismissInteraction?: () => void;
private inline = false;
private workingDelegate?: FrameworkDelegate;
private focusDescendantOnPresent = false;
lastFocus?: HTMLElement;
@State() presented = false;
@Element() el!: HTMLIonPopoverElement;
/** @internal */
@Prop() hasController = false;
/** @internal */
@Prop() delegate?: FrameworkDelegate;
/** @internal */
@Prop() overlayIndex!: number;
/**
* Animation to use when the popover is presented.
*/
@Prop() enterAnimation?: AnimationBuilder;
/**
* Animation to use when the popover is dismissed.
*/
@Prop() leaveAnimation?: AnimationBuilder;
/**
* The component to display inside of the popover.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* slot your component inside of `ion-popover`.
*/
@Prop() component?: ComponentRef;
/**
* The data to pass to the popover component.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* set the props directly on your component.
*/
@Prop() componentProps?: ComponentProps;
/**
* If `true`, the keyboard will be automatically dismissed when the overlay is presented.
*/
@Prop() keyboardClose = true;
/**
* 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 popover will be dismissed when the backdrop is clicked.
*/
@Prop() backdropDismiss = true;
/**
* The event to pass to the popover animation.
*/
@Prop() event: any;
/**
* If `true`, a backdrop will be displayed behind the popover.
* This property controls whether or not the backdrop
* darkens the screen when the popover is presented.
* It does not control whether or not the backdrop
* is active or present in the DOM.
*/
@Prop() showBackdrop = true;
/**
* If `true`, the popover will be translucent.
* Only applies when the mode is `"ios"` and the device supports
* [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility).
*/
@Prop() translucent = false;
/**
* If `true`, the popover will animate.
*/
@Prop() animated = true;
/**
* Additional attributes to pass to the popover.
*/
@Prop() htmlAttributes?: PopoverAttributes;
/**
* Describes what kind of interaction with the trigger that
* should cause the popover to open. Does not apply when the `trigger`
* property is `undefined`.
* If `'click'`, the popover will be presented when the trigger is left clicked.
* If `'hover'`, the popover will be presented when a pointer hovers over the trigger.
* If `'context-menu'`, the popover will be presented when the trigger is right
* clicked on desktop and long pressed on mobile. This will also prevent your
* device's normal context menu from appearing.
*/
@Prop() triggerAction: TriggerAction = 'click';
/**
* An ID corresponding to the trigger element that
* causes the popover to open. Use the `trigger-action`
* property to customize the interaction that results in
* the popover opening.
*/
@Prop() trigger: string | undefined;
/**
* Describes how to calculate the popover width.
* If `'cover'`, the popover width will match the width of the trigger.
* If `'auto'`, the popover width will be determined by the content in
* the popover.
*/
@Prop() size: PopoverSize = 'auto';
/**
* If `true`, the popover will be automatically
* dismissed when the content has been clicked.
*/
@Prop() dismissOnSelect = false;
/**
* Describes what to position the popover relative to.
* If `'trigger'`, the popover will be positioned relative
* to the trigger button. If passing in an event, this is
* determined via event.target.
* If `'event'`, the popover will be positioned relative
* to the x/y coordinates of the trigger action. If passing
* in an event, this is determined via event.clientX and event.clientY.
*/
@Prop() reference: PositionReference = 'trigger';
/**
* Describes which side of the `reference` point to position
* the popover on. The `'start'` and `'end'` values are RTL-aware,
* and the `'left'` and `'right'` values are not.
*/
@Prop() side: PositionSide = 'bottom';
/**
* Describes how to align the popover content with the `reference` point.
* Defaults to `'center'` for `ios` mode, and `'start'` for `md` mode.
*/
@Prop({ mutable: true }) alignment?: PositionAlign;
/**
* If `true`, the popover will display an arrow that points at the
* `reference` when running in `ios` mode. Does not apply in `md` mode.
*/
@Prop() arrow = true;
/**
* If `true`, the popover will open. If `false`, the popover will close.
* Use this if you need finer grained control over presentation, otherwise
* just use the popoverController or the `trigger` property.
* Note: `isOpen` will not automatically be set back to `false` when
* the popover dismisses. You will need to do that in your code.
*/
@Prop() isOpen = false;
/**
* @internal
*
* If `true` the popover will not register its own keyboard event handlers.
* This allows the contents of the popover to handle their own keyboard interactions.
*
* If `false`, the popover will register its own keyboard event handlers for
* navigating `ion-list` items within a popover (up/down/home/end/etc.).
* This will also cancel browser keyboard event bindings to prevent scroll
* behavior in a popover using a list of items.
*/
@Prop() keyboardEvents = false;
@Watch('trigger')
@Watch('triggerAction')
onTriggerChange() {
this.configureTriggerInteraction();
}
@Watch('isOpen')
onIsOpenChange(newValue: boolean, oldValue: boolean) {
if (newValue === true && oldValue === false) {
this.present();
} else if (newValue === false && oldValue === true) {
this.dismiss();
}
}
/**
* If `true`, the component passed into `ion-popover` will
* automatically be mounted when the popover is created. The
* component will remain mounted even when the popover is dismissed.
* However, the component will be destroyed when the popover is
* destroyed. This property is not reactive and should only be
* used when initially creating a popover.
*
* Note: This feature only applies to inline popovers in JavaScript
* frameworks such as Angular, React, and Vue.
*/
@Prop() keepContentsMounted = false;
/**
* Emitted after the popover has presented.
*/
@Event({ eventName: 'ionPopoverDidPresent' }) didPresent!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
*/
@Event({ eventName: 'ionPopoverWillPresent' }) willPresent!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverWillDismiss' }) willDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverDidDismiss' }) didDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has presented.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'didPresent' }) didPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
* Shorthand for ionPopoverWillPresent.
*/
@Event({ eventName: 'willPresent' }) willPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'willDismiss' }) willDismissShorthand!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
* Shorthand for ionPopoverDidDismiss.
*/
@Event({ eventName: 'didDismiss' }) didDismissShorthand!: EventEmitter<OverlayEventDetail>;
connectedCallback() {
const { configureTriggerInteraction, el } = this;
prepareOverlay(el);
configureTriggerInteraction();
}
disconnectedCallback() {
const { destroyTriggerInteraction } = this;
if (destroyTriggerInteraction) {
destroyTriggerInteraction();
}
}
componentWillLoad() {
/**
* If user has custom ID set then we should
* not assign the default incrementing ID.
*/
this.popoverId = this.el.hasAttribute('id') ? this.el.getAttribute('id')! : `ion-popover-${this.popoverIndex}`;
this.parentPopover = this.el.closest(`ion-popover:not(#${this.popoverId})`) as HTMLIonPopoverElement | null;
if (this.alignment === undefined) {
this.alignment = getIonMode(this) === 'ios' ? 'center' : 'start';
}
}
componentDidLoad() {
const { parentPopover, isOpen } = this;
/**
* If popover was rendered with isOpen="true"
* then we should open popover immediately.
*/
if (isOpen === true) {
raf(() => this.present());
}
if (parentPopover) {
addEventListener(parentPopover, 'ionPopoverWillDismiss', () => {
this.dismiss(undefined, undefined, false);
});
}
}
/**
* When opening a popover from a trigger, we should not be
* modifying the `event` prop from inside the component.
* Additionally, when pressing the "Right" arrow key, we need
* to shift focus to the first descendant in the newly presented
* popover.
*
* @internal
*/
@Method()
async presentFromTrigger(event?: any, focusDescendant = false) {
this.focusDescendantOnPresent = focusDescendant;
await this.present(event);
this.focusDescendantOnPresent = false;
}
/**
* 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 };
}
/**
* Present the popover overlay after it has been created.
* Developers can pass a mouse, touch, or pointer event
* to position the popover relative to where that event
* was dispatched.
*/
@Method()
async present(event?: MouseEvent | TouchEvent | PointerEvent | CustomEvent): Promise<void> {
if (this.presented) {
return;
}
/**
* When using an inline popover
* and dismissing a popover it is possible to
* quickly present the popover while it is
* dismissing. We need to await any current
* transition to allow the dismiss to finish
* before presenting again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const data = {
...this.componentProps,
popover: this.el,
};
const { inline, delegate } = this.getDelegate(true);
this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);
await deepReady(this.usersElement);
if (!this.keyboardEvents) {
this.configureKeyboardInteraction();
}
this.configureDismissInteraction();
this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {
event: event || this.event,
size: this.size,
trigger: this.triggerEl,
reference: this.reference,
side: this.side,
align: this.alignment,
});
await this.currentTransition;
this.currentTransition = undefined;
/**
* If popover is nested and was
* presented using the "Right" arrow key,
* we need to move focus to the first
* descendant inside of the popover.
*/
if (this.focusDescendantOnPresent) {
focusFirstDescendant(this.el, this.el);
}
}
/**
* Dismiss the popover 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 popover. For example, 'cancel' or 'backdrop'.
* @param dismissParentPopover If `true`, dismissing this popover will also dismiss
* a parent popover if this popover is nested. Defaults to `true`.
*/
@Method()
async dismiss(data?: any, role?: string, dismissParentPopover = true): Promise<boolean> {
/**
* When using an inline popover
* and presenting a popover it is possible to
* quickly dismiss the popover while it is
* presenting. We need to await any current
* transition to allow the present to finish
* before dismissing again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const { destroyKeyboardInteraction, destroyDismissInteraction } = this;
if (dismissParentPopover && this.parentPopover) {
this.parentPopover.dismiss(data, role, dismissParentPopover);
}
this.currentTransition = dismiss(this, data, role, 'popoverLeave', iosLeaveAnimation, mdLeaveAnimation, this.event);
const shouldDismiss = await this.currentTransition;
if (shouldDismiss) {
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
this.destroyKeyboardInteraction = undefined;
}
if (destroyDismissInteraction) {
destroyDismissInteraction();
this.destroyDismissInteraction = undefined;
}
/**
* If using popover inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps
*/
const { delegate } = this.getDelegate();
await detachComponent(delegate, this.usersElement);
}
this.currentTransition = undefined;
return shouldDismiss;
}
/**
* @internal
*/
@Method()
async getParentPopover(): Promise<HTMLIonPopoverElement | null> {
return this.parentPopover;
}
/**
* Returns a promise that resolves when the popover did dismiss.
*/
@Method()
onDidDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverDidDismiss');
}
/**
* Returns a promise that resolves when the popover will dismiss.
*/
@Method()
onWillDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverWillDismiss');
}
private onBackdropTap = () => {
this.dismiss(undefined, BACKDROP);
};
private onLifecycle = (modalEvent: CustomEvent) => {
const el = this.usersElement;
const name = LIFECYCLE_MAP[modalEvent.type];
if (el && name) {
const event = new CustomEvent(name, {
bubbles: false,
cancelable: false,
detail: modalEvent.detail,
});
el.dispatchEvent(event);
}
};
private configureTriggerInteraction = () => {
const { trigger, triggerAction, el, destroyTriggerInteraction } = this;
if (destroyTriggerInteraction) {
destroyTriggerInteraction();
}
const triggerEl = (this.triggerEl = trigger !== undefined ? document.getElementById(trigger) : null);
if (!triggerEl) {
return;
}
this.destroyTriggerInteraction = configureTriggerInteraction(triggerEl, triggerAction, el);
};
private configureKeyboardInteraction = () => {
const { destroyKeyboardInteraction, el } = this;
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
}
this.destroyKeyboardInteraction = configureKeyboardInteraction(el);
};
private configureDismissInteraction = () => {
const { destroyDismissInteraction, parentPopover, triggerAction, triggerEl, el } = this;
if (!parentPopover || !triggerEl) {
return;
}
if (destroyDismissInteraction) {
destroyDismissInteraction();
}
this.destroyDismissInteraction = configureDismissInteraction(triggerEl, triggerAction, el, parentPopover);
};
render() {
const mode = getIonMode(this);
const { onLifecycle, popoverId, parentPopover, dismissOnSelect, side, arrow, htmlAttributes } = this;
const desktop = isPlatform('desktop');
const enableArrow = arrow && !parentPopover;
return (
<Host
aria-modal="true"
no-router
tabindex="-1"
{...(htmlAttributes as any)}
style={{
zIndex: `${20000 + this.overlayIndex}`,
}}
id={popoverId}
class={{
...getClassMap(this.cssClass),
[mode]: true,
'popover-translucent': this.translucent,
'overlay-hidden': true,
'popover-desktop': desktop,
[`popover-side-${side}`]: true,
'popover-nested': !!parentPopover,
}}
onIonPopoverDidPresent={onLifecycle}
onIonPopoverWillPresent={onLifecycle}
onIonPopoverWillDismiss={onLifecycle}
onIonPopoverDidDismiss={onLifecycle}
onIonBackdropTap={this.onBackdropTap}
>
{!parentPopover && <ion-backdrop tappable={this.backdropDismiss} visible={this.showBackdrop} part="backdrop" />}
<div class="popover-wrapper ion-overlay-wrapper" onClick={dismissOnSelect ? () => this.dismiss() : undefined}>
{enableArrow && <div class="popover-arrow" part="arrow"></div>}
<div class="popover-content" part="content">
<slot></slot>
</div>
</div>
</Host>
);
}
}
const LIFECYCLE_MAP: any = {
ionPopoverDidPresent: 'ionViewDidEnter',
ionPopoverWillPresent: 'ionViewWillEnter',
ionPopoverWillDismiss: 'ionViewWillLeave',
ionPopoverDidDismiss: 'ionViewDidLeave',
};
let popoverIds = 0;