Skip to content

Instantly share code, notes, and snippets.

@blasten
Created October 2, 2015 23:45
Show Gist options
  • Save blasten/410788d20f8c8b935fdd to your computer and use it in GitHub Desktop.
Save blasten/410788d20f8c8b935fdd to your computer and use it in GitHub Desktop.
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-fit-behavior/iron-fit-behavior.html">
<link rel="import" href="../iron-resizable-behavior/iron-resizable-behavior.html">
<link rel="import" href="iron-overlay-backdrop.html">
<link rel="import" href="iron-overlay-manager.html">
<script>
/**
Use `Polymer.IronOverlayBehavior` to implement an element that can be hidden or shown, and displays
on top of other content. It includes an optional backdrop, and can be used to implement a variety
of UI controls including dialogs and drop downs. Multiple overlays may be displayed at once.
### Closing and canceling
A dialog may be hidden by closing or canceling. The difference between close and cancel is user
intent. Closing generally implies that the user acknowledged the content on the overlay. By default,
it will cancel whenever the user taps outside it or presses the escape key. This behavior is
configurable with the `no-cancel-on-esc-key` and the `no-cancel-on-outside-click` properties.
`close()` should be called explicitly by the implementer when the user interacts with a control
in the overlay element. When the dialog is canceled, the overlay fires an 'iron-overlay-canceled'
event. Call `preventDefault` on this event to prevent the overlay from closing.
### Positioning
By default the element is sized and positioned to fit and centered inside the window. You can
position and size it manually using CSS. See `Polymer.IronFitBehavior`.
### Backdrop
Set the `with-backdrop` attribute to display a backdrop behind the overlay. The backdrop is
appended to `<body>` and is of type `<iron-overlay-backdrop>`. See its doc page for styling
options.
### Limitations
The element is styled to appear on top of other content by setting its `z-index` property. You
must ensure no element has a stacking context with a higher `z-index` than its parent stacking
context. You should place this element as a child of `<body>` whenever possible.
@main
@demo demo/index.html
@polymerBehavior Polymer.IronOverlayBehavior
*/
Polymer.IronOverlayBehaviorImpl = {
properties: {
/**
* True if the overlay is currently displayed.
*/
opened: {
observer: '_openedChanged',
type: Boolean,
value: false,
notify: true
},
/**
* True if the overlay was canceled when it was last closed.
*/
canceled: {
observer: '_canceledChanged',
readOnly: true,
type: Boolean,
value: false
},
/**
* Set to true to display a backdrop behind the overlay.
*/
withBackdrop: {
type: Boolean,
value: false
},
/**
* Set to true to disable auto-focusing the overlay or child nodes with
* the `autofocus` attribute` when the overlay is opened.
*/
noAutoFocus: {
type: Boolean,
value: false
},
/**
* Set to true to disable canceling the overlay with the ESC key.
*/
noCancelOnEscKey: {
type: Boolean,
value: false
},
/**
* Set to true to disable canceling the overlay by clicking outside it.
*/
noCancelOnOutsideClick: {
type: Boolean,
value: false
},
/**
* Returns the reason this dialog was last closed.
*/
closingReason: {
// was a getter before, but needs to be a property so other
// behaviors can override this.
type: Object
},
_manager: {
type: Object,
value: Polymer.IronOverlayManager
},
_boundOnCaptureClick: {
type: Function,
value: function() {
return this._onCaptureClick.bind(this);
}
},
_boundOnCaptureKeydown: {
type: Function,
value: function() {
return this._onCaptureKeydown.bind(this);
}
}
},
listeners: {
'tap': '_onClick',
'iron-resize': '_onIronResize'
},
/**
* The backdrop element.
* @type Node
*/
get backdropElement() {
return this._backdrop;
},
get _focusNode() {
return Polymer.dom(this).querySelector('[autofocus]') || this;
},
registered: function() {
this._backdrop = document.createElement('iron-overlay-backdrop');
},
ready: function() {
this._ensureSetup();
if (this._callOpenedWhenReady) {
this._openedChanged();
}
},
detached: function() {
this.opened = false;
this._completeBackdrop();
this._manager.removeOverlay(this);
},
/**
* Toggle the opened state of the overlay.
*/
toggle: function() {
this.opened = !this.opened;
},
/**
* Open the overlay.
*/
open: function() {
this.opened = true;
this.closingReason = {canceled: false};
},
/**
* Close the overlay.
*/
close: function() {
this.opened = false;
this._setCanceled(false);
},
/**
* Cancels the overlay.
*/
cancel: function() {
var cancelEvent = this.fire('iron-overlay-canceled', undefined, {cancelable: true});
if (cancelEvent.defaultPrevented) {
return;
}
this.opened = false;
this._setCanceled(true);
},
_ensureSetup: function() {
if (this._overlaySetup) {
return;
}
this._overlaySetup = true;
this.style.outline = 'none';
this.style.display = 'none';
},
_openedChanged: function() {
if (this.opened) {
this.removeAttribute('aria-hidden');
} else {
this.setAttribute('aria-hidden', 'true');
}
// wait to call after ready only if we're initially open
if (!this._overlaySetup) {
this._callOpenedWhenReady = this.opened;
return;
}
if (this._openChangedAsync) {
this.cancelAsync(this._openChangedAsync);
}
this._toggleListeners();
if (this.opened) {
this._prepareRenderOpened();
}
// async here to allow overlay layer to become visible.
this._openChangedAsync = this.async(function() {
// overlay becomes visible here
this.style.display = '';
// force layout to ensure transitions will go
/** @suppress {suspiciousCode} */ this.offsetWidth;
if (this.opened) {
this._renderOpened();
} else {
this._renderClosed();
}
this._openChangedAsync = null;
});
},
_canceledChanged: function() {
this.closingReason = this.closingReason || {};
this.closingReason.canceled = this.canceled;
},
_toggleListener: function(enable, node, event, boundListener, capture) {
if (enable) {
// enable document-wide tap recognizer
if (event === 'tap') {
Polymer.Gestures.add(document, 'tap', null);
}
node.addEventListener(event, boundListener, capture);
} else {
// disable document-wide tap recognizer
if (event === 'tap') {
Polymer.Gestures.remove(document, 'tap', null);
}
node.removeEventListener(event, boundListener, capture);
}
},
_toggleListeners: function() {
if (this._toggleListenersAsync) {
this.cancelAsync(this._toggleListenersAsync);
}
// async so we don't auto-close immediately via a click.
this._toggleListenersAsync = this.async(function() {
this._toggleListener(this.opened, document, 'tap', this._boundOnCaptureClick, true);
this._toggleListener(this.opened, document, 'keydown', this._boundOnCaptureKeydown, true);
this._toggleListenersAsync = null;
}, 1);
},
// tasks which must occur before opening; e.g. making the element visible
_prepareRenderOpened: function() {
this._manager.addOverlay(this);
if (this.withBackdrop) {
this.backdropElement.prepare();
this._manager.trackBackdrop(this);
}
this._preparePositioning();
this.fit();
this._finishPositioning();
},
// tasks which cause the overlay to actually open; typically play an
// animation
_renderOpened: function() {
if (this.withBackdrop) {
this.backdropElement.open();
}
this._finishRenderOpened();
},
_renderClosed: function() {
if (this.withBackdrop) {
this.backdropElement.close();
}
this._finishRenderClosed();
},
_onTransitionend: function(event) {
// make sure this is our transition event.
if (event && event.target !== this) {
return;
}
if (this.opened) {
this._finishRenderOpened();
} else {
this._finishRenderClosed();
}
},
_finishRenderOpened: function() {
// focus the child node with [autofocus]
if (!this.noAutoFocus) {
this._focusNode.focus();
}
this.fire('iron-overlay-opened');
this._squelchNextResize = true;
this.async(this.notifyResize);
},
_finishRenderClosed: function() {
// hide the overlay and remove the backdrop
this.resetFit();
this.style.display = 'none';
this._completeBackdrop();
this._manager.removeOverlay(this);
this._focusNode.blur();
// focus the next overlay, if there is one
this._manager.focusOverlay();
this.fire('iron-overlay-closed', this.closingReason);
this._squelchNextResize = true;
this.async(this.notifyResize);
},
_completeBackdrop: function() {
if (this.withBackdrop) {
this._manager.trackBackdrop(this);
this.backdropElement.complete();
}
},
_preparePositioning: function() {
this.style.transition = this.style.webkitTransition = 'none';
this.style.transform = this.style.webkitTransform = 'none';
this.style.display = '';
},
_finishPositioning: function() {
this.style.display = 'none';
this.style.transform = this.style.webkitTransform = '';
// force layout to avoid application of transform
/** @suppress {suspiciousCode} */ this.offsetWidth;
this.style.transition = this.style.webkitTransition = '';
},
_applyFocus: function() {
if (this.opened) {
if (!this.noAutoFocus) {
this._focusNode.focus();
}
} else {
this._focusNode.blur();
this._manager.focusOverlay();
}
},
_onCaptureClick: function(event) {
// attempt to close asynchronously and prevent the close of a tap event is immediately heard
// on target. This is because in shadow dom due to event retargetting event.target is not
// useful.
if (!this.noCancelOnOutsideClick && (this._manager.currentOverlay() == this)) {
this._cancelJob = this.async(function() {
this.cancel();
}, 10);
}
},
_onClick: function(event) {
if (this._cancelJob) {
this.cancelAsync(this._cancelJob);
this._cancelJob = null;
}
},
_onCaptureKeydown: function(event) {
var ESC = 27;
if (!this.noCancelOnEscKey && (event.keyCode === ESC)) {
this.cancel();
event.stopPropagation();
}
},
_onIronResize: function() {
if (this._squelchNextResize) {
this._squelchNextResize = false;
return;
}
if (this.opened) {
this.refit();
}
}
/**
* Fired after the `iron-overlay` opens.
* @event iron-overlay-opened
*/
/**
* Fired when the `iron-overlay` is canceled, but before it is closed.
* Cancel the event to prevent the `iron-overlay` from closing.
* @event iron-overlay-canceled
*/
/**
* Fired after the `iron-overlay` closes.
* @event iron-overlay-closed
* @param {{canceled: (boolean|undefined)}} set to the `closingReason` attribute
*/
};
/** @polymerBehavior */
Polymer.IronOverlayBehavior = [Polymer.IronFitBehavior, Polymer.IronResizableBehavior, Polymer.IronOverlayBehaviorImpl];
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment