UNPKG

widget-router

Version:

Widget Router is another Typescript (also JavaScript) Router, but this one works better if used in widgets inside HTML

1,557 lines (1,377 loc) 136 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("WidgetRouter", [], factory); else if(typeof exports === 'object') exports["WidgetRouter"] = factory(); else root["WidgetRouter"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = isFunction var toString = Object.prototype.toString function isFunction (fn) { var string = toString.call(fn) return string === '[object Function]' || (typeof fn === 'function' && string !== '[object RegExp]') || (typeof window !== 'undefined' && // IE8 and below (fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt)) }; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var WidgetRouter_1 = __webpack_require__(2); exports.WidgetRouter = WidgetRouter_1.WidgetRouter; var RouteResult_1 = __webpack_require__(13); exports.RouteResult = RouteResult_1.RouteResult; var RouteConfig_1 = __webpack_require__(14); exports.RouteConfig = RouteConfig_1.RouteConfig; var Routes_1 = __webpack_require__(15); exports.Routes = Routes_1.Routes; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var Utilities_1 = __webpack_require__(3); var TemplateProvider_1 = __webpack_require__(4); var event_handler_manager_1 = __webpack_require__(12); var WidgetRouter = (function (_super) { __extends(WidgetRouter, _super); //public templatesCollection: Object; function WidgetRouter(containerId, routeConfig, appScope, controllerHelper) { var _this = _super.call(this) || this; var currentContainer = document.querySelector(containerId); if (currentContainer === undefined || currentContainer === null) { throw new Error(containerId + ' was not found inside document, please set a valid container Id selector.'); } _this.containerId = containerId; _this.routeConfig = routeConfig; _this.appScope = appScope ? appScope : {}; routeConfig.routes.forEach(function (route) { _this.appScope[route.name] = {}; }); _this.controllerHelper = controllerHelper; _this.pageIdPrefix = routeConfig.pageIdPrefix !== undefined && routeConfig.pageIdPrefix !== null ? routeConfig.pageIdPrefix : ''; _this.controllersInitiated = {}; _this.routeConfig.routes.forEach(function (route) { var currentPage = document.querySelector(_this.containerId).querySelector('#' + _this.pageIdPrefix + route.name); if (currentPage === undefined || currentPage === null) { document.querySelector(_this.containerId).innerHTML += '<div id="' + _this.pageIdPrefix + route.name + '" style="display:none;"></div>'; } else { currentPage.style.display = 'none'; } }); _this.templateProvider = new TemplateProvider_1.TemplateProvider(); if (_this.routeConfig.usingTemplates) { if (controllerHelper === undefined && controllerHelper === null) { controllerHelper = {}; } controllerHelper.templatesCollection = {}; } _this.attach(['beforego', 'aftergo']); return _this; } WidgetRouter.prototype.executeController = function (routeName, params, templateContent, initController, currentRouteConfig) { var _this = this; var dfd = new Promise(function (resolve, reject) { var routeResult = { routeName: routeName, routeParams: params, routeScope: _this.appScope[routeName], router: _this, controllerHelper: _this.controllerHelper }; if (_this.routeConfig.usingTemplates) { if (_this.controllerHelper.templatesCollection === undefined || _this.controllerHelper.templatesCollection === null) { _this.controllerHelper.templatesCollection = {}; } _this.controllerHelper.templatesCollection[routeName] = templateContent; } if (initController && Utilities_1.Utilities.isFunction(currentRouteConfig.controller)) { (function () { try { var controllerResult = currentRouteConfig.controller(routeResult); if (controllerResult !== undefined && controllerResult !== null && !!controllerResult.then && typeof controllerResult.then === 'function') { controllerResult.then(function () { resolve(routeResult); }).catch(function (err) { console.error(err); }); } else { _this.controllersInitiated[routeName] = true; resolve(routeResult); } } catch (e) { console.error(e); reject(e); } })(); } else { resolve(routeResult); } }); return dfd; }; WidgetRouter.prototype.go = function (routeName, params, noCache, initController) { var _this = this; var dfd = new Promise(function (resolve, reject) { _this.trigger('beforego').then(function () { var currentRouteConfig = _this.routeConfig.routes.find(function (route) { return route.name === routeName; }); if (currentRouteConfig === undefined || currentRouteConfig == null) { throw new Error('Route Configuration not found for that Route Name'); } _this.routeConfig.afterRouteInitController = _this.routeConfig.afterRouteInitController !== undefined && _this.routeConfig.afterRouteInitController !== null ? _this.routeConfig.afterRouteInitController : true; initController = initController !== undefined && initController !== null ? initController : _this.routeConfig.afterRouteInitController; initController = currentRouteConfig.controller !== undefined && currentRouteConfig.controller !== null ? initController : false; if (_this.activePage !== undefined && _this.activePage !== null && _this.activePage.trim() !== '') { var activePage = document.querySelector(_this.containerId).querySelector('#' + _this.pageIdPrefix + _this.activePage); activePage.style.display = 'none'; } var newActivePage = document.querySelector(_this.containerId).querySelector('#' + _this.pageIdPrefix + routeName); if (newActivePage === undefined || newActivePage === null) { document.querySelector(_this.containerId).innerHTML += '<div id="' + _this.pageIdPrefix + routeName + '">'; newActivePage = document.querySelector(_this.containerId).querySelector('#' + _this.pageIdPrefix + routeName); } else { newActivePage.style.display = 'block'; } _this.activePage = routeName; if (currentRouteConfig.templateFile !== undefined && currentRouteConfig.templateFile !== null && currentRouteConfig.templateFile.trim() !== '') { _this.getTemplateFromFile(currentRouteConfig.templateFile).then(function (templateContent) { if (!_this.routeConfig.usingTemplates) { newActivePage.innerHTML = templateContent; } _this.executeController(routeName, params, templateContent, initController, currentRouteConfig).then(function (routeResult) { _this.trigger('aftergo').then(function () { resolve(routeResult); }).catch(function (err) { return reject(err); }).catch(function (err) { return reject(err); }); }).catch(function (err) { console.error(err); reject(err); }); }).catch(function (err) { console.error(err); reject(err); }); } else { if (newActivePage !== undefined && newActivePage !== null && currentRouteConfig.template !== undefined && currentRouteConfig.template !== null && currentRouteConfig.template.trim() !== '' && !_this.routeConfig.usingTemplates) { newActivePage.innerHTML = currentRouteConfig.template; } _this.executeController(routeName, params, currentRouteConfig.template, initController, currentRouteConfig).then(function (routeResult) { _this.trigger('aftergo').then(function () { resolve(routeResult); }).catch(function (err) { return reject(err); }).catch(function (err) { return reject(err); }); }).catch(function (err) { console.error(err); reject(err); }); } }).catch(function (err) { console.error(err); }); }); return dfd; }; WidgetRouter.prototype.getTemplateFromFile = function (templateFile) { var _this = this; var dfd = new Promise(function (resolve, reject) { _this.templateProvider.get(templateFile).then(function (templateContent) { resolve(templateContent); }).catch(function (error) { console.log(error); reject(error); }); }); return dfd; }; return WidgetRouter; }(event_handler_manager_1.EventHandlerManager)); exports.WidgetRouter = WidgetRouter; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Utilities; (function (Utilities) { function isFunction(obj) { return obj !== undefined && obj !== null && !!(obj && obj.constructor && obj.call && obj.apply); } Utilities.isFunction = isFunction; })(Utilities = exports.Utilities || (exports.Utilities = {})); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var xhr = __webpack_require__(5); var TemplateProvider = (function () { function TemplateProvider() { } TemplateProvider.prototype.get = function (template, noCache) { var version = ''; if (noCache) { version = '?v=' + new Date().getTime().toString(); } var dfd = new Promise(function (resolve, reject) { xhr.get(template + version, { timeout: 4000 }, function (error, response, body) { if (error) { reject(error); } else { resolve(body); } }); }); return dfd; }; return TemplateProvider; }()); exports.TemplateProvider = TemplateProvider; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var window = __webpack_require__(6) var isFunction = __webpack_require__(0) var parseHeaders = __webpack_require__(8) var xtend = __webpack_require__(11) module.exports = createXHR createXHR.XMLHttpRequest = window.XMLHttpRequest || noop createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) { createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) { options = initParams(uri, options, callback) options.method = method.toUpperCase() return _createXHR(options) } }) function forEachArray(array, iterator) { for (var i = 0; i < array.length; i++) { iterator(array[i]) } } function isEmpty(obj){ for(var i in obj){ if(obj.hasOwnProperty(i)) return false } return true } function initParams(uri, options, callback) { var params = uri if (isFunction(options)) { callback = options if (typeof uri === "string") { params = {uri:uri} } } else { params = xtend(options, {uri: uri}) } params.callback = callback return params } function createXHR(uri, options, callback) { options = initParams(uri, options, callback) return _createXHR(options) } function _createXHR(options) { if(typeof options.callback === "undefined"){ throw new Error("callback argument missing") } var called = false var callback = function cbOnce(err, response, body){ if(!called){ called = true options.callback(err, response, body) } } function readystatechange() { if (xhr.readyState === 4) { setTimeout(loadFunc, 0) } } function getBody() { // Chrome with requestType=blob throws errors arround when even testing access to responseText var body = undefined if (xhr.response) { body = xhr.response } else { body = xhr.responseText || getXml(xhr) } if (isJson) { try { body = JSON.parse(body) } catch (e) {} } return body } function errorFunc(evt) { clearTimeout(timeoutTimer) if(!(evt instanceof Error)){ evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) } evt.statusCode = 0 return callback(evt, failureResponse) } // will load the data & process the response in a special response object function loadFunc() { if (aborted) return var status clearTimeout(timeoutTimer) if(options.useXDR && xhr.status===undefined) { //IE8 CORS GET successful response doesn't have a status field, but body is fine status = 200 } else { status = (xhr.status === 1223 ? 204 : xhr.status) } var response = failureResponse var err = null if (status !== 0){ response = { body: getBody(), statusCode: status, method: method, headers: {}, url: uri, rawRequest: xhr } if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE response.headers = parseHeaders(xhr.getAllResponseHeaders()) } } else { err = new Error("Internal XMLHttpRequest Error") } return callback(err, response, response.body) } var xhr = options.xhr || null if (!xhr) { if (options.cors || options.useXDR) { xhr = new createXHR.XDomainRequest() }else{ xhr = new createXHR.XMLHttpRequest() } } var key var aborted var uri = xhr.url = options.uri || options.url var method = xhr.method = options.method || "GET" var body = options.body || options.data var headers = xhr.headers = options.headers || {} var sync = !!options.sync var isJson = false var timeoutTimer var failureResponse = { body: undefined, headers: {}, statusCode: 0, method: method, url: uri, rawRequest: xhr } if ("json" in options && options.json !== false) { isJson = true headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user if (method !== "GET" && method !== "HEAD") { headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user body = JSON.stringify(options.json === true ? body : options.json) } } xhr.onreadystatechange = readystatechange xhr.onload = loadFunc xhr.onerror = errorFunc // IE9 must have onprogress be set to a unique function. xhr.onprogress = function () { // IE must die } xhr.onabort = function(){ aborted = true; } xhr.ontimeout = errorFunc xhr.open(method, uri, !sync, options.username, options.password) //has to be after open if(!sync) { xhr.withCredentials = !!options.withCredentials } // Cannot set timeout with sync request // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent if (!sync && options.timeout > 0 ) { timeoutTimer = setTimeout(function(){ if (aborted) return aborted = true//IE9 may still call readystatechange xhr.abort("timeout") var e = new Error("XMLHttpRequest timeout") e.code = "ETIMEDOUT" errorFunc(e) }, options.timeout ) } if (xhr.setRequestHeader) { for(key in headers){ if(headers.hasOwnProperty(key)){ xhr.setRequestHeader(key, headers[key]) } } } else if (options.headers && !isEmpty(options.headers)) { throw new Error("Headers cannot be set on an XDomainRequest object") } if ("responseType" in options) { xhr.responseType = options.responseType } if ("beforeSend" in options && typeof options.beforeSend === "function" ) { options.beforeSend(xhr) } // Microsoft Edge browser sends "undefined" when send is called with undefined value. // XMLHttpRequest spec says to pass null as body to indicate no body // See https://github.com/naugtur/xhr/issues/100. xhr.send(body || null) return xhr } function getXml(xhr) { if (xhr.responseType === "document") { return xhr.responseXML } var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror" if (xhr.responseType === "" && !firefoxBugTakenEffect) { return xhr.responseXML } return null } function noop() {} /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var win; if (typeof window !== "undefined") { win = window; } else if (typeof global !== "undefined") { win = global; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } module.exports = win; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }), /* 7 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { var trim = __webpack_require__(9) , forEach = __webpack_require__(10) , isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } module.exports = function (headers) { if (!headers) return {} var result = {} forEach( trim(headers).split('\n') , function (row) { var index = row.indexOf(':') , key = trim(row.slice(0, index)).toLowerCase() , value = trim(row.slice(index + 1)) if (typeof(result[key]) === 'undefined') { result[key] = value } else if (isArray(result[key])) { result[key].push(value) } else { result[key] = [ result[key], value ] } } ) return result } /***/ }), /* 9 */ /***/ (function(module, exports) { exports = module.exports = trim; function trim(str){ return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ return str.replace(/^\s*/, ''); }; exports.right = function(str){ return str.replace(/\s*$/, ''); }; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(0) module.exports = forEach var toString = Object.prototype.toString var hasOwnProperty = Object.prototype.hasOwnProperty function forEach(list, iterator, context) { if (!isFunction(iterator)) { throw new TypeError('iterator must be a function') } if (arguments.length < 3) { context = this } if (toString.call(list) === '[object Array]') forEachArray(list, iterator, context) else if (typeof list === 'string') forEachString(list, iterator, context) else forEachObject(list, iterator, context) } function forEachArray(array, iterator, context) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { iterator.call(context, array[i], i, array) } } } function forEachString(string, iterator, context) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. iterator.call(context, string.charAt(i), i, string) } } function forEachObject(object, iterator, context) { for (var k in object) { if (hasOwnProperty.call(object, k)) { iterator.call(context, object[k], k, object) } } } /***/ }), /* 11 */ /***/ (function(module, exports) { module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else if(typeof define === 'function' && define.amd) define("EventHandlerManager", [], factory); else if(typeof exports === 'object') exports["EventHandlerManager"] = factory(); else root["EventHandlerManager"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Iteration = __webpack_require__(1); module.exports = ArrayIterator; function ArrayIterator(iterable, start, stop, step) { this.array = iterable; this.start = start || 0; this.stop = stop || Infinity; this.step = step || 1; } ArrayIterator.prototype.next = function () { var iteration; if (this.start < Math.min(this.array.length, this.stop)) { iteration = new Iteration(this.array[this.start], false, this.start); this.start += this.step; } else { iteration = new Iteration(undefined, true); } return iteration; }; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = Iteration; function Iteration(value, done, index) { this.value = value; this.done = done; this.index = index; } Iteration.prototype.equals = function (other) { return ( typeof other == 'object' && other.value === this.value && other.done === this.done && other.index === this.index ); }; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EventHandlerManager_1 = __webpack_require__(3); exports.EventHandlerManager = EventHandlerManager_1.EventHandlerManager; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Q = __webpack_require__(4); var EventHandlerManager = (function () { function EventHandlerManager() { this.events = {}; this.eventsRefs = {}; this.idCounter = 0; } EventHandlerManager.prototype.attach = function (events) { var _this = this; if (events instanceof Array) { events.forEach(function (event) { _this.events[event] = []; }); } else { this.events[events] = []; } }; EventHandlerManager.prototype.on = function (events, action) { var _this = this; var eventsList = []; if (!(events instanceof Array)) { eventsList.push(events); } else { eventsList = events; } var eventIdList = []; eventsList.forEach(function (event) { var currentEvent = { eventId: ++_this.idCounter, action: function (event, sender) { return Q.spread([event, sender], function (event, sender) { return action(event, sender); }); } }; _this.events[event].push(currentEvent); eventIdList.push(currentEvent.eventId); _this.eventsRefs[currentEvent.eventId] = currentEvent; }); if (eventIdList.length === 1) { return eventIdList[0]; } return eventIdList; }; EventHandlerManager.prototype.off = function (eventRef) { var _this = this; if (typeof eventRef === "number") { this.eventsRefs[eventRef] = null; var currentEvent = this.events.find(function (event) { return event.eventId === eventRef; }); if (currentEvent !== undefined && currentEvent !== null) { currentEvent = null; } } else if (typeof eventRef === "string") { this.events[eventRef].forEach(function (event) { _this.eventsRefs[event.eventId] = null; }); this.events[eventRef] = null; } else if (eventRef === undefined || eventRef === null) { this.events = {}; this.eventsRefs = {}; } }; EventHandlerManager.prototype.trigger = function (events, sequential, order) { var _this = this; var eventsList = []; if (!(events instanceof Array)) { eventsList.push(events); } else { eventsList = events; } var executionQueue = []; eventsList.forEach(function (eventParam) { _this.events[eventParam].forEach(function (event) { executionQueue.push(function () { return event.action(eventParam, _this); }); }); }); if (sequential) { if (order === 'reverse') { return executionQueue.slice().reverse().reduce(Q.when, Q()); } return executionQueue.reduce(Q.when, Q()); } var asyncQueue = []; executionQueue.forEach(function (callback) { asyncQueue.push(callback()); }); return Q.all(asyncQueue); }; return EventHandlerManager; }()); exports.EventHandlerManager = EventHandlerManager; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) {/* vim:ts=4:sts=4:sw=4: */ /*! * * Copyright 2009-2013 Kris Kowal under the terms of the MIT * license found at http://github.com/kriskowal/q/raw/master/LICENSE * * With parts by Tyler Close * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found * at http://www.opensource.org/licenses/mit-license.html * Forked at ref_send.js version: 2009-05-11 * * With parts by Mark Miller * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*global -WeakMap */ var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported // by Q. var qStartingLine = captureLine(); var qFileName; var WeakMap = __webpack_require__(6); var iterate = __webpack_require__(7); var asap = __webpack_require__(9); function isObject(value) { return value === Object(value); } // long stack traces var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, promise) { // If possible, transform the error stack trace by removing Node and Q // cruft, then concatenating with the stack trace of `promise`. See #57. if (hasStacks && promise.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var p = promise; !!p && handlers.get(p); p = handlers.get(p).became) { if (p.stack) { stacks.unshift(p.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { if (Q.isIntrospective) { return stackString; } var lines = stackString.split("\n"); var desiredLines = []; for (var i = 0; i < lines.length; ++i) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" // In IE10 function name can have spaces ("Anonymous function") O_o var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0]; var lineNumber = fileNameAndLineNumber[1]; return fileName === qFileName && lineNumber >= qStartingLine && lineNumber <= qEndingLine; } // discover own file name and line number range for filtering stack // traces function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } qFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function deprecate(callback, name, alternative) { return function Q_deprecate() { if ( typeof console !== "undefined" && typeof console.warn === "function" ) { if (alternative) { console.warn( name + " is deprecated, use " + alternative + " instead.", new Error("").stack ); } else { console.warn( name + " is deprecated.", new Error("").stack ); } } return callback.apply(this, arguments); }; } // end of long stack traces var handlers = new WeakMap(); function Q_getHandler(promise) { var handler = handlers.get(promise); if (!handler || !handler.became) { return handler; } handler = follow(handler); handlers.set(promise, handler); return handler; } function follow(handler) { if (!handler.became) { return handler; } else { handler.became = follow(handler.became); return handler.became; } } var theViciousCycleError = new Error("Can't resolve a promise with itself"); var theViciousCycleRejection = Q_reject(theViciousCycleError); var theViciousCycle = Q_getHandler(theViciousCycleRejection); var thenables = new WeakMap(); /** * Coerces a value to a promise. If the value is a promise, pass it through * unaltered. If the value has a `then` method, it is presumed to be a promise * but not one of our own, so it is treated as a “thenable” promise and this * returns a promise that stands for it. Otherwise, this returns a promise that * has already been fulfilled with the value. * @param value promise, object with a then method, or a fulfillment value * @returns {Promise} the same promise as given, or a promise for the given * value */ module.exports = Q; function Q(value) { // If the object is already a Promise, return it directly. This enables // the resolve function to both be used to created references from objects, // but to tolerably coerce non-promises to promises. if (Q_isPromise(value)) { return value; } else if (isThenable(value)) { if (!thenables.has(value)) { thenables.set(value, new Promise(new Thenable(value))); } return thenables.get(value); } else { return new Promise(new Fulfilled(value)); } } /** * Controls whether or not long stack traces will be on * @type {boolean} */ Q.longStackSupport = false; /** * Returns a promise that has been rejected with a reason, which should be an * instance of `Error`. * @param {Error} error reason for the failure. * @returns {Promise} rejection */ Q.reject = Q_reject; function Q_reject(error) { return new Promise(new Rejected(error)); } /** * Constructs a {promise, resolve, reject} object. * * `resolve` is a callback to invoke with a more resolved value for the * promise. To fulfill the promise, invoke `resolve` with any value that is * not a thenable. To reject the promise, invoke `resolve` with a rejected * thenable, or invoke `reject` with the reason directly. To resolve the * promise to another thenable, thus putting it in the same state, invoke * `resolve` with that other thenable. * * @returns {{promise, resolve, reject}} a deferred */ Q.defer = defer; function defer() { var handler = new Pending(); var promise = new Promise(handler); var deferred = new Deferred(promise); if (Q.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { // NOTE: don't try to use `Error.captureStackTrace` or transfer the // accessor around; that causes memory leaks as per GH-111. Just // reify the stack trace as a string ASAP. // // At the same time, cut off the first line; it's always just // "[object Promise]\n", as per the `toString`. promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } } return deferred; } // TODO /** */ Q.when = function Q_when(value, fulfilled, rejected, ms) { return Q(value).then(fulfilled, rejected, ms); }; /** * Turns an array of promises into a promise for an array. If any of the * promises gets rejected, the whole array is rejected immediately. * @param {Array.<Promise>} an array (or promise for an array) of values (or * promises for values) * @returns {Promise.<Array>} a promise for an array of the corresponding values */ // By Mark Miller // http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled Q.all = Q_all; function Q_all(questions) { // XXX deprecated behavior if (Q_isPromise(questions)) { if ( typeof console !== "undefined" && typeof console.warn === "function" ) { console.warn("Q.all no longer directly unwraps a promise. Use Q(array).all()"); } return Q(questions).all(); } var countDown = 0; var deferred = defer(); var answers = Array(questions.length); var estimates = []; var estimate = -Infinity; var setEstimate; Array.prototype.forEach.call(questions, function Q_all_each(promise, index) { var handler; if ( Q_isPromise(promise) && (handler = Q_getHandler(promise)).state === "fulfilled" ) { answers[index] = handler.value; } else { ++countDown; promise = Q(promise); promise.then( function Q_all_eachFulfilled(value) { answers[index] = value; if (--countDown === 0) { deferred.resolve(answers); } }, deferred.reject ); promise.observeEstimate(function Q_all_eachEstimate(newEstimate) { var oldEstimate = estimates[index]; estimates[index] = newEstimate; if (newEstimate > estimate) { estimate = newEstimate; } else if (oldEstimate === estimate && newEstimate <= estimate) { // There is a 1/length chance that we will need to perform // this O(length) walk, so amortized O(1) computeEstimate(); } if (estimates.length === questions.length && estimate !== setEstimate) { deferred.setEstimate(estimate); setEstimate = estimate; } }); } }); function computeEstimate() { estimate = -Infinity; for (var index = 0; index < estimates.length; index++) { if (estimates[index] > estimate) { estimate = estimates[index]; } } } if (countDown === 0) { deferred.resolve(answers); } return deferred.promise; } /** * @see Promise#allSettled */ Q.allSettled = Q_allSettled; function Q_allSettled(questions) { // XXX deprecated behavior if (Q_isPromise(questions)) { if ( typeof console !== "undefined" && typeof console.warn === "function" ) { console.warn("Q.allSettled no longer directly unwraps a promise. Use Q(array).allSettled()"); } return Q(questions).allSettled(); } return Q_all(questions.map(function Q_allSettled_each(promise) { promise = Q(promise); function regardless() { return promise.inspect(); } return promise.then(regardless, regardless); })); } /** * Returns a promise for the given value (or promised value), some * milliseconds after it resolved. Passes rejections immediately. * @param {Any*} promise * @param {Number} milliseconds * @returns a promise for the resolution of the given promise after milliseconds * time has elapsed since the resolution of the given promise. * If the given promise rejects, that is passed immediately. */ Q.delay = function Q_delay(object, timeout) { if (timeout === void 0) { timeout = object; object = void 0; } return Q(object).delay(timeout); }; /** * Causes a promise to be rejected if it does not get fulfilled before * some milliseconds time out. * @param {Any*} promise * @param {Number} milliseconds timeout * @param {String} custom error message (optional) * @returns a promise for the resolution of the given promise if it is * fulfilled before the timeout, otherwise rejected. */ Q.timeout = function Q_timeout(object, ms, message) { return Q(object).timeout(ms, message); }; /** * Spreads the values of a promised array of arguments into the * fulfillment callback. * @param fulfilled callback that receives variadic arguments from the * promised array * @param rejected callback that receives the exception if the promise * is rejected. * @returns a promise for the return value or thrown exception of * either callback. */ Q.spread = Q_spread; function Q_spread(value, fulfilled, rejected) { return Q(value).spread(fulfilled, rejected); } /** * If two promises eventually fulfill to the same value, promises that value, * but otherwise rejects. * @param x {Any*} * @param y {Any*} * @returns {Any*} a promise for x and y if they are the same, but a rejection * otherwise. * */ Q.join = function Q_join(x, y) { return Q.spread([x, y], function Q_joined(x, y) { if (x === y) { // TODO: "===" should be Object.is or equiv return x; } else { throw new Error("Can't join: not the same: " + x + " " + y); } }); }; /** * Returns a promise for the first of an array of promises to become fulfilled. * @param answers {Array} promises to race * @returns {Promise} the first promise to be fulfilled */ Q.race = Q_race; function Q_race(answerPs) { return new Promise(function(deferred) { answerPs.forEach(function(answerP) { Q(answerP).then(deferred.resolve, deferred.reject); }); }); } /** * Calls the promised function in a future turn. * @param object promise or immediate reference for target function * @param ...args array of application arguments */ Q.try = function Q_try(callback) { return Q(callback).dispatch("call", [[]]); }; /** * TODO */ Q.function = Promise_function; function Promise_function(wrapped) { return function promiseFunctionWrapper() { var args = new Array(arguments.length); for (var index = 0; index < arguments.length; index++) { args[index] = arguments[index]; } return Q(wrapped).apply(this, args); }; } /** * The promised function decorator ensures that any promise arguments * are settled and passed as values (`this` is also settled and passed * as a value). It will also ensure that the result of a function is * always a promise. * * @example * var add = Q.promised(function (a, b) { * retur