@vaadin/overlay 23.3.0-alpha4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,993 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2017 - 2022 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
6
+ import { FlattenedNodesObserver } from '@polymer/polymer/lib/utils/flattened-nodes-observer.js';
7
+ import { afterNextRender } from '@polymer/polymer/lib/utils/render-status.js';
8
+ import { templatize } from '@polymer/polymer/lib/utils/templatize.js';
9
+ import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';
10
+ import { isIOS } from '@vaadin/component-base/src/browser-utils.js';
11
+ import { ControllerMixin } from '@vaadin/component-base/src/controller-mixin.js';
12
+ import { DirMixin } from '@vaadin/component-base/src/dir-mixin.js';
13
+ import { FocusTrapController } from '@vaadin/component-base/src/focus-trap-controller.js';
14
+ import { ThemableMixin } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
15
+
16
+ /**
17
+ *
18
+ * `<vaadin-overlay>` is a Web Component for creating overlays. The content of the overlay
19
+ * can be populated in two ways: imperatively by using renderer callback function and
20
+ * declaratively by using Polymer's Templates.
21
+ *
22
+ * ### Rendering
23
+ *
24
+ * By default, the overlay uses the content provided by using the renderer callback function.
25
+ *
26
+ * The renderer function provides `root`, `owner`, `model` arguments when applicable.
27
+ * Generate DOM content by using `model` object properties if needed, append it to the `root`
28
+ * element and control the state of the host element by accessing `owner`. Before generating new
29
+ * content, users are able to check if there is already content in `root` for reusing it.
30
+ *
31
+ * ```html
32
+ * <vaadin-overlay id="overlay"></vaadin-overlay>
33
+ * ```
34
+ * ```js
35
+ * const overlay = document.querySelector('#overlay');
36
+ * overlay.renderer = function(root) {
37
+ * root.textContent = "Overlay content";
38
+ * };
39
+ * ```
40
+ *
41
+ * Renderer is called on the opening of the overlay and each time the related model is updated.
42
+ * DOM generated during the renderer call can be reused
43
+ * in the next renderer call and will be provided with the `root` argument.
44
+ * On first call it will be empty.
45
+ *
46
+ * **NOTE:** when the renderer property is defined, the `<template>` content is not used.
47
+ *
48
+ * ### Templating
49
+ *
50
+ * Alternatively, the content can be provided with Polymer Template.
51
+ * Overlay finds the first child template and uses that in case renderer callback function
52
+ * is not provided. You can also set a custom template using the `template` property.
53
+ *
54
+ * After the content from the template is stamped, the `content` property
55
+ * points to the content container.
56
+ *
57
+ * The overlay provides `forwardHostProp` when calling
58
+ * `Polymer.Templatize.templatize` for the template, so that the bindings
59
+ * from the parent scope propagate to the content.
60
+ *
61
+ * ### Styling
62
+ *
63
+ * To style the overlay content, use styles in the parent scope:
64
+ *
65
+ * - If the overlay is used in a component, then the component styles
66
+ * apply the overlay content.
67
+ * - If the overlay is used in the global DOM scope, then global styles
68
+ * apply to the overlay content.
69
+ *
70
+ * See examples for styling the overlay content in the live demos.
71
+ *
72
+ * The following Shadow DOM parts are available for styling the overlay component itself:
73
+ *
74
+ * Part name | Description
75
+ * -----------|---------------------------------------------------------|
76
+ * `backdrop` | Backdrop of the overlay
77
+ * `overlay` | Container for position/sizing/alignment of the content
78
+ * `content` | Content of the overlay
79
+ *
80
+ * The following state attributes are available for styling:
81
+ *
82
+ * Attribute | Description | Part
83
+ * ---|---|---
84
+ * `opening` | Applied just after the overlay is attached to the DOM. You can apply a CSS @keyframe animation for this state. | `:host`
85
+ * `closing` | Applied just before the overlay is detached from the DOM. You can apply a CSS @keyframe animation for this state. | `:host`
86
+ *
87
+ * The following custom CSS properties are available for styling:
88
+ *
89
+ * Custom CSS property | Description | Default value
90
+ * ---|---|---
91
+ * `--vaadin-overlay-viewport-bottom` | Bottom offset of the visible viewport area | `0` or detected offset
92
+ *
93
+ * See [Styling Components](https://vaadin.com/docs/latest/styling/custom-theme/styling-components) documentation.
94
+ *
95
+ * @fires {CustomEvent} opened-changed - Fired when the `opened` property changes.
96
+ * @fires {CustomEvent} vaadin-overlay-open - Fired after the overlay is opened.
97
+ * @fires {CustomEvent} vaadin-overlay-close - Fired before the overlay will be closed. If canceled the closing of the overlay is canceled as well.
98
+ * @fires {CustomEvent} vaadin-overlay-closing - Fired when the overlay will be closed.
99
+ * @fires {CustomEvent} vaadin-overlay-outside-click - Fired before the overlay will be closed on outside click. If canceled the closing of the overlay is canceled as well.
100
+ * @fires {CustomEvent} vaadin-overlay-escape-press - Fired before the overlay will be closed on ESC button press. If canceled the closing of the overlay is canceled as well.
101
+ *
102
+ * @extends HTMLElement
103
+ * @mixes ThemableMixin
104
+ * @mixes DirMixin
105
+ * @mixes ControllerMixin
106
+ */
107
+ class Overlay extends ThemableMixin(DirMixin(ControllerMixin(PolymerElement))) {
108
+ static get template() {
109
+ return html`
110
+ <style>
111
+ :host {
112
+ z-index: 200;
113
+ position: fixed;
114
+
115
+ /* Despite of what the names say, <vaadin-overlay> is just a container
116
+ for position/sizing/alignment. The actual overlay is the overlay part. */
117
+
118
+ /* Default position constraints: the entire viewport. Note: themes can
119
+ override this to introduce gaps between the overlay and the viewport. */
120
+ top: 0;
121
+ right: 0;
122
+ bottom: var(--vaadin-overlay-viewport-bottom);
123
+ left: 0;
124
+
125
+ /* Use flexbox alignment for the overlay part. */
126
+ display: flex;
127
+ flex-direction: column; /* makes dropdowns sizing easier */
128
+ /* Align to center by default. */
129
+ align-items: center;
130
+ justify-content: center;
131
+
132
+ /* Allow centering when max-width/max-height applies. */
133
+ margin: auto;
134
+
135
+ /* The host is not clickable, only the overlay part is. */
136
+ pointer-events: none;
137
+
138
+ /* Remove tap highlight on touch devices. */
139
+ -webkit-tap-highlight-color: transparent;
140
+
141
+ /* CSS API for host */
142
+ --vaadin-overlay-viewport-bottom: 0;
143
+ }
144
+
145
+ :host([hidden]),
146
+ :host(:not([opened]):not([closing])) {
147
+ display: none !important;
148
+ }
149
+
150
+ [part='overlay'] {
151
+ -webkit-overflow-scrolling: touch;
152
+ overflow: auto;
153
+ pointer-events: auto;
154
+
155
+ /* Prevent overflowing the host in MSIE 11 */
156
+ max-width: 100%;
157
+ box-sizing: border-box;
158
+
159
+ -webkit-tap-highlight-color: initial; /* reenable tap highlight inside */
160
+ }
161
+
162
+ [part='backdrop'] {
163
+ z-index: -1;
164
+ content: '';
165
+ background: rgba(0, 0, 0, 0.5);
166
+ position: fixed;
167
+ top: 0;
168
+ left: 0;
169
+ bottom: 0;
170
+ right: 0;
171
+ pointer-events: auto;
172
+ }
173
+ </style>
174
+
175
+ <div id="backdrop" part="backdrop" hidden$="[[!withBackdrop]]"></div>
176
+ <div part="overlay" id="overlay" tabindex="0">
177
+ <div part="content" id="content">
178
+ <slot></slot>
179
+ </div>
180
+ </div>
181
+ `;
182
+ }
183
+
184
+ static get is() {
185
+ return 'vaadin-overlay';
186
+ }
187
+
188
+ static get properties() {
189
+ return {
190
+ /**
191
+ * When true, the overlay is visible and attached to body.
192
+ */
193
+ opened: {
194
+ type: Boolean,
195
+ notify: true,
196
+ observer: '_openedChanged',
197
+ reflectToAttribute: true,
198
+ },
199
+
200
+ /**
201
+ * Owner element passed with renderer function
202
+ * @type {HTMLElement}
203
+ */
204
+ owner: Element,
205
+
206
+ /**
207
+ * Custom function for rendering the content of the overlay.
208
+ * Receives three arguments:
209
+ *
210
+ * - `root` The root container DOM element. Append your content to it.
211
+ * - `owner` The host element of the renderer function.
212
+ * - `model` The object with the properties related with rendering.
213
+ * @type {OverlayRenderer | null | undefined}
214
+ */
215
+ renderer: Function,
216
+
217
+ /**
218
+ * The template of the overlay content.
219
+ * @type {HTMLTemplateElement | null | undefined}
220
+ */
221
+ template: {
222
+ type: Object,
223
+ notify: true,
224
+ },
225
+
226
+ /**
227
+ * References the content container after the template is stamped.
228
+ * @type {!HTMLElement | undefined}
229
+ */
230
+ content: {
231
+ type: Object,
232
+ notify: true,
233
+ },
234
+
235
+ /**
236
+ * When true the overlay has backdrop on top of content when opened.
237
+ * @type {boolean}
238
+ */
239
+ withBackdrop: {
240
+ type: Boolean,
241
+ value: false,
242
+ reflectToAttribute: true,
243
+ },
244
+
245
+ /**
246
+ * Object with properties that is passed to `renderer` function
247
+ */
248
+ model: Object,
249
+
250
+ /**
251
+ * When true the overlay won't disable the main content, showing
252
+ * it doesn’t change the functionality of the user interface.
253
+ * @type {boolean}
254
+ */
255
+ modeless: {
256
+ type: Boolean,
257
+ value: false,
258
+ reflectToAttribute: true,
259
+ observer: '_modelessChanged',
260
+ },
261
+
262
+ /**
263
+ * When set to true, the overlay is hidden. This also closes the overlay
264
+ * immediately in case there is a closing animation in progress.
265
+ * @type {boolean}
266
+ */
267
+ hidden: {
268
+ type: Boolean,
269
+ reflectToAttribute: true,
270
+ observer: '_hiddenChanged',
271
+ },
272
+
273
+ /**
274
+ * When true move focus to the first focusable element in the overlay,
275
+ * or to the overlay if there are no focusable elements.
276
+ * @type {boolean}
277
+ */
278
+ focusTrap: {
279
+ type: Boolean,
280
+ value: false,
281
+ },
282
+
283
+ /**
284
+ * Set to true to enable restoring of focus when overlay is closed.
285
+ * @type {boolean}
286
+ */
287
+ restoreFocusOnClose: {
288
+ type: Boolean,
289
+ value: false,
290
+ },
291
+
292
+ /**
293
+ * Set to specify the element which should be focused on overlay close,
294
+ * if `restoreFocusOnClose` is set to true.
295
+ * @type {HTMLElement}
296
+ */
297
+ restoreFocusNode: {
298
+ type: HTMLElement,
299
+ },
300
+
301
+ /** @private */
302
+ _mouseDownInside: {
303
+ type: Boolean,
304
+ },
305
+
306
+ /** @private */
307
+ _mouseUpInside: {
308
+ type: Boolean,
309
+ },
310
+
311
+ /** @private */
312
+ _instance: {
313
+ type: Object,
314
+ },
315
+
316
+ /** @private */
317
+ _originalContentPart: Object,
318
+
319
+ /** @private */
320
+ _contentNodes: Array,
321
+
322
+ /** @private */
323
+ _oldOwner: Element,
324
+
325
+ /** @private */
326
+ _oldModel: Object,
327
+
328
+ /** @private */
329
+ _oldTemplate: Object,
330
+
331
+ /** @private */
332
+ _oldRenderer: Object,
333
+
334
+ /** @private */
335
+ _oldOpened: Boolean,
336
+ };
337
+ }
338
+
339
+ static get observers() {
340
+ return ['_templateOrRendererChanged(template, renderer, owner, model, opened)'];
341
+ }
342
+
343
+ constructor() {
344
+ super();
345
+ this._boundMouseDownListener = this._mouseDownListener.bind(this);
346
+ this._boundMouseUpListener = this._mouseUpListener.bind(this);
347
+ this._boundOutsideClickListener = this._outsideClickListener.bind(this);
348
+ this._boundKeydownListener = this._keydownListener.bind(this);
349
+
350
+ this._observer = new FlattenedNodesObserver(this, (info) => {
351
+ this._setTemplateFromNodes(info.addedNodes);
352
+ });
353
+
354
+ // Listener for preventing closing of the paper-dialog and all components extending `iron-overlay-behavior`.
355
+ this._boundIronOverlayCanceledListener = this._ironOverlayCanceled.bind(this);
356
+
357
+ /* c8 ignore next 3 */
358
+ if (isIOS) {
359
+ this._boundIosResizeListener = () => this._detectIosNavbar();
360
+ }
361
+
362
+ this.__focusTrapController = new FocusTrapController(this);
363
+ }
364
+
365
+ /** @protected */
366
+ ready() {
367
+ super.ready();
368
+
369
+ this._observer.flush();
370
+
371
+ // Need to add dummy click listeners to this and the backdrop or else
372
+ // the document click event listener (_outsideClickListener) may never
373
+ // get invoked on iOS Safari (reproducible in <vaadin-dialog>
374
+ // and <vaadin-context-menu>).
375
+ this.addEventListener('click', () => {});
376
+ this.$.backdrop.addEventListener('click', () => {});
377
+
378
+ this.addController(this.__focusTrapController);
379
+ }
380
+
381
+ /** @private */
382
+ _detectIosNavbar() {
383
+ /* c8 ignore next 15 */
384
+ if (!this.opened) {
385
+ return;
386
+ }
387
+
388
+ const innerHeight = window.innerHeight;
389
+ const innerWidth = window.innerWidth;
390
+
391
+ const landscape = innerWidth > innerHeight;
392
+
393
+ const clientHeight = document.documentElement.clientHeight;
394
+
395
+ if (landscape && clientHeight > innerHeight) {
396
+ this.style.setProperty('--vaadin-overlay-viewport-bottom', `${clientHeight - innerHeight}px`);
397
+ } else {
398
+ this.style.setProperty('--vaadin-overlay-viewport-bottom', '0');
399
+ }
400
+ }
401
+
402
+ /**
403
+ * @param {!Array<!Element>} nodes
404
+ * @protected
405
+ */
406
+ _setTemplateFromNodes(nodes) {
407
+ this.template = nodes.find((node) => node.localName && node.localName === 'template') || this.template;
408
+ }
409
+
410
+ /**
411
+ * @param {Event=} sourceEvent
412
+ * @event vaadin-overlay-close
413
+ * fired before the `vaadin-overlay` will be closed. If canceled the closing of the overlay is canceled as well.
414
+ */
415
+ close(sourceEvent) {
416
+ const evt = new CustomEvent('vaadin-overlay-close', {
417
+ bubbles: true,
418
+ cancelable: true,
419
+ detail: { sourceEvent },
420
+ });
421
+ this.dispatchEvent(evt);
422
+ if (!evt.defaultPrevented) {
423
+ this.opened = false;
424
+ }
425
+ }
426
+
427
+ /** @protected */
428
+ connectedCallback() {
429
+ super.connectedCallback();
430
+
431
+ /* c8 ignore next 3 */
432
+ if (this._boundIosResizeListener) {
433
+ this._detectIosNavbar();
434
+ window.addEventListener('resize', this._boundIosResizeListener);
435
+ }
436
+ }
437
+
438
+ /** @protected */
439
+ disconnectedCallback() {
440
+ super.disconnectedCallback();
441
+
442
+ /* c8 ignore next 3 */
443
+ if (this._boundIosResizeListener) {
444
+ window.removeEventListener('resize', this._boundIosResizeListener);
445
+ }
446
+ }
447
+
448
+ /**
449
+ * Requests an update for the content of the overlay.
450
+ * While performing the update, it invokes the renderer passed in the `renderer` property.
451
+ *
452
+ * It is not guaranteed that the update happens immediately (synchronously) after it is requested.
453
+ */
454
+ requestContentUpdate() {
455
+ if (this.renderer) {
456
+ this.renderer.call(this.owner, this.content, this.owner, this.model);
457
+ }
458
+ }
459
+
460
+ /** @private */
461
+ _ironOverlayCanceled(event) {
462
+ event.preventDefault();
463
+ }
464
+
465
+ /** @private */
466
+ _mouseDownListener(event) {
467
+ this._mouseDownInside = event.composedPath().indexOf(this.$.overlay) >= 0;
468
+ }
469
+
470
+ /** @private */
471
+ _mouseUpListener(event) {
472
+ this._mouseUpInside = event.composedPath().indexOf(this.$.overlay) >= 0;
473
+ }
474
+
475
+ /**
476
+ * We need to listen on 'click' / 'tap' event and capture it and close the overlay before
477
+ * propagating the event to the listener in the button. Otherwise, if the clicked button would call
478
+ * open(), this would happen: https://www.youtube.com/watch?v=Z86V_ICUCD4
479
+ *
480
+ * @event vaadin-overlay-outside-click
481
+ * fired before the `vaadin-overlay` will be closed on outside click. If canceled the closing of the overlay is canceled as well.
482
+ *
483
+ * @private
484
+ */
485
+ _outsideClickListener(event) {
486
+ if (event.composedPath().includes(this.$.overlay) || this._mouseDownInside || this._mouseUpInside) {
487
+ this._mouseDownInside = false;
488
+ this._mouseUpInside = false;
489
+ return;
490
+ }
491
+ if (!this._last) {
492
+ return;
493
+ }
494
+
495
+ const evt = new CustomEvent('vaadin-overlay-outside-click', {
496
+ bubbles: true,
497
+ cancelable: true,
498
+ detail: { sourceEvent: event },
499
+ });
500
+ this.dispatchEvent(evt);
501
+
502
+ if (this.opened && !evt.defaultPrevented) {
503
+ this.close(event);
504
+ }
505
+ }
506
+
507
+ /**
508
+ * @event vaadin-overlay-escape-press
509
+ * fired before the `vaadin-overlay` will be closed on ESC button press. If canceled the closing of the overlay is canceled as well.
510
+ *
511
+ * @private
512
+ */
513
+ _keydownListener(event) {
514
+ if (!this._last) {
515
+ return;
516
+ }
517
+
518
+ // Only close modeless overlay on Esc press when it contains focus
519
+ if (this.modeless && !event.composedPath().includes(this.$.overlay)) {
520
+ return;
521
+ }
522
+
523
+ if (event.key === 'Escape') {
524
+ const evt = new CustomEvent('vaadin-overlay-escape-press', {
525
+ bubbles: true,
526
+ cancelable: true,
527
+ detail: { sourceEvent: event },
528
+ });
529
+ this.dispatchEvent(evt);
530
+
531
+ if (this.opened && !evt.defaultPrevented) {
532
+ this.close(event);
533
+ }
534
+ }
535
+ }
536
+
537
+ /** @protected */
538
+ _ensureTemplatized() {
539
+ this._setTemplateFromNodes(Array.from(this.children));
540
+ }
541
+
542
+ /**
543
+ * @event vaadin-overlay-open
544
+ * fired after the `vaadin-overlay` is opened.
545
+ *
546
+ * @private
547
+ */
548
+ _openedChanged(opened, wasOpened) {
549
+ if (!this._instance) {
550
+ this._ensureTemplatized();
551
+ }
552
+
553
+ if (opened) {
554
+ // Store focused node.
555
+ this.__restoreFocusNode = this._getActiveElement();
556
+ this._animatedOpening();
557
+
558
+ afterNextRender(this, () => {
559
+ if (this.focusTrap) {
560
+ this.__focusTrapController.trapFocus(this.$.overlay);
561
+ }
562
+
563
+ const evt = new CustomEvent('vaadin-overlay-open', { bubbles: true });
564
+ this.dispatchEvent(evt);
565
+ });
566
+
567
+ document.addEventListener('keydown', this._boundKeydownListener);
568
+
569
+ if (!this.modeless) {
570
+ this._addGlobalListeners();
571
+ }
572
+ } else if (wasOpened) {
573
+ if (this.focusTrap) {
574
+ this.__focusTrapController.releaseFocus();
575
+ }
576
+
577
+ this._animatedClosing();
578
+
579
+ document.removeEventListener('keydown', this._boundKeydownListener);
580
+
581
+ if (!this.modeless) {
582
+ this._removeGlobalListeners();
583
+ }
584
+ }
585
+ }
586
+
587
+ /** @private */
588
+ _hiddenChanged(hidden) {
589
+ if (hidden && this.hasAttribute('closing')) {
590
+ this._flushAnimation('closing');
591
+ }
592
+ }
593
+
594
+ /**
595
+ * @return {boolean}
596
+ * @protected
597
+ */
598
+ _shouldAnimate() {
599
+ const name = getComputedStyle(this).getPropertyValue('animation-name');
600
+ const hidden = getComputedStyle(this).getPropertyValue('display') === 'none';
601
+ return !hidden && name && name !== 'none';
602
+ }
603
+
604
+ /**
605
+ * @param {string} type
606
+ * @param {Function} callback
607
+ * @protected
608
+ */
609
+ _enqueueAnimation(type, callback) {
610
+ const handler = `__${type}Handler`;
611
+ const listener = (event) => {
612
+ if (event && event.target !== this) {
613
+ return;
614
+ }
615
+ callback();
616
+ this.removeEventListener('animationend', listener);
617
+ delete this[handler];
618
+ };
619
+ this[handler] = listener;
620
+ this.addEventListener('animationend', listener);
621
+ }
622
+
623
+ /**
624
+ * @param {string} type
625
+ * @protected
626
+ */
627
+ _flushAnimation(type) {
628
+ const handler = `__${type}Handler`;
629
+ if (typeof this[handler] === 'function') {
630
+ this[handler]();
631
+ }
632
+ }
633
+
634
+ /** @protected */
635
+ _animatedOpening() {
636
+ if (this.parentNode === document.body && this.hasAttribute('closing')) {
637
+ this._flushAnimation('closing');
638
+ }
639
+ this._attachOverlay();
640
+ if (!this.modeless) {
641
+ this._enterModalState();
642
+ }
643
+ this.setAttribute('opening', '');
644
+
645
+ if (this._shouldAnimate()) {
646
+ this._enqueueAnimation('opening', () => {
647
+ this._finishOpening();
648
+ });
649
+ } else {
650
+ this._finishOpening();
651
+ }
652
+ }
653
+
654
+ /** @protected */
655
+ _attachOverlay() {
656
+ this._placeholder = document.createComment('vaadin-overlay-placeholder');
657
+ this.parentNode.insertBefore(this._placeholder, this);
658
+ document.body.appendChild(this);
659
+ this.bringToFront();
660
+ }
661
+
662
+ /** @protected */
663
+ _finishOpening() {
664
+ document.addEventListener('iron-overlay-canceled', this._boundIronOverlayCanceledListener);
665
+ this.removeAttribute('opening');
666
+ }
667
+
668
+ /** @protected */
669
+ _finishClosing() {
670
+ document.removeEventListener('iron-overlay-canceled', this._boundIronOverlayCanceledListener);
671
+ this._detachOverlay();
672
+ this.$.overlay.style.removeProperty('pointer-events');
673
+ this.removeAttribute('closing');
674
+ }
675
+
676
+ /**
677
+ * @event vaadin-overlay-closing
678
+ * Fired when the overlay will be closed.
679
+ *
680
+ * @protected
681
+ */
682
+ _animatedClosing() {
683
+ if (this.hasAttribute('opening')) {
684
+ this._flushAnimation('opening');
685
+ }
686
+ if (this._placeholder) {
687
+ this._exitModalState();
688
+
689
+ // Use this.restoreFocusNode if specified, otherwise fallback to the node
690
+ // which was focused before opening the overlay.
691
+ const restoreFocusNode = this.restoreFocusNode || this.__restoreFocusNode;
692
+
693
+ if (this.restoreFocusOnClose && restoreFocusNode) {
694
+ // If the activeElement is `<body>` or inside the overlay,
695
+ // we are allowed to restore the focus. In all the other
696
+ // cases focus might have been moved elsewhere by another
697
+ // component or by the user interaction (e.g. click on a
698
+ // button outside the overlay).
699
+ const activeElement = this._getActiveElement();
700
+
701
+ if (activeElement === document.body || this._deepContains(activeElement)) {
702
+ // Focusing the restoreFocusNode doesn't always work synchronously on Firefox and Safari
703
+ // (e.g. combo-box overlay close on outside click).
704
+ setTimeout(() => restoreFocusNode.focus());
705
+ }
706
+ this.__restoreFocusNode = null;
707
+ }
708
+
709
+ this.setAttribute('closing', '');
710
+ this.dispatchEvent(new CustomEvent('vaadin-overlay-closing'));
711
+
712
+ if (this._shouldAnimate()) {
713
+ this._enqueueAnimation('closing', () => {
714
+ this._finishClosing();
715
+ });
716
+ } else {
717
+ this._finishClosing();
718
+ }
719
+ }
720
+ }
721
+
722
+ /** @protected */
723
+ _detachOverlay() {
724
+ this._placeholder.parentNode.insertBefore(this, this._placeholder);
725
+ this._placeholder.parentNode.removeChild(this._placeholder);
726
+ }
727
+
728
+ /**
729
+ * Returns all attached overlays in visual stacking order.
730
+ * @private
731
+ */
732
+ static get __attachedInstances() {
733
+ return Array.from(document.body.children)
734
+ .filter((el) => el instanceof Overlay && !el.hasAttribute('closing'))
735
+ .sort((a, b) => a.__zIndex - b.__zIndex || 0);
736
+ }
737
+
738
+ /**
739
+ * Returns true if this is the last one in the opened overlays stack
740
+ * @return {boolean}
741
+ * @protected
742
+ */
743
+ get _last() {
744
+ return this === Overlay.__attachedInstances.pop();
745
+ }
746
+
747
+ /** @private */
748
+ _modelessChanged(modeless) {
749
+ if (!modeless) {
750
+ if (this.opened) {
751
+ this._addGlobalListeners();
752
+ this._enterModalState();
753
+ }
754
+ } else {
755
+ this._removeGlobalListeners();
756
+ this._exitModalState();
757
+ }
758
+ }
759
+
760
+ /** @protected */
761
+ _addGlobalListeners() {
762
+ document.addEventListener('mousedown', this._boundMouseDownListener);
763
+ document.addEventListener('mouseup', this._boundMouseUpListener);
764
+ // Firefox leaks click to document on contextmenu even if prevented
765
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=990614
766
+ document.documentElement.addEventListener('click', this._boundOutsideClickListener, true);
767
+ }
768
+
769
+ /** @protected */
770
+ _enterModalState() {
771
+ if (document.body.style.pointerEvents !== 'none') {
772
+ // Set body pointer-events to 'none' to disable mouse interactions with
773
+ // other document nodes.
774
+ this._previousDocumentPointerEvents = document.body.style.pointerEvents;
775
+ document.body.style.pointerEvents = 'none';
776
+ }
777
+
778
+ // Disable pointer events in other attached overlays
779
+ Overlay.__attachedInstances.forEach((el) => {
780
+ if (el !== this) {
781
+ el.shadowRoot.querySelector('[part="overlay"]').style.pointerEvents = 'none';
782
+ }
783
+ });
784
+ }
785
+
786
+ /** @protected */
787
+ _removeGlobalListeners() {
788
+ document.removeEventListener('mousedown', this._boundMouseDownListener);
789
+ document.removeEventListener('mouseup', this._boundMouseUpListener);
790
+ document.documentElement.removeEventListener('click', this._boundOutsideClickListener, true);
791
+ }
792
+
793
+ /** @protected */
794
+ _exitModalState() {
795
+ if (this._previousDocumentPointerEvents !== undefined) {
796
+ // Restore body pointer-events
797
+ document.body.style.pointerEvents = this._previousDocumentPointerEvents;
798
+ delete this._previousDocumentPointerEvents;
799
+ }
800
+
801
+ // Restore pointer events in the previous overlay(s)
802
+ const instances = Overlay.__attachedInstances;
803
+ let el;
804
+ // Use instances.pop() to ensure the reverse order
805
+ while ((el = instances.pop())) {
806
+ if (el === this) {
807
+ // Skip the current instance
808
+ continue;
809
+ }
810
+ el.shadowRoot.querySelector('[part="overlay"]').style.removeProperty('pointer-events');
811
+ if (!el.modeless) {
812
+ // Stop after the last modal
813
+ break;
814
+ }
815
+ }
816
+ }
817
+
818
+ /** @protected */
819
+ _removeOldContent() {
820
+ if (!this.content || !this._contentNodes) {
821
+ return;
822
+ }
823
+
824
+ this._observer.disconnect();
825
+
826
+ this._contentNodes.forEach((node) => {
827
+ if (node.parentNode === this.content) {
828
+ this.content.removeChild(node);
829
+ }
830
+ });
831
+
832
+ if (this._originalContentPart) {
833
+ // Restore the original <div part="content">
834
+ this.$.content.parentNode.replaceChild(this._originalContentPart, this.$.content);
835
+ this.$.content = this._originalContentPart;
836
+ this._originalContentPart = undefined;
837
+ }
838
+
839
+ this._observer.connect();
840
+
841
+ this._contentNodes = undefined;
842
+ this.content = undefined;
843
+ }
844
+
845
+ /**
846
+ * @param {!HTMLTemplateElement} template
847
+ * @protected
848
+ */
849
+ _stampOverlayTemplate(template) {
850
+ this._removeOldContent();
851
+
852
+ if (!template._Templatizer) {
853
+ template._Templatizer = templatize(template, this, {
854
+ forwardHostProp(prop, value) {
855
+ if (this._instance) {
856
+ this._instance.forwardHostProp(prop, value);
857
+ }
858
+ },
859
+ });
860
+ }
861
+
862
+ this._instance = new template._Templatizer({});
863
+ this._contentNodes = Array.from(this._instance.root.childNodes);
864
+
865
+ const templateRoot = template._templateRoot || (template._templateRoot = template.getRootNode());
866
+
867
+ if (templateRoot !== document) {
868
+ if (!this.$.content.shadowRoot) {
869
+ this.$.content.attachShadow({ mode: 'open' });
870
+ }
871
+
872
+ let scopeCssText = Array.from(templateRoot.querySelectorAll('style')).reduce(
873
+ (result, style) => result + style.textContent,
874
+ '',
875
+ );
876
+
877
+ // The overlay root’s :host styles should not apply inside the overlay
878
+ scopeCssText = scopeCssText.replace(/:host/g, ':host-nomatch');
879
+
880
+ if (scopeCssText) {
881
+ // Append a style to the content shadowRoot
882
+ const style = document.createElement('style');
883
+ style.textContent = scopeCssText;
884
+ this.$.content.shadowRoot.appendChild(style);
885
+ this._contentNodes.unshift(style);
886
+ }
887
+
888
+ this.$.content.shadowRoot.appendChild(this._instance.root);
889
+ this.content = this.$.content.shadowRoot;
890
+ } else {
891
+ this.appendChild(this._instance.root);
892
+ this.content = this;
893
+ }
894
+ }
895
+
896
+ /** @private */
897
+ _removeNewRendererOrTemplate(template, oldTemplate, renderer, oldRenderer) {
898
+ if (template !== oldTemplate) {
899
+ this.template = undefined;
900
+ } else if (renderer !== oldRenderer) {
901
+ this.renderer = undefined;
902
+ }
903
+ }
904
+
905
+ /** @private */
906
+ // eslint-disable-next-line max-params
907
+ _templateOrRendererChanged(template, renderer, owner, model, opened) {
908
+ if (template && renderer) {
909
+ this._removeNewRendererOrTemplate(template, this._oldTemplate, renderer, this._oldRenderer);
910
+ throw new Error('You should only use either a renderer or a template for overlay content');
911
+ }
912
+
913
+ const ownerOrModelChanged = this._oldOwner !== owner || this._oldModel !== model;
914
+ this._oldModel = model;
915
+ this._oldOwner = owner;
916
+
917
+ const templateChanged = this._oldTemplate !== template;
918
+ this._oldTemplate = template;
919
+
920
+ const rendererChanged = this._oldRenderer !== renderer;
921
+ this._oldRenderer = renderer;
922
+
923
+ const openedChanged = this._oldOpened !== opened;
924
+ this._oldOpened = opened;
925
+
926
+ if (rendererChanged) {
927
+ this.content = this;
928
+ this.content.innerHTML = '';
929
+ // Whenever a Lit-based renderer is used, it assigns a Lit part to the node it was rendered into.
930
+ // When clearing the rendered content, this part needs to be manually disposed of.
931
+ // Otherwise, using a Lit-based renderer on the same node will throw an exception or render nothing afterward.
932
+ delete this.content._$litPart$;
933
+ }
934
+
935
+ if (template && templateChanged) {
936
+ this._stampOverlayTemplate(template);
937
+ } else if (renderer && (rendererChanged || openedChanged || ownerOrModelChanged)) {
938
+ if (opened) {
939
+ this.requestContentUpdate();
940
+ }
941
+ }
942
+ }
943
+
944
+ /**
945
+ * @return {!Element}
946
+ * @protected
947
+ */
948
+ _getActiveElement() {
949
+ // Document.activeElement can be null
950
+ // https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement
951
+ let active = document.activeElement || document.body;
952
+ while (active.shadowRoot && active.shadowRoot.activeElement) {
953
+ active = active.shadowRoot.activeElement;
954
+ }
955
+ return active;
956
+ }
957
+
958
+ /**
959
+ * @param {!Node} node
960
+ * @return {boolean}
961
+ * @protected
962
+ */
963
+ _deepContains(node) {
964
+ if (this.contains(node)) {
965
+ return true;
966
+ }
967
+ let n = node;
968
+ const doc = node.ownerDocument;
969
+ // Walk from node to `this` or `document`
970
+ while (n && n !== doc && n !== this) {
971
+ n = n.parentNode || n.host;
972
+ }
973
+ return n === this;
974
+ }
975
+
976
+ /**
977
+ * Brings the overlay as visually the frontmost one
978
+ */
979
+ bringToFront() {
980
+ let zIndex = '';
981
+ const frontmost = Overlay.__attachedInstances.filter((o) => o !== this).pop();
982
+ if (frontmost) {
983
+ const frontmostZIndex = frontmost.__zIndex;
984
+ zIndex = frontmostZIndex + 1;
985
+ }
986
+ this.style.zIndex = zIndex;
987
+ this.__zIndex = zIndex || parseFloat(getComputedStyle(this).zIndex);
988
+ }
989
+ }
990
+
991
+ customElements.define(Overlay.is, Overlay);
992
+
993
+ export { Overlay };