/
vaadin-overlay.html
1098 lines (945 loc) · 34.9 KB
/
vaadin-overlay.html
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
<!--
@license
Copyright (c) 2017 Vaadin Ltd.
This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
-->
<link rel="import" href="../../polymer/polymer-element.html">
<link rel="import" href="../../polymer/lib/utils/templatize.html">
<link rel="import" href="../../polymer/lib/utils/render-status.html">
<link rel="import" href="../../polymer/lib/utils/flattened-nodes-observer.html">
<link rel="import" href="../../vaadin-themable-mixin/vaadin-themable-mixin.html">
<link rel="import" href="../../vaadin-element-mixin/vaadin-dir-mixin.html">
<link rel="import" href="vaadin-focusables-helper.html">
<dom-module id="vaadin-overlay">
<template>
<style>
:host {
z-index: 200;
position: fixed;
/*
Despite of what the names say, <vaadin-overlay> is just a container
for position/sizing/alignment. The actual overlay is the overlay part.
*/
/*
Default position constraints: the entire viewport. Note: themes can
override this to introduce gaps between the overlay and the viewport.
*/
top: 0;
right: 0;
bottom: var(--vaadin-overlay-viewport-bottom);
left: 0;
/* Use flexbox alignment for the overlay part. */
display: flex;
flex-direction: column; /* makes dropdowns sizing easier */
/* Align to center by default. */
align-items: center;
justify-content: center;
/* Allow centering when max-width/max-height applies. */
margin: auto;
/* The host is not clickable, only the overlay part is. */
pointer-events: none;
/* Remove tap highlight on touch devices. */
-webkit-tap-highlight-color: transparent;
/* CSS API for host */
--vaadin-overlay-viewport-bottom: 0;
}
:host([hidden]),
:host(:not([opened]):not([closing])) {
display: none !important;
}
[part="overlay"] {
-webkit-overflow-scrolling: touch;
overflow: auto;
pointer-events: auto;
/* Prevent overflowing the host in MSIE 11 */
max-width: 100%;
box-sizing: border-box;
-webkit-tap-highlight-color: initial; /* reenable tap highlight inside */
}
[part="backdrop"] {
z-index: -1;
content: "";
background: rgba(0, 0, 0, 0.5);
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
pointer-events: auto;
}
</style>
<div id="backdrop" part="backdrop" hidden$="{{!withBackdrop}}"></div>
<div part="overlay" id="overlay" tabindex="0">
<div part="content" id="content">
<slot></slot>
</div>
</div>
</template>
</dom-module>
<script>
(function() {
let overlayContentCounter = 0;
const overlayContentCache = {};
const createOverlayContent = (cssText) => {
const is = overlayContentCache[cssText] || processOverlayStyles(cssText);
return document.createElement(is);
};
const processOverlayStyles = (cssText) => {
overlayContentCounter++;
const is = `vaadin-overlay-content-${overlayContentCounter}`;
const styledTemplate = document.createElement('template');
const style = document.createElement('style');
style.textContent = ':host { display: block; }' + cssText;
styledTemplate.content.appendChild(style);
if (window.ShadyCSS) {
window.ShadyCSS.prepareTemplate(styledTemplate, is);
}
// NOTE(platosha): Have to use an awkward IIFE returning class here
// to prevent this class from showing up in analysis.json & API docs.
const klass = (() => /** @private */ class extends HTMLElement {
static get is() {
return is;
}
constructor() {
super();
if (!this.shadowRoot) {
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(document.importNode(styledTemplate.content, true));
}
}
connectedCallback() {
if (window.ShadyCSS) {
window.ShadyCSS.styleElement(this);
}
}
})();
customElements.define(klass.is, klass);
overlayContentCache[cssText] = is;
return is;
};
/**
*
* `<vaadin-overlay>` is a Web Component for creating overlays. The content of the overlay
* can be populated in two ways: imperatively by using renderer callback function and
* declaratively by using Polymer's Templates.
*
* ### Rendering
*
* By default, the overlay uses the content provided by using the renderer callback function.
*
* The renderer function provides `root`, `owner`, `model` arguments when applicable.
* Generate DOM content by using `model` object properties if needed, append it to the `root`
* element and control the state of the host element by accessing `owner`. Before generating new
* content, users are able to check if there is already content in `root` for reusing it.
*
* ```html
* <vaadin-overlay id="overlay"></vaadin-overlay>
* ```
* ```js
* const overlay = document.querySelector('#overlay');
* overlay.renderer = function(root) {
* root.textContent = "Overlay content";
* };
* ```
*
* Renderer is called on the opening of the overlay and each time the related model is updated.
* DOM generated during the renderer call can be reused
* in the next renderer call and will be provided with the `root` argument.
* On first call it will be empty.
*
* **NOTE:** when the renderer property is defined, the `<template>` content is not used.
*
* ### Templating
*
* Alternatively, the content can be provided with Polymer Template.
* Overlay finds the first child template and uses that in case renderer callback function
* is not provided. You can also set a custom template using the `template` property.
*
* After the content from the template is stamped, the `content` property
* points to the content container.
*
* The overlay provides `forwardHostProp` when calling
* `Polymer.Templatize.templatize` for the template, so that the bindings
* from the parent scope propagate to the content. You can also pass
* custom `instanceProps` object using the `instanceProps` property.
*
* ```html
* <vaadin-overlay>
* <template>Overlay content</template>
* </vaadin-overlay>
* ```
*
* **NOTE:** when using `instanceProps`: because of the Polymer limitation,
* every template can only be templatized once, so it is important
* to set `instanceProps` before the `template` is assigned to the overlay.
*
* ### Styling
*
* To style the overlay content, use styles in the parent scope:
*
* - If the overlay is used in a component, then the component styles
* apply the overlay content.
* - If the overlay is used in the global DOM scope, then global styles
* apply to the overlay content.
*
* See examples for styling the overlay content in the live demos.
*
* The following Shadow DOM parts are available for styling the overlay component itself:
*
* Part name | Description
* -----------|---------------------------------------------------------|
* `backdrop` | Backdrop of the overlay
* `overlay` | Container for position/sizing/alignment of the content
* `content` | Content of the overlay
*
* The following state attributes are available for styling:
*
* Attribute | Description | Part
* ---|---|---
* `opening` | Applied just after the overlay is attached to the DOM. You can apply a CSS @keyframe animation for this state. | `:host`
* `closing` | Applied just before the overlay is detached from the DOM. You can apply a CSS @keyframe animation for this state. | `:host`
*
* The following custom CSS properties are available for styling:
*
* Custom CSS property | Description | Default value
* ---|---|---
* `--vaadin-overlay-viewport-bottom` | Bottom offset of the visible viewport area | `0` or detected offset
*
* See [ThemableMixin – how to apply styles for shadow parts](https://github.com/vaadin/vaadin-themable-mixin/wiki)
*
* @memberof Vaadin
* @mixes Vaadin.ThemableMixin
* @demo demo/index.html
*/
class OverlayElement extends Vaadin.ThemableMixin(Vaadin.DirMixin(Polymer.Element)) {
static get is() {
return 'vaadin-overlay';
}
static get properties() {
return {
/**
* When true, the overlay is visible and attached to body.
*/
opened: {
type: Boolean,
notify: true,
observer: '_openedChanged',
reflectToAttribute: true
},
/**
* Owner element passed with renderer function
* @type {HTMLElement}
*/
owner: Element,
/**
* Custom function for rendering the content of the overlay.
* Receives three arguments:
*
* - `root` The root container DOM element. Append your content to it.
* - `owner` The host element of the renderer function.
* - `model` The object with the properties related with rendering.
* @type {OverlayRenderer | null | undefined}
*/
renderer: Function,
/**
* The template of the overlay content.
* @type {HTMLTemplateElement | null | undefined}
*/
template: {
type: Object,
notify: true
},
/**
* Optional argument for `Polymer.Templatize.templatize`.
*/
instanceProps: {
type: Object
},
/**
* References the content container after the template is stamped.
* @type {!HTMLElement | undefined}
*/
content: {
type: Object,
notify: true
},
/**
* When true the overlay has backdrop on top of content when opened.
* @type {boolean}
*/
withBackdrop: {
type: Boolean,
value: false,
reflectToAttribute: true
},
/**
* Object with properties that is passed to `renderer` function
*/
model: Object,
/**
* When true the overlay won't disable the main content, showing
* it doesn’t change the functionality of the user interface.
* @type {boolean}
*/
modeless: {
type: Boolean,
value: false,
reflectToAttribute: true,
observer: '_modelessChanged'
},
/**
* When set to true, the overlay is hidden. This also closes the overlay
* immediately in case there is a closing animation in progress.
* @type {boolean}
*/
hidden: {
type: Boolean,
reflectToAttribute: true,
observer: '_hiddenChanged'
},
/**
* When true move focus to the first focusable element in the overlay,
* or to the overlay if there are no focusable elements.
* @type {boolean}
*/
focusTrap: {
type: Boolean,
value: false
},
/**
* Set to true to enable restoring of focus when overlay is closed.
* @type {boolean}
*/
restoreFocusOnClose: {
type: Boolean,
value: false,
},
/** @private */
_mouseDownInside: {
type: Boolean
},
/** @private */
_mouseUpInside: {
type: Boolean
},
/** @private */
_instance: {
type: Object
},
/** @private */
_originalContentPart: Object,
/** @private */
_contentNodes: Array,
/** @private */
_oldOwner: Element,
/** @private */
_oldModel: Object,
/** @private */
_oldTemplate: Object,
/** @private */
_oldInstanceProps: Object,
/** @private */
_oldRenderer: Object,
/** @private */
_oldOpened: Boolean
};
}
static get observers() {
return [
'_templateOrRendererChanged(template, renderer, owner, model, instanceProps, opened)'
];
}
constructor() {
super();
this._boundMouseDownListener = this._mouseDownListener.bind(this);
this._boundMouseUpListener = this._mouseUpListener.bind(this);
this._boundOutsideClickListener = this._outsideClickListener.bind(this);
this._boundKeydownListener = this._keydownListener.bind(this);
this._observer = new Polymer.FlattenedNodesObserver(this, info => {
this._setTemplateFromNodes(info.addedNodes);
});
// Listener for preventing closing of the paper-dialog and all components extending `iron-overlay-behavior`.
this._boundIronOverlayCanceledListener = this._ironOverlayCanceled.bind(this);
if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {
this._boundIosResizeListener = () => this._detectIosNavbar();
}
}
ready() {
super.ready();
this._observer.flush();
// Need to add dummy click listeners to this and the backdrop or else
// the document click event listener (_outsideClickListener) may never
// get invoked on iOS Safari (reproducible in <vaadin-dialog>
// and <vaadin-context-menu>).
this.addEventListener('click', () => {});
this.$.backdrop.addEventListener('click', () => {});
}
/** @private */
_detectIosNavbar() {
if (!this.opened) {
return;
}
const innerHeight = window.innerHeight;
const innerWidth = window.innerWidth;
const landscape = innerWidth > innerHeight;
const clientHeight = document.documentElement.clientHeight;
if (landscape && clientHeight > innerHeight) {
this.style.setProperty('--vaadin-overlay-viewport-bottom', clientHeight - innerHeight + 'px');
} else {
this.style.setProperty('--vaadin-overlay-viewport-bottom', '0');
}
}
/**
* @param {!Array<!Element>} nodes
* @protected
*/
_setTemplateFromNodes(nodes) {
this.template = nodes.filter(node => node.localName && node.localName === 'template')[0] || this.template;
}
/**
* @param {Event=} sourceEvent
* @event vaadin-overlay-close
* fired before the `vaadin-overlay` will be closed. If canceled the closing of the overlay is canceled as well.
*/
close(sourceEvent) {
var evt = new CustomEvent('vaadin-overlay-close', {bubbles: true, cancelable: true, detail: {sourceEvent: sourceEvent}});
this.dispatchEvent(evt);
if (!evt.defaultPrevented) {
this.opened = false;
}
}
connectedCallback() {
super.connectedCallback();
if (this._boundIosResizeListener) {
this._detectIosNavbar();
window.addEventListener('resize', this._boundIosResizeListener);
}
}
disconnectedCallback() {
super.disconnectedCallback();
this._boundIosResizeListener && window.removeEventListener('resize', this._boundIosResizeListener);
}
/** @private */
_ironOverlayCanceled(event) {
event.preventDefault();
}
/** @private */
_mouseDownListener(event) {
this._mouseDownInside = event.composedPath().indexOf(this.$.overlay) >= 0;
}
/** @private */
_mouseUpListener(event) {
this._mouseUpInside = event.composedPath().indexOf(this.$.overlay) >= 0;
}
/**
* We need to listen on 'click' / 'tap' event and capture it and close the overlay before
* propagating the event to the listener in the button. Otherwise, if the clicked button would call
* open(), this would happen: https://www.youtube.com/watch?v=Z86V_ICUCD4
*
* @event vaadin-overlay-outside-click
* fired before the `vaadin-overlay` will be closed on outside click. If canceled the closing of the overlay is canceled as well.
*
* @private
*/
_outsideClickListener(event) {
if (event.composedPath().indexOf(this.$.overlay) !== -1 ||
this._mouseDownInside || this._mouseUpInside) {
this._mouseDownInside = false;
this._mouseUpInside = false;
return;
}
if (!this._last) {
return;
}
const evt = new CustomEvent('vaadin-overlay-outside-click', {bubbles: true, cancelable: true, detail: {sourceEvent: event}});
this.dispatchEvent(evt);
if (this.opened && !evt.defaultPrevented) {
this.close(event);
}
}
/**
* @event vaadin-overlay-escape-press
* fired before the `vaadin-overlay` will be closed on ESC button press. If canceled the closing of the overlay is canceled as well.
*
* @private
*/
_keydownListener(event) {
if (!this._last) {
return;
}
// TAB
if (event.key === 'Tab' && this.focusTrap && !event.defaultPrevented) {
// if only tab key is pressed, cycle forward, else cycle backwards.
this._cycleTab(event.shiftKey ? -1 : 1);
event.preventDefault();
// ESC
} else if (event.key === 'Escape' || event.key === 'Esc') {
const evt = new CustomEvent('vaadin-overlay-escape-press', {bubbles: true, cancelable: true, detail: {sourceEvent: event}});
this.dispatchEvent(evt);
if (this.opened && !evt.defaultPrevented) {
this.close(event);
}
}
}
/** @protected */
_ensureTemplatized() {
this._setTemplateFromNodes(Array.from(this.children));
}
/**
* @event vaadin-overlay-open
* fired after the `vaadin-overlay` is opened.
*
* @private
*/
_openedChanged(opened, wasOpened) {
if (!this._instance) {
this._ensureTemplatized();
}
if (opened) {
// Store focused node.
this.__restoreFocusNode = this._getActiveElement();
this._animatedOpening();
Polymer.RenderStatus.afterNextRender(this, () => {
if (this.focusTrap && !this.contains(document._activeElement || document.activeElement)) {
this._cycleTab(0, 0);
}
const evt = new CustomEvent('vaadin-overlay-open', {bubbles: true});
this.dispatchEvent(evt);
});
if (!this.modeless) {
this._addGlobalListeners();
}
} else if (wasOpened) {
this._animatedClosing();
if (!this.modeless) {
this._removeGlobalListeners();
}
}
}
/** @private */
_hiddenChanged(hidden) {
if (hidden && this.hasAttribute('closing')) {
this._flushAnimation('closing');
}
}
/**
* @return {boolean}
* @protected
*/
_shouldAnimate() {
const name = getComputedStyle(this).getPropertyValue('animation-name');
const hidden = getComputedStyle(this).getPropertyValue('display') === 'none';
return !hidden && name && name != 'none';
}
/**
* @param {string} type
* @param {Function} callback
* @protected
*/
_enqueueAnimation(type, callback) {
const handler = `__${type}Handler`;
const listener = event => {
if (event && event.target !== this) {
return;
}
callback();
this.removeEventListener('animationend', listener);
delete this[handler];
};
this[handler] = listener;
this.addEventListener('animationend', listener);
}
/**
* @param {string} type
* @protected
*/
_flushAnimation(type) {
const handler = `__${type}Handler`;
if (typeof this[handler] === 'function') {
this[handler]();
}
}
/** @protected */
_animatedOpening() {
if (this.parentNode === document.body && this.hasAttribute('closing')) {
this._flushAnimation('closing');
}
this._attachOverlay();
if (!this.modeless) {
this._enterModalState();
}
this.setAttribute('opening', '');
const finishOpening = () => {
document.addEventListener('iron-overlay-canceled', this._boundIronOverlayCanceledListener);
this.removeAttribute('opening');
};
if (this._shouldAnimate()) {
this._enqueueAnimation('opening', finishOpening);
} else {
finishOpening();
}
}
/** @protected */
_attachOverlay() {
this._placeholder = document.createComment('vaadin-overlay-placeholder');
this.parentNode.insertBefore(this._placeholder, this);
document.body.appendChild(this);
this.bringToFront();
}
/** @protected */
_animatedClosing() {
if (this.hasAttribute('opening')) {
this._flushAnimation('opening');
}
if (this._placeholder) {
this._exitModalState();
if (this.restoreFocusOnClose && this.__restoreFocusNode) {
// If the activeElement is `<body>` or inside the overlay,
// we are allowed to restore the focus. In all the other
// cases focus might have been moved elsewhere by another
// component or by the user interaction (e.g. click on a
// button outside the overlay).
const activeElement = this._getActiveElement();
if (activeElement === document.body || this._deepContains(activeElement)) {
this.__restoreFocusNode.focus();
}
this.__restoreFocusNode = null;
}
this.setAttribute('closing', '');
const finishClosing = () => {
document.removeEventListener('iron-overlay-canceled', this._boundIronOverlayCanceledListener);
this._detachOverlay();
this.shadowRoot.querySelector('[part="overlay"]').style.removeProperty('pointer-events');
this.removeAttribute('closing');
};
if (this._shouldAnimate()) {
this._enqueueAnimation('closing', finishClosing);
} else {
finishClosing();
}
}
}
/** @protected */
_detachOverlay() {
this._placeholder.parentNode.insertBefore(this, this._placeholder);
this._placeholder.parentNode.removeChild(this._placeholder);
}
/**
* Returns all attached overlays in visual stacking order.
* @private
*/
static get __attachedInstances() {
return Array.from(document.body.children)
.filter(el => el instanceof OverlayElement && !el.hasAttribute('closing'))
.sort((a, b) => (a.__zIndex - b.__zIndex) || 0);
}
/**
* returns true if this is the last one in the opened overlays stack
* @return {boolean}
* @protected
*/
get _last() {
return this === OverlayElement.__attachedInstances.pop();
}
/** @private */
_modelessChanged(modeless) {
if (!modeless) {
if (this.opened) {
this._addGlobalListeners();
this._enterModalState();
}
} else {
this._removeGlobalListeners();
this._exitModalState();
}
}
/** @protected */
_addGlobalListeners() {
document.addEventListener('mousedown', this._boundMouseDownListener);
document.addEventListener('mouseup', this._boundMouseUpListener);
// Firefox leaks click to document on contextmenu even if prevented
// https://bugzilla.mozilla.org/show_bug.cgi?id=990614
document.documentElement.addEventListener('click', this._boundOutsideClickListener, true);
document.addEventListener('keydown', this._boundKeydownListener);
}
/** @protected */
_enterModalState() {
if (document.body.style.pointerEvents !== 'none') {
// Set body pointer-events to 'none' to disable mouse interactions with
// other document nodes.
this._previousDocumentPointerEvents = document.body.style.pointerEvents;
document.body.style.pointerEvents = 'none';
}
// Disable pointer events in other attached overlays
OverlayElement.__attachedInstances.forEach(el => {
if (el !== this) {
el.shadowRoot.querySelector('[part="overlay"]').style.pointerEvents = 'none';
}
});
}
/** @protected */
_removeGlobalListeners() {
document.removeEventListener('mousedown', this._boundMouseDownListener);
document.removeEventListener('mouseup', this._boundMouseUpListener);
document.documentElement.removeEventListener('click', this._boundOutsideClickListener, true);
document.removeEventListener('keydown', this._boundKeydownListener);
}
/** @protected */
_exitModalState() {
if (this._previousDocumentPointerEvents !== undefined) {
// Restore body pointer-events
document.body.style.pointerEvents = this._previousDocumentPointerEvents;
delete this._previousDocumentPointerEvents;
}
// Restore pointer events in the previous overlay(s)
const instances = OverlayElement.__attachedInstances;
let el;
// Use instances.pop() to ensure the reverse order
while (el = instances.pop()) {
if (el === this) {
// Skip the current instance
continue;
}
el.shadowRoot.querySelector('[part="overlay"]').style.removeProperty('pointer-events');
if (!el.modeless) {
// Stop after the last modal
break;
}
}
}
/** @protected */
_removeOldContent() {
if (!this.content || !this._contentNodes) {
return;
}
this._observer.disconnect();
this._contentNodes.forEach(node => {
if (node.parentNode === this.content) {
this.content.removeChild(node);
}
});
if (this._originalContentPart) {
// Restore the original <div part="content">
this.$.content.parentNode.replaceChild(this._originalContentPart, this.$.content);
this.$.content = this._originalContentPart;
this._originalContentPart = undefined;
}
this._observer.connect();
this._contentNodes = undefined;
this.content = undefined;
}
/**
* @param {!HTMLTemplateElement} template
* @param {object} instanceProps
* @protected
*/
_stampOverlayTemplate(template, instanceProps) {
this._removeOldContent();
if (!template._Templatizer) {
template._Templatizer = Polymer.Templatize.templatize(template, this, {
instanceProps: instanceProps,
forwardHostProp: function(prop, value) {
if (this._instance) {
this._instance.forwardHostProp(prop, value);
}
}
});
}
this._instance = new template._Templatizer({});
this._contentNodes = Array.from(this._instance.root.childNodes);
const templateRoot = template._templateRoot || (template._templateRoot = template.getRootNode());
const _isScoped = templateRoot !== document;
if (_isScoped) {
const isShady = window.ShadyCSS && !window.ShadyCSS.nativeShadow;
if (!this.$.content.shadowRoot) {
this.$.content.attachShadow({mode: 'open'});
}
let scopeCssText = Array.from(templateRoot.querySelectorAll('style'))
.reduce((result, style) => result + style.textContent, '');
if (isShady) {
// NOTE(platosha): ShadyCSS removes <style>’s from templates, so
// we have to use these protected APIs to get their contents back
const styleInfo = window.ShadyCSS.ScopingShim
._styleInfoForNode(templateRoot.host);
if (styleInfo) {
scopeCssText += styleInfo._getStyleRules().parsedCssText;
scopeCssText += '}';
}
}
// The overlay root’s :host styles should not apply inside the overlay
scopeCssText = scopeCssText.replace(/:host/g, ':host-nomatch');
if (scopeCssText) {
if (isShady) {
// ShadyDOM: replace the <div part="content"> with a generated
// styled custom element
const contentPart = createOverlayContent(scopeCssText);
contentPart.id = 'content';
contentPart.setAttribute('part', 'content');
this.$.content.parentNode.replaceChild(contentPart, this.$.content);
// NOTE(platosha): carry the style scope of the content part
contentPart.className = this.$.content.className;
this._originalContentPart = this.$.content;
this.$.content = contentPart;
} else {
// Shadow DOM: append a style to the content shadowRoot
const style = document.createElement('style');
style.textContent = scopeCssText;
this.$.content.shadowRoot.appendChild(style);
this._contentNodes.unshift(style);
}
}
this.$.content.shadowRoot.appendChild(this._instance.root);
this.content = this.$.content.shadowRoot;
} else {
this.appendChild(this._instance.root);
this.content = this;
}
}
/** @private */
_removeNewRendererOrTemplate(template, oldTemplate, renderer, oldRenderer) {
if (template !== oldTemplate) {
this.template = undefined;
} else if (renderer !== oldRenderer) {
this.renderer = undefined;
}
}
/**
* Manually invoke existing renderer.
*/
render() {
if (this.renderer) {
this.renderer.call(this.owner, this.content, this.owner, this.model);
}
}
/** @private */
_templateOrRendererChanged(template, renderer, owner, model, instanceProps, opened) {
if (template && renderer) {
this._removeNewRendererOrTemplate(template, this._oldTemplate, renderer, this._oldRenderer);
throw new Error('You should only use either a renderer or a template for overlay content');
}
const ownerOrModelChanged = (this._oldOwner !== owner || this._oldModel !== model);
this._oldModel = model;
this._oldOwner = owner;
const templateOrInstancePropsChanged = (this._oldInstanceProps !== instanceProps || this._oldTemplate !== template);
this._oldInstanceProps = instanceProps;
this._oldTemplate = template;
const rendererChanged = this._oldRenderer !== renderer;
this._oldRenderer = renderer;
const openedChanged = this._oldOpened !== opened;
this._oldOpened = opened;
if (template && templateOrInstancePropsChanged) {
this._stampOverlayTemplate(template, instanceProps);
} else if (renderer && (rendererChanged || openedChanged || ownerOrModelChanged)) {
this.content = this;
if (rendererChanged) {
while (this.content.firstChild) {
this.content.removeChild(this.content.firstChild);
}
}
if (opened) {
this.render();
}
}
}
/**
* @param {Element} element
* @return {boolean}
* @protected
*/
_isFocused(element) {
return element && element.getRootNode().activeElement === element;
}
/**
* @param {Element[]} elements
* @return {number}
* @protected
*/
_focusedIndex(elements) {
elements = elements || this._getFocusableElements();