iron-overlay-behavior.html 12.1 KB
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
<!--
@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.

@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 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>