all files / main/ Modal.js

52.75% Statements 144/273
22.58% Branches 28/124
38.71% Functions 12/31
52.57% Lines 143/272
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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
'use strict';
 
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.EVENT_MODAL_ASYNC_TARGET_LOADED = exports.EVENT_MODAL_INIT = exports.EVENT_MODAL_OPENED = exports.EVENT_MODAL_BEFORE_CLOSED = exports.EVENT_MODAL_CLOSED = undefined;
 
var _promise = require('babel-runtime/core-js/promise');
 
var _promise2 = _interopRequireDefault(_promise);
 
var _assign = require('babel-runtime/core-js/object/assign');
 
var _assign2 = _interopRequireDefault(_assign);
 
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
 
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
 
var _createClass2 = require('babel-runtime/helpers/createClass');
 
var _createClass3 = _interopRequireDefault(_createClass2);
 
var _Settings = require('./util/Settings');
 
var _Settings2 = _interopRequireDefault(_Settings);
 
var _Event = require('./util/Event');
 
var _Event2 = _interopRequireDefault(_Event);
 
var _Util = require('./util/Util');
 
var _Util2 = _interopRequireDefault(_Util);
 
var _Widget = require('./Widget');
 
var _Widget2 = _interopRequireDefault(_Widget);
 
var _FixedWindow = require('./lib/FixedWindow');
 
var _FixedWindow2 = _interopRequireDefault(_FixedWindow);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
var KEY_ESC = 27;
/* Attribute Names */
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 David Heidrich, BowlingX <me@bowlingx.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
 
/*!
 * FlexCss.Modal
 * Licensed under the MIT License (MIT)
 * Copyright (c) 2015 David Heidrich, BowlingX <me@bowlingx.com>
 */
 
/* global KeyboardEvent */
 
var ATTR_CREATE_NEW = 'data-new-instance';
var ATTR_CLOSE = 'data-close-modal';
var ATTR_NAME = 'data-modal';
 
/* Class names */
var CLS_CONTAINER_CURRENT = 'front';
var CLS_OPEN = 'open';
var CLS_CURRENT = 'current';
var CLS_PART_OF_STACK = 'part-of-stack';
var CLS_MODAL_CONTAINER = 'modal-container';
var CLS_ANIM_END = 'modal-anim-end';
var CLS_LOADER_CONTAINER = 'loader-container';
var CLS_LOADER = 'loader';
var CLS_BACKDROP = 'backdrop';
 
/* Events */
 
/**
 * Event triggered when modal is closed
 * @type {string}
 */
var EVENT_MODAL_CLOSED = exports.EVENT_MODAL_CLOSED = 'flexcss.modal.closed';
/**
 * Event triggered before a modal is closed, cancelable
 * @type {string}
 */
var EVENT_MODAL_BEFORE_CLOSED = exports.EVENT_MODAL_BEFORE_CLOSED = 'flexcss.modal.beforeClose';
/**
 * Event triggered when a modal is opened
 * @type {string}
 */
var EVENT_MODAL_OPENED = exports.EVENT_MODAL_OPENED = 'flexcss.modal.opened';
 
/**
 * Event triggered when modal is initilized, called on target
 * @type {string}
 */
var EVENT_MODAL_INIT = exports.EVENT_MODAL_INIT = 'flexcss.modal.init';
 
/**
 * Triggered when the content of an async modal on a target is loaded, called on target
 * @type {string}
 */
var EVENT_MODAL_ASYNC_TARGET_LOADED = exports.EVENT_MODAL_ASYNC_TARGET_LOADED = 'flexcss.modal.asyncTargetLoaded';
 
/**
 * A Modal Implementation
 */
 
var Modal = function () {
    function Modal(DelegateContainer, options) {
        (0, _classCallCheck3.default)(this, Modal);
 
        var doc = global.document;
        var container = DelegateContainer instanceof HTMLElement ? DelegateContainer : doc.getElementById(DelegateContainer);
 
        // Instance vars:
        Iif (!container) {
            throw new Error('Could not found container element by given ID/Element: ' + DelegateContainer);
        }
 
        this.currentOpen = null;
 
        this.loading = false;
 
        this.container = container;
 
        /**
         * Default Options
         */
        this.options = {
            classNames: 'modal',
            closeOnEscape: true,
            closeOnBackgroundClick: true,
            destroyOnFinish: false,
            fixedContainer: true,
            containerClassNames: ''
        };
 
        (0, _assign2.default)(this.options, options);
 
        // Container where events are delegated
        this.eventContainer = null;
        this.eventFunction = null;
 
        this.dataMainPageContainer = global.document.body;
 
        this.currentScrollTop = 0;
 
        this.modalContainer = null;
 
        // Destroy full modal instance when no dialogs are bind to?
        // Otherwise container is recycled
        this.destroyOnFinish = this.options.destroyOnFinish;
    }
 
    /**
     * Removes this modal from global stack
     * Will handle fixing main html element too
     * @private
     * @param n
     */
 
 
    (0, _createClass3.default)(Modal, [{
        key: '_removeModalFromStack',
        value: function _removeModalFromStack(n) {
            var t = Modal._modalInstances.indexOf(n);
            if (t > -1) {
                Modal._modalInstances.splice(t, 1);
                _FixedWindow2.default.getInstance().close();
            }
        }
 
        /**
         * Modal container that contains all `stacked` modals for this instance
         * @returns {HTMLElement}
         */
 
    }, {
        key: 'getModalContainer',
        value: function getModalContainer() {
            return this.modalContainer;
        }
 
        /**
         * Closes the current open modal of this stack
         * @params [e], optional event
         * @returns {*}
         */
 
    }, {
        key: 'close',
        value: function close(e) {
            var self = this;
 
            var options = self.currentOpen ? _Util2.default.applyOptionsFromElement(self.currentOpen, _Util2.default.copy(self.options)) : self.options;
 
            // close only on keyboard if instance should
            if (!options.closeOnEscape && e instanceof KeyboardEvent) {
                return false;
            }
 
            // close only on background if instance should
            if (!options.closeOnBackgroundClick && e && e.type === _Settings2.default.getTabEvent() && !e.target.hasAttribute(ATTR_CLOSE)) {
                return false;
            }
 
            // if an instance is currently loading, prevent from closing
            if (self.loading) {
                return false;
            }
 
            if (e) {
                e.preventDefault();
            }
 
            if (self.currentOpen) {
                // dispatch beforeClose event, if prevented prevent modal from closing
                var ev = _Event2.default.dispatchAndFire(self.currentOpen, EVENT_MODAL_BEFORE_CLOSED);
                if (ev.defaultPrevented) {
                    return false;
                }
 
                this._finishState(self.currentOpen);
                // if there is an previous modal
                if (self.currentOpen.prevModal) {
                    // switch to the next modal
                    return self.switchModals(self.currentOpen.prevModal, self.currentOpen.prevModal.prevModal || null);
                }
 
                // finally trigger closed event
                _Event2.default.dispatch(self.currentOpen, EVENT_MODAL_CLOSED).withOriginal(e).fire();
            }
            self._removeModalFromStack(self.currentOpen);
 
            // Full stack closed:
            self.currentOpen = null;
            if (self.modalContainer) {
                // setup next open
                var lastContainer = Modal._modalInstances[Modal._modalInstances.length - 1];
                var classList = self.modalContainer.classList;
                classList.remove(CLS_CONTAINER_CURRENT);
                classList.remove(CLS_BACKDROP);
                classList.remove(CLS_OPEN);
                // Remove all current classes from child-nodes
                for (var i = 0; i < self.modalContainer.childNodes.length; i++) {
                    var node = self.modalContainer.childNodes[i];
                    var cl = node.classList;
                    // remove applied styles
                    self._finishState(node);
                    cl.remove(CLS_CURRENT);
                    cl.remove(CLS_PART_OF_STACK);
                }
                if (lastContainer) {
                    lastContainer.parentNode.classList.add(CLS_CONTAINER_CURRENT);
                }
            }
 
            if (self.destroyOnFinish) {
                self.destroy();
            }
            return self;
        }
 
        /**
         * Resets a target when newly initilizes
         * @param target
         * @private
         */
 
    }, {
        key: '_finishState',
        value: function _finishState(target) {
            target.classList.remove(CLS_ANIM_END);
        }
 
        /**
         * Handler called when a Modal has finished an animation
         * @param e
         * @param self
         * @private
         */
 
    }, {
        key: '_finishAnim',
        value: function _finishAnim(e, self) {
            e.target.classList.add(CLS_ANIM_END);
            e.target.removeEventListener(e.type, self, true);
        }
 
        /**
         * Brings the given modal to front
         * @param co
         * @param last
         */
 
    }, {
        key: 'switchModals',
        value: function switchModals(co, last) {
            co.prevModal = last;
            Modal._modalInstances.push(co);
            _FixedWindow2.default.getInstance().open(this, this.modalContainer);
            Iif (last) {
                this._finishState(last);
                _Util2.default.prefixedAnimateEvent(last, 'AnimationEnd', this._finishAnim);
                last.classList.add(CLS_PART_OF_STACK);
            }
            // set new currentOpen
            this.currentOpen = co;
 
            // bring current container to the front
            var instances = Modal._modalInstances;
 
            for (var m = 0; m < instances.length; m++) {
                instances[m].parentNode.classList.remove(CLS_CONTAINER_CURRENT);
            }
            this.modalContainer.classList.add(CLS_CONTAINER_CURRENT);
            // remove animations if animations has been completed, fixes various bugs:
            // - fixes nested scrolling element issue in iOS Browsers / Mobile-Safari
            _Util2.default.prefixedAnimateEvent(co, 'AnimationEnd', this._finishAnim);
 
            for (var i = 0; i < this.modalContainer.childNodes.length; i++) {
                var n = this.modalContainer.childNodes[i];
                var isCurrent = n.classList.contains(CLS_CURRENT);
                Eif (n === co) {
                    co.classList.add(CLS_CURRENT);
                    co.classList.remove(CLS_PART_OF_STACK);
                    this._finishState(co);
                } else {
                    n.classList.remove(CLS_CURRENT);
                    if (isCurrent) {
                        this._removeModalFromStack(n);
                        _Event2.default.dispatchAndFire(n, EVENT_MODAL_CLOSED);
                    }
                }
            }
        }
 
        /**
         * Creates a Modal and opens it (later)
         * @param e
         * @returns {Promise|boolean}
         */
 
    }, {
        key: 'createWidget',
        value: function createWidget(e) {
            var _this = this;
 
            var self = this;
            Iif (this.loading) {
                return false;
            }
 
            // check if another modal has registered events on this dom path:
            Iif (e && e.target) {
                var foundInstance = _Util2.default.parentsUntil(e.target, function (node) {
                    return node && node.flexModalInstance;
                });
 
                // if another instance has been found, abort
                if (foundInstance !== this.container) {
                    return false;
                }
            }
            var targetContent = void 0;
            var future = void 0;
            var widget = void 0;
            var target = void 0;
            var hasTarget = true;
            var isHtmlElement = e instanceof HTMLElement;
            var isWidget = _Widget2.default.isWidget(e);
            Eif (isHtmlElement || isWidget) {
                Iif (isHtmlElement) {
                    targetContent = e;
                } else {
                    widget = e;
                    targetContent = widget.element;
                }
            } else {
                target = e.target;
                if (!target) {
                    throw new Error('Could not find target, did you pass an event, a HTMLElement or an Widget?');
                }
                hasTarget = target.hasAttribute(ATTR_NAME);
                targetContent = target.getAttribute(ATTR_NAME);
                widget = _Widget2.default.findWidget(target);
                if (target.hasAttribute(ATTR_CREATE_NEW) && !e.newInstance) {
                    var newInstance = new Modal(this.container).setDestroyOnFinish(true);
                    e.newInstance = true;
                    newInstance.fromEvent(e).then(function () {
                        newInstance.registerEvents(newInstance.getModalContainer());
                    });
                    return false;
                }
                if (hasTarget) {
                    e.stopImmediatePropagation();
                    e.preventDefault();
                }
            }
 
            Iif (!hasTarget) {
                return false;
            }
 
            var modalContainerClasses = this.modalContainer ? this.modalContainer.classList : [];
 
            // lazy create modal container
            Eif (!this.modalContainer) {
                this.modalContainer = global.document.createElement('div');
                this.modalContainer.className = CLS_MODAL_CONTAINER + ' ' + this.options.containerClassNames + ' ' + CLS_OPEN;
                var closeModalFunction = function closeModalFunction(ce) {
                    if (_this.loading) {
                        return false;
                    }
                    if (_Util2.default.isPartOfNode(ce.target, _this.currentOpen)) {
                        if (!ce.target.hasAttribute(ATTR_CLOSE)) {
                            return false;
                        }
                    }
                    _this.close(ce);
                };
 
                this.modalContainer.addEventListener(_Settings2.default.getTabEvent(), closeModalFunction, false);
 
                modalContainerClasses = this.modalContainer.classList;
                this.container.appendChild(this.modalContainer);
            } else {
                modalContainerClasses.add(CLS_OPEN);
            }
 
            var loader = void 0;
            var doc = global.document;
            var toggleLoader = function toggleLoader(show) {
                if (show) {
                    loader = doc.createElement('div');
                    loader.className = CLS_LOADER_CONTAINER;
                    var loaderLoader = doc.createElement('div');
                    loaderLoader.className = CLS_LOADER;
                    loader.appendChild(loaderLoader);
                    _this.modalContainer.appendChild(loader);
                } else {
                    loader.parentNode.removeChild(loader);
                }
            };
            modalContainerClasses.add('loading');
            modalContainerClasses.add(CLS_CONTAINER_CURRENT);
 
            requestAnimationFrame(function () {
                requestAnimationFrame(function () {
                    modalContainerClasses.add(CLS_BACKDROP);
                });
            });
 
            this.loading = true;
            toggleLoader(true);
            var async = widget ? widget.getAsync() : null;
            Eif (_Widget2.default.isWidget(widget) && async) {
                future = async.then(function (r) {
                    var result = void 0;
                    Eif (r instanceof HTMLElement || r instanceof DocumentFragment) {
                        result = r;
                    } else {
                        // Create container Element:
                        var element = doc.createElement('div');
                        element.className = self.options.classNames;
                        element.innerHTML = r;
                        element.id = _Util2.default.guid();
                        result = element;
                    }
                    widget.finalContent = result;
                    _Event2.default.dispatchAndFire(target, EVENT_MODAL_ASYNC_TARGET_LOADED);
                    return result;
                });
            } else {
                var el = targetContent instanceof HTMLElement || targetContent instanceof DocumentFragment ? targetContent : doc.getElementById(targetContent);
                if (el) {
                    future = new _promise2.default(function (resolve) {
                        resolve(el);
                    });
                } else {
                    throw new Error('Could not found given modal element (content) with ID: ' + targetContent);
                }
            }
 
            _Event2.default.dispatchAndFire(target, EVENT_MODAL_INIT);
 
            return future.then(function (thisEl) {
                thisEl.hfWidgetInstance = _this;
                _this.modalContainer.appendChild(thisEl);
                modalContainerClasses.remove('loading');
                _this.loading = false;
                toggleLoader(false);
                _this.open(thisEl, true, e);
                return thisEl;
            });
        }
 
        /**
         * Open's an already rendered modal
         * @param {HTMLElement} modal
         * @param {Boolean} [internal], set to true to prevent container management
         * @param {Boolean} [maybeEvent], optional event-object that triggered open
         */
 
    }, {
        key: 'open',
        value: function open(modal, internal, maybeEvent) {
            Iif (!internal) {
                this.modalContainer.classList.add('open');
            }
            this.switchModals(modal, this.currentOpen);
 
            _Event2.default.dispatch(modal, EVENT_MODAL_OPENED).withOriginal(maybeEvent).fire();
        }
    }, {
        key: 'registerEvents',
        value: function registerEvents(delegate) {
            var _this2 = this;
 
            var delegateContainer = delegate || this.container;
            // Modals should always be fixed
            _FixedWindow2.default.getInstance().addScreenConstraint(Modal, function () {
                return true;
            });
            // register modal instance so we can detect multiple registrars
            delegateContainer.flexModalInstance = this;
            this.eventFunction = function () {
                for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
                    args[_key] = arguments[_key];
                }
 
                _this2.createWidget.apply(_this2, args);
            };
            delegateContainer.addEventListener(_Settings2.default.getTabEvent(), this.eventFunction, false);
 
            this.eventContainer = delegateContainer;
            return this;
        }
 
        /**
         * Creates a new Dialog Instance either directly from HTML Element or a Widget instance
         * @param {HTMLElement|Widget} widget instance or html element
         * @returns {Promise}
         */
 
    }, {
        key: 'fromWidget',
        value: function fromWidget(widget) {
            return this.createWidget(widget);
        }
 
        /**
         * Creates a Widget from event
         * @param e
         * @returns {Promise}
         */
 
    }, {
        key: 'fromEvent',
        value: function fromEvent(e) {
            return this.createWidget(e);
        }
    }, {
        key: 'setDestroyOnFinish',
        value: function setDestroyOnFinish(v) {
            this.destroyOnFinish = v;
            return this;
        }
 
        /**
         * Destroy this widget instance, cleans empty DOM nodes
         * Will use fast MutationObserver if available, otherwise falls back to DOMNodeRemoved event
         */
 
    }, {
        key: 'destroy',
        value: function destroy() {
            var modalContainer = this.modalContainer;
            var isEmptyContainer = modalContainer.childNodes.length === 0;
            // Remove event listener on destroy, do not remove DOM node
            if (this.eventContainer) {
                this.eventContainer.removeEventListener(_Settings2.default.getTabEvent(), this.eventFunction, true);
            }
 
            if (isEmptyContainer) {
                if (modalContainer.parentNode) {
                    modalContainer.parentNode.removeChild(modalContainer);
                }
            }
            if (global.MutationObserver) {
                var observer = new MutationObserver(function (mutations) {
                    mutations.forEach(function () {
                        if (modalContainer.childNodes.length === 0) {
                            modalContainer.parentNode.removeChild(modalContainer);
                            observer.disconnect();
                        }
                    });
                });
                observer.observe(modalContainer, {
                    childList: true
                });
            } else {
                modalContainer.addEventListener('DOMNodeRemoved', function (e) {
                    if (e.target !== modalContainer && modalContainer.childNodes.length - 1 === 0) {
                        modalContainer.parentNode.removeChild(modalContainer);
                    }
                });
            }
        }
    }]);
    return Modal;
}();
 
// Static variable that keeps track of all open modals
 
 
Modal._modalInstances = [];
 
Eif (global.addEventListener) {
    // Global keydown listener for modal
    global.addEventListener('keydown', function (e) {
        if (e.keyCode === KEY_ESC) {
            var lastModal = Modal._modalInstances[Modal._modalInstances.length - 1];
            if (lastModal) {
                _Widget2.default.findWidget(lastModal).close(e);
            }
        }
    });
}
 
exports.default = Modal;