all files / montage/core/ application.js

12.85% Statements 23/179
4.81% Branches 5/104
23.08% Functions 6/26
12.85% Lines 23/179
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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    274×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
/**
 * @module core/application
 * @requires event/event-manager
 * @requires template
 * @requires ui/popup/popup
 * @requires ui/popup/alert
 * @requires ui/popup/confirm
 * @requires ui/loading
 * @requires ui/popup/growl
 * @requires ui/slot
 */
 
var Target = require("./target").Target,
    MontageWindow = require("../window-loader/montage-window").MontageWindow,
    Slot;
 
require("./dom");
 
var FIRST_LOAD_KEY_SUFFIX = "-is-first-load";
 
/**
 * The application is a singleton, it initially loads and oversees the running program.
 * It is also responsible for window management.
 * The behavior of the application can be modified by implementing a delegate
 * {@link Application#delegate}.
 * It is also possible to subclass the application by specifying an
 * `applicationPrototype"` in the `package.json`.
 *
 * @class Application
 * @extends Target
 */
var Application = exports.Application = Target.specialize( /** @lends Application.prototype # */ {
 
    /**
     * Provides a reference to the Montage event manager used in the
     * application.
     *
     * @property {EventManager} value
     * @default null
     */
    eventManager: {
        value: null
    },
 
    /**
     * Provides a reference to the parent application.
     *
     * @property {Application} value
     * @default null
     */
    parentApplication: {
        value: null
    },
 
    name: {
        value: null
    },
 
    _isFirstLoad: {
        value: null
    },
 
    isFirstLoad: {
        get: function () {
            return this._isFirstLoad;
        }
    },
 
    /**
     * Provides a reference to the main application.
     *
     * @type {Application}
     * @default this
     */
    mainApplication: {
        get: function () {
            // JFD TODO: We should cache the result, would need to update it
            // when the window is detached or attached
            var mainApplication = this;
            while (mainApplication.parentApplication) {
                mainApplication = mainApplication.parentApplication;
            }
            return mainApplication;
        }
    },
 
    /**
     * possible values: "z-order", "reverse-z-order", "z-order", "reverse-open-order"
     * @private
     * @property {String} value
     */
    _windowsSortOrder: {
        value: "reverse-z-order"
    },
 
    /**
     * Determines the sort order for the Application.windows array.
     * Possible values are: z-order, reverse-z-order, open-order,
     * reverse-open-order
     *
     * @returns {string}
     * @default "reverse-z-order"
     */
    windowsSortOrder: {
        get: function () {
            if (this.parentApplication == null) {
                return this._windowsSortOrder;
            } else {
                return this.mainApplication.windowsSortOrder;
            }
        },
 
        set: function (value) {
            if (this.parentApplication == null) {
                if (["z-order", "reverse-z-order", "z-order", "reverse-open-order"].indexOf(value) !== -1) {
                    this._windowsSortOrder = value;
                }
            } else {
                this.mainApplication.windowsSortOrder = value;
            }
        }
    },
 
    /**
     * Provides a reference to all the windows opened by the main application
     * or any of its descendents, including the main window itself.
     * The list is kept sorted, the sort order is determined by the
     * `Application.windowsSortOrder` property
     *
     * @returns {Array<MontageWindow>}
     */
    windows: {
        get: function () {
            if (this.parentApplication == null) {
                if (!this._windows) {
                    var theWindow = new MontageWindow();
                    theWindow.application = this;
                    theWindow.window = window;
                    this.window = theWindow;
 
                    this._windows = [this.window];
                    this._multipleWindow = true;
                }
                return this._windows;
            } else {
                return this.mainApplication.windows;
            }
        }
    },
 
    _window: {
        value: null
    },
 
    /**
     * Provides a reference to the MontageWindow associated with the
     * application.
     *
     * @returns {MontageWindow}
     */
    window: {
        get: function () {
            if (!this._window && this == this.mainApplication) {
                var theWindow = new MontageWindow();
                theWindow.application = this;
                theWindow.window = window;
                this._window = theWindow;
            }
            return this._window;
        },
 
        set: function (value) {
            if (!this._window) {
                this._window = value;
            }
        }
    },
 
    /**
     * An array of the child windows attached to the application.
     * @type {Array<MontageWindow>}
     * @default {Array} []
     */
    attachedWindows: {
        value: []
    },
 
    /**
     * Returns the event manager for the specified window object.
     * @function
     * @param {Window} aWindow The browser window whose event manager object should be returned.
     * @returns aWindow.defaultEventMananger
     */
    eventManagerForWindow: {
        value: function (aWindow) {
            return aWindow.defaultEventMananger;
        }
    },
 
    /**
     * Return the top most window of any of the Montage Windows.
     * @type {MontageWindow}
     * @default document.defaultView
     */
    focusWindow: {
        get: function () {
            var windows = this.windows,
                sortOrder = this.windowsSortOrder;
 
            if (sortOrder == "z-order") {
                return windows[0];
            } else if (sortOrder == "reverse-z-order") {
                return windows[windows.length - 1];
            } else {
                for (var i in windows) {
                    if (windows[i].focused) {
                        return windows[i];
                    }
                }
            }
        }
    },
 
    /**
     * The application's delegate object, it can implement a
     * `willFinishLoading` method that will be called right after the
     * index.html is loaded.
     * The application delegate is also the next event target after the
     * application.
     * @type {Object}
     * @default null
     */
    delegate: {
        value: null
    },
 
    nextTarget: {
        get: function () {
            return this.delegate;
        }
    },
 
    /**
     * Opens a component in a new browser window, and registers the window with
     * the Montage event manager.
     *
     * The component URL must be in the same domain as the calling script. Can
     * be relative to the main application
     *
     * @function
     * @param {string} component, the path to the reel component to open in the
     * new window.
     * @param {string} name, the component main class name.
     * @param {Object} parameters, the new window parameters (accept same
     * parameters than window.open).
     *
     * @example
     * var app = document.application;
     * app.openWindow("docs/help.reel", "Help", "{width:300, height:500}");
     */
    openWindow: {
        value: function (component, name, parameters) {
            var thisRef = this,
                childWindow = new MontageWindow(),
                childApplication,
                event,
                windowParams = {
                    location: false,
                    // height: <pixels>,
                    // width: <pixels>,
                    // left: <pixels>,
                    // top: <pixels>,
                    menubar: false,
                    resizable: true,
                    scrollbars: true,
                    status: false,
                    titlebar: true,
                    toolbar: false
                };
 
            var loadInfo = {
                module: component,
                name: name,
                parent: window,
                callback: function (aWindow, aComponent) {
                    var sortOrder;
 
                    // Finishing the window object initialization and let the consumer knows the window is loaded and ready
                    childApplication = aWindow.document.application;
                    childWindow.window = aWindow;
                    childWindow.application = childApplication;
                    childWindow.component = aComponent;
                    childApplication.window = childWindow;
 
                    thisRef.attachedWindows.push(childWindow);
 
                    sortOrder = thisRef.mainApplication.windowsSortOrder;
                    if (sortOrder == "z-order" || sortOrder == "reverse-open-order") {
                        thisRef.windows.unshift(childWindow);
                    } else {
                        thisRef.windows.push(childWindow);
                    }
 
                    event = document.createEvent("CustomEvent");
                    event.initCustomEvent("load", true, true, null);
                    childWindow.dispatchEvent(event);
                }
            };
 
            // If this is the first time we open a window, let's install a focus listener and make sure the body element is focusable
            // Applicable only on the main application
            if (this === this.mainApplication && !this._multipleWindow) {
                var montageWindow = this.window;    // Will cause to create a Montage Window for the mainApplication and install the needed event handlers
            }
 
            if (typeof parameters == "object") {
                var param, value, separator = "", stringParamaters = "";
 
                // merge the windowParams with the parameters
                for (param in parameters) {
                    if (parameters.hasOwnProperty(param)) {
                        windowParams[param] = parameters[param];
                    }
                }
            }
 
            // now convert the windowParams into a string
            var excludedParams = ["name"];
            for (param in windowParams) {
                if (excludedParams.indexOf(param) == -1) {
                    value = windowParams[param];
                    if (typeof value == "boolean") {
                        value = value ? "yes" : "no";
                    } else {
                        value = String(value);
                        if (value.match(/[ ,"]/)) {
                            value = '"' + value.replace(/"/g, "\\\"") + '"';
                        }
                    }
                    stringParamaters += separator + param + "=" + value;
                    separator = ",";
                }
            }
 
            global.require.loadPackage({name: "montage"}).then(function (require) {
                var newWindow = window.open(require.location + "window-loader/index.html", "_blank", stringParamaters);
                newWindow.loadInfo = loadInfo;
            });
 
            return childWindow;
        }
    },
 
    /**
     * Attach a window to a parent application.
     * When a window open, it is automatically attached to the Application used
     * to create the window.
     * @function
     * @param {MontageWindow} window to detach.
     */
    attachWindow: {
        value: function (montageWindow) {
            var parentApplicaton = montageWindow.application.parentApplication,
                sortOrder;
 
            if (parentApplicaton !== this) {
                if (parentApplicaton) {
                    parentApplicaton.detachWindow(montageWindow);
                }
 
                montageWindow.parentApplication = this;
                this.attachedWindows.push(montageWindow);
 
                sortOrder = this.mainApplication.windowsSortOrder;
                if (sortOrder == "z-order" || sortOrder == "reverse-open-order") {
                    this.windows.unshift(montageWindow);
                } else {
                    this.windows.push(montageWindow);
                }
                montageWindow.focus();
            }
            return montageWindow;
        }
    },
 
    /**
     * Detach the window from its parent application.
     * If no montageWindow is specified, the current application's windows will
     * be detached.
     * @function
     * @param {MontageWindow} window to detach.
     */
    detachWindow: {
        value: function (montageWindow) {
            var index,
                parentApplicaton,
                windows = this.windows;
 
            if (montageWindow === undefined) {
                montageWindow = this.window;
            }
            parentApplicaton = montageWindow.application.parentApplication;
 
            if (parentApplicaton == this) {
                index = this.attachedWindows.indexOf(montageWindow);
                if (index !== -1) {
                    this.attachedWindows.splice(index, 1);
                }
                index = windows.indexOf(montageWindow);
                if (index !== -1) {
                    windows.splice(index, 1);
                }
                montageWindow.application.parentApplication = null;
            } else if (parentApplicaton) {
                parentApplicaton.detachWindow(montageWindow);
            }
            return montageWindow;
        }
    },
 
    constructor: {
        value: function Application() {
            Iif (window.loadInfo && !this.parentApplication) {
                this.parentApplication = window.loadInfo.parent.document.application;
            }
        }
    },
 
    _load: {
        value: function (applicationRequire, callback) {
            var rootComponent,
                self = this;
 
            this.name = applicationRequire.packageDescription.name;
            this._loadApplicationContext();
 
            // assign to the exports so that it is available in the deserialization of the template
            exports.application = self;
 
            return require.async("ui/component")
            .then(function(exports) {
                rootComponent = exports.__root__;
                rootComponent.element = document;
 
                return require("./template").instantiateDocument(window.document, applicationRequire)
                .then(function (part) {
                    self.callDelegateMethod("willFinishLoading", self);
                    rootComponent.needsDraw = true;
                    Eif (callback) {
                        callback(self);
                    }
                    return self;
                });
            });
        }
    },
 
    _loadApplicationContext: {
        value: function () {
            Eif (this._isFirstLoad === null) {
                var alreadyLoadedLocalStorageKey = this.name + FIRST_LOAD_KEY_SUFFIX,
                    hasAlreadyBeenLoaded = localStorage.getItem(alreadyLoadedLocalStorageKey);
 
                Iif (hasAlreadyBeenLoaded === null) {
                    try {
                        localStorage.setItem(alreadyLoadedLocalStorageKey, true);
                    }
                    catch(error) {
                        console.log("In private mode you are")
                    }
                }
 
                this._isFirstLoad = !hasAlreadyBeenLoaded;
            }
        }
    },
 
    /**
     * @private
     */
    _alertPopup: {value: null, enumerable: false},
    /**
     * @private
     */
    _confirmPopup: {value: null, enumerable: false},
    /**
     * @private
     */
    _notifyPopup: {value: null, enumerable: false},
    /**
     * @private
     */
    _zIndex: {value: null},
 
    /**
     * @private
     */
    _isSystemPopup: {value: function (type) {
        return (type === 'alert' || type === 'confirm' || type === 'notify');
    }},
 
    /**
     * @private
     */
    _createPopupSlot: {value: function (zIndex) {
        var slotEl = document.createElement('div');
        document.body.appendChild(slotEl);
        slotEl.style.zIndex = zIndex;
        slotEl.style.position = 'absolute';
 
        var popupSlot = new Slot();
        popupSlot.element = slotEl;
        popupSlot.attachToParentComponent();
        return popupSlot;
    }},
 
    getPopupSlot: {
        value: function (type, content, callback) {
 
            var self = this;
            require.async("ui/slot.reel/slot")
            .then(function (exports) {
                Slot = Slot || exports.Slot;
                type = type || "custom";
                var isSystemPopup = self._isSystemPopup(type), zIndex, popupSlot;
                self.popupSlots = self.popupSlots || {};
 
                if(isSystemPopup) {
                    switch (type) {
                        case "alert":
                            zIndex = 19004;
                            break;
                        case "confirm":
                            zIndex = 19003;
                            break;
                        case "notify":
                            zIndex = 19002;
                            break;
                    }
                } else {
                    // custom popup
                    if(!self._zIndex) {
                        self._zIndex = 17000;
                    } else {
                        self._zIndex = self._zIndex + 1;
                    }
                    zIndex = self._zIndex;
                }
 
                popupSlot = self.popupSlots[type];
                if (!popupSlot) {
                    popupSlot = self.popupSlots[type] = self._createPopupSlot(zIndex);
                }
                // use the new zIndex for custom popup
                if(!isSystemPopup) {
                    popupSlot.element.style.zIndex = zIndex;
                }
 
                popupSlot.content = content;
                callback.call(this, popupSlot);
 
            });
        }
    },
 
    returnPopupSlot: {value: function (type) {
        var self = this;
        if(self.popupSlots && self.popupSlots[type]) {
            var popupSlot = self.popupSlots[type];
            popupSlot.content = null;
            // is there a way to remove the Slot
            // OR should we remove the slotEl from the DOM to clean up ?
        }
 
    }},
 
    /**
     * @private
     */
    _getActivePopupSlots: {
        value: function () {
            var arr = [];
            if(this.popupSlots) {
                var keys = Object.keys(this.popupSlots);
                if(keys && keys.length > 0) {
                    var i, len = keys.length, slot;
                    for(i=0; i< len; i++) {
                        slot = this.popupSlots[keys[i]];
                        if(slot && slot.content !== null) {
                            arr.push(slot);
                        }
 
                    }
                }
            }
            return arr;
        }
    }
});