app-decorators
Version:
Collection of useful ES7 Decorators, writtin in ES6, that can be used for building webapps
1,409 lines (1,171 loc) • 37.5 kB
JavaScript
System.register(['app-decorators/src/libs/element-to-function'], function (_export, _context) {
"use strict";
var _elementToFunc, _slicedToArray, _createClass, Router;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
return {
setters: [function (_appDecoratorsSrcLibsElementToFunction) {
_elementToFunc = _appDecoratorsSrcLibsElementToFunction.default;
}],
execute: function () {
_slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
_createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
_export('Router', Router = function () {
/**
* constructor
* @param {Object} config
* @return {Router}
*/
/**
* _uid
* @type {string}
*/
/**
* routes
* @type {Object}
*/
/**
* _runRoute
* @type {Boolean}
*/
/**
* mode
* @type {Object}
*/
/**
*
* @type {WeakMap}
* @private
*/
function Router() {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Router);
this._refs = {
routes: null,
scope: null,
globalScope: null,
bind: null,
helper: null
};
this.event = {
action: null,
urlchange: null
};
this.mode = {
shadowRoute: null
};
this.promise = {};
this._runRoute = true;
this._lastFragment = null;
this._routes = {
pathname: {},
search: {},
hash: {},
cache: {}
};
this._autoStart = false;
this._uid = null;
this.tmpDomain = 'http://x.x';
var event = config.event,
mode = config.mode,
autostart = config.autostart;
this.event = event;
this.mode = mode;
this._autoStart = typeof autostart === 'boolean' ? autostart : this._autoStart;
this.init(config);
}
/**
* init
* @return {Undefined}
*/
/**
* tmpDomain
* @type {string}
*/
/**
* _autoStart
* @type {boolean}
* @private
*/
/**
* _lastFragment
* @type {String}
*/
/**
* promise
* @type {Object}
*/
/**
* event
* @type {Object}
*/
_createClass(Router, [{
key: 'init',
value: function init() {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this._initRefs(config);
this._bindInternalCoreEvents();
this._initRoutes();
this._createUid();
if (this._autoStart) {
this.start();
}
}
}, {
key: 'reinit',
value: function reinit(options) {
this.init(options);
}
}, {
key: 'initialized',
value: function initialized() {
return this._refs.has(this);
}
}, {
key: 'delete',
value: function _delete() {
this._refs.delete(this);
}
}, {
key: '_initRefs',
value: function _initRefs(_ref2) {
var _ref2$routes = _ref2.routes,
routes = _ref2$routes === undefined ? [] : _ref2$routes,
scope = _ref2.scope,
globalScope = _ref2.globalScope,
helper = _ref2.helper,
bind = _ref2.bind;
if (!scope || !globalScope || !helper) {
throw new Error('\n\t\t\t\tRequired: scope, globalScope and helper.\n\t\t\t\tOptional: use routes when passing routes through constructor.\n\t\t\t\tOptional: use bind when overriding scope of handlers.\n\t\t\t');
}
this._refs = new WeakMap([[this, new Map([['routes', routes], ['scope', scope], ['globalScope', globalScope], ['bind', bind], ['helper', helper]])]]);
}
}, {
key: 'RegExp',
value: function RegExp() {
var _refs$get$get;
return (_refs$get$get = this._refs.get(this).get('helper')).RegExp.apply(_refs$get$get, arguments);
}
}, {
key: 'guid',
value: function guid() {
var _refs$get$get2;
return (_refs$get$get2 = this._refs.get(this).get('helper')).guid.apply(_refs$get$get2, arguments);
}
}, {
key: 'pushState',
value: function pushState() {
var _history;
return (_history = history).pushState.apply(_history, arguments);
}
}, {
key: 'replaceState',
value: function replaceState() {
var _history2;
return (_history2 = history).replaceState.apply(_history2, arguments);
}
}, {
key: 'forward',
value: function forward() {
return history.forward();
}
}, {
key: 'back',
value: function back() {
return history.back();
}
}, {
key: '_createUid',
value: function _createUid() {
this._uid = this.guid();
}
}, {
key: 'on',
value: function on() {
var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var handler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
if (!type) {
throw 'Please pass at least type e.g urlchange, Foo, Bar, ...';
}
var classof = Object.prototype.toString.call(handler).slice(8, -1);
if (handler !== undefined && classof !== 'Function') {
throw 'The handler must be a Function or Undefined';
}
var _type$split = type.split(' '),
_type$split2 = _slicedToArray(_type$split, 2),
name = _type$split2[0],
route = _type$split2[1];
var promise = this.addRouteListener(name, route, handler);
if (this._autoStart) {
this.start();
}
return promise;
}
}, {
key: 'off',
value: function off(event) {
if (!event) {
throw 'No event passed';
}
this._removeRoute(event);
}
}, {
key: 'trigger',
value: function trigger() {
var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!this._refs.has(this)) {
return null;
}
this.scope.trigger(event, params);
}
}, {
key: 'destroy',
value: function destroy() {
if (!this._refs.has(this)) {
return null;
}
this._removeInternalCoreEvents();
this._removeRegisteredEvents();
this._removeRefs();
}
}, {
key: 'addRouteListener',
value: function addRouteListener(name, route, handler) {
var _this = this;
// bind bindObject if exsits
if (handler && this.bind) {
var _context2;
handler = (_context2 = this.bind, handler).bind(_context2);
}
/**
* _addRoute is required for:
* 1. if route matched then we can take name for triggering event
* 2. if router should destroy, see .destroy()
*/
if (route && name && handler) {
this._addRoute(route, name, handler);
}
// create promise if handler not exists
var promise = null;
if (name && !handler) {
promise = this._addPromise(name);
}
this.scope.on(name, function (event) {
var _createURL = _this.createURL(location.href),
search = _createURL.search,
hash = _createURL.hash;
var searchParams = _this.queryString.parse(search);
var hashParams = _this.queryString.parse(hash);
var args = Object.assign({}, event.detail, {
search: searchParams, hash: hashParams, event: event
});
if (handler) {
handler(args);
}
// resolve promise
_this._promiseHandler(name, args);
});
return promise;
}
}, {
key: '_addRoute',
value: function _addRoute(route, name, handler) {
if (!this._isValidRoute(route)) {
throw '\n\t\t\t\tPassed "' + route + '" is not valid. Please\n\t\t\t\tpass only pathname, search or hash.\n\t\t\t';
}
var urlpart = this._getURLType(route);
if (this._routes[urlpart][route]) {
throw 'route: "' + route + '" already exists!';
}
if (this._existsEvent(name)) {
throw 'Eventname: "' + name + '" already exists!';
}
var type = this._isDynamicURL(route) ? 'dynamic' : 'static';
var strict = urlpart === 'pathname';
var regex = this._convertRouteToXRegexExp(route, strict);
var routeObjectArgs = { name: name, route: route, regex: regex, type: type, urlpart: urlpart, handler: handler };
this._routes[urlpart][route] = this._createRouteObject(routeObjectArgs);
}
}, {
key: '_existsEvent',
value: function _existsEvent(event) {
var allRoutes = this.getRoutes();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(allRoutes)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var route = _step.value;
var name = allRoutes[route].name;
if (event === name) {
return true;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return false;
}
}, {
key: '_removeRoute',
value: function _removeRoute(event) {
// remove route event from listener
this.scope.off(event);
// remove route event from _routes
var allRoutes = this.getRoutes();
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = Object.keys(allRoutes)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var routeKey = _step2.value;
var _allRoutes$routeKey = allRoutes[routeKey],
name = _allRoutes$routeKey.name,
urlpart = _allRoutes$routeKey.urlpart,
route = _allRoutes$routeKey.route;
if (name === event) {
delete this._routes[urlpart][route];
return;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
}, {
key: '_createRouteObject',
value: function _createRouteObject(_ref3) {
var name = _ref3.name,
route = _ref3.route,
regex = _ref3.regex,
type = _ref3.type,
urlpart = _ref3.urlpart,
handler = _ref3.handler;
return {
type: type,
name: name,
route: route,
handler: handler,
urlpart: urlpart,
regex: regex,
params: null,
fragment: null,
cache: false
};
}
}, {
key: '_addPromise',
value: function _addPromise(name) {
var _this2 = this;
if (!this.promise[name]) {
this.promise[name] = [];
}
var promise = new Promise(function (resolve) {
_this2.promise[name].push(resolve);
});
return promise;
}
}, {
key: 'getRoutes',
value: function getRoutes() {
var urlpart = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var routes = null;
if (urlpart) {
routes = this._routes[urlpart];
} else {
routes = Object.assign({}, this._routes.pathname, this._routes.search, this._routes.hash);
}
return routes;
}
}, {
key: 'createURL',
value: function createURL(href) {
var url = new URL(href);
url.fragment = url.href.replace(url.origin, '');
return url;
}
}, {
key: '_bindInternalCoreEvents',
value: function _bindInternalCoreEvents() {
var _this3 = this;
// When an event.action triggered e.g. a "click a" <a href="..>
// This also trigger internal in _onAction an urlchange event
this.scope.on(this.event.action, this._onAction.bind(this));
// When back or forward button is in use
// This also trigger internal in _onAction an urlchange event
this.globalScope.on(this.event.popstate, function (event) {
//if back/forward button in use, we have to check in which
//route scope we are
if (!_this3._inPopstateScope(event)) {
return;
}
_this3._onAction(event);
});
this.scope.on(this.event.urlchange, this._onUrlchange.bind(this));
}
}, {
key: '_inPopstateScope',
value: function _inPopstateScope(event) {
var route_uid = event.state && event.state.route_uid;
var inPopstateScope = this._uid === route_uid;
return route_uid && inPopstateScope;
}
}, {
key: '_removeInternalCoreEvents',
value: function _removeInternalCoreEvents() {
this.scope.off(this.event.action);
this.globalScope.off(this.event.popstate);
this.scope.off(this.event.urlchange);
}
}, {
key: '_removeRegisteredEvents',
value: function _removeRegisteredEvents() {
var allRoutes = this.getRoutes();
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = Object.keys(allRoutes)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var route = _step3.value;
var name = allRoutes[route].name;
this.off(name);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
}, {
key: '_removeRefs',
value: function _removeRefs() {
this.delete();
}
}, {
key: '_initRoutes',
value: function _initRoutes() {
if (!this.routes.length) {
return;
}
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = this.routes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var routeExpression = _step4.value;
var _routeExpression = _slicedToArray(routeExpression, 2),
route = _routeExpression[0],
handler = _routeExpression[1];
if (this.bind) {
var _context3;
handler = (_context3 = this.bind, handler).bind(_context3);
}
this.on(route, handler);
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
}, {
key: '_onAction',
value: function _onAction(event) {
this._preventDefault(event);
if (!this._runRoute) {
return;
}
if (this.mode.shadowRoute) {
this._stopPropagation(event);
}
this._applyActionEvent(event);
}
}, {
key: '_applyActionEvent',
value: function _applyActionEvent(event) {
var href = this._getCurrentHref(event);
var urlObject = this.createURL(href);
var fragment = urlObject.fragment;
var _diffFragments2 = this._diffFragments(fragment, this._lastFragment),
changed = _diffFragments2.changed,
changepart = _diffFragments2.changepart;
if (changed) {
Object.assign(urlObject, {
changepart: changepart,
target: event.target
});
if (this._isDefinedEventAction(event.type)) {
var url = encodeURI(fragment);
var route_uid = this._uid;
this.pushState({ route_uid: route_uid }, null, url);
}
this.trigger(this.event.urlchange, urlObject);
}
this._setURLFragment(fragment);
}
}, {
key: '_isDefinedEventAction',
value: function _isDefinedEventAction(event_type) {
var isDefinedEventAction = event_type === this._getDefinedEventAction();
return isDefinedEventAction;
}
}, {
key: '_getCurrentHref',
value: function _getCurrentHref(event) {
// extract defined_event_action e.g. "click" from "click a"
var defined_event_action = this._getDefinedEventAction();
// check if event is triggered by "click" or triggered by back/forward button and return href
var href = event.type === defined_event_action ? event.target.href : location.href;
return href;
}
}, {
key: '_getDefinedEventAction',
value: function _getDefinedEventAction() {
var _event$action$split = this.event.action.split(' '),
_event$action$split2 = _slicedToArray(_event$action$split, 1),
defined_event_action = _event$action$split2[0];
return defined_event_action;
}
}, {
key: '_diffFragments',
value: function _diffFragments(currentFragment, lastFragment) {
var diff = {
changed: false,
changepart: []
};
diff.changed = currentFragment !== lastFragment || lastFragment === null;
var currentFragmentParts = this._convertFragmentToParts(currentFragment);
var lastFragmentParts = this._convertFragmentToParts(lastFragment);
var diffParts = this._diffFragmentParts(currentFragmentParts, lastFragmentParts);
diff.changepart = diffParts;
return diff;
}
}, {
key: '_convertFragmentToParts',
value: function _convertFragmentToParts() {
var fragment = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var urlObject = this.createURL('' + this.tmpDomain + fragment);
return {
pathname: urlObject.pathname,
search: urlObject.search,
hash: urlObject.hash
};
}
}, {
key: '_diffFragmentParts',
value: function _diffFragmentParts(fragment1, fragment2) {
var parts = [];
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = Object.keys(fragment1)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var part = _step5.value;
if (fragment1[part] === fragment2[part]) {
continue;
}
parts.push(part);
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
return parts;
}
}, {
key: '_setURLFragment',
value: function _setURLFragment(fragment) {
this._lastFragment = fragment;
}
}, {
key: '_onUrlchange',
value: function _onUrlchange(event) {
if (!(event.detail instanceof URL)) {
return null;
}
var _event$detail = event.detail,
fragment = _event$detail.fragment,
changepart = _event$detail.changepart,
target = _event$detail.target;
var matchedUrlObjects = this._matchURL(fragment, changepart, true);
if (!matchedUrlObjects.length) {
return null;
}
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = matchedUrlObjects[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var matchedURL = _step6.value;
var name = matchedURL.name;
matchedURL.URL = event.detail;
this.trigger(name, Object.assign({}, matchedURL, { target: target }));
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
}
}, {
key: '_matchURL',
value: function _matchURL(fragment) {
var changepart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var cache = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var matchedUrlObjects = [];
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = changepart[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var part = _step7.value;
var matchedURLObject = null;
var url = '' + this.tmpDomain + fragment;
var fragmentPart = this.createURL(url)[part];
// load from cache
matchedURLObject = this._getRouteCache(fragmentPart);
if (matchedURLObject && cache) {
matchedUrlObjects.push(matchedURLObject);
continue;
}
// match dynamic url
matchedURLObject = this._match(fragmentPart, part);
if (matchedURLObject) {
this._addRouteCache(fragment, matchedURLObject);
matchedUrlObjects.push(matchedURLObject);
}
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
return matchedUrlObjects;
}
}, {
key: '_match',
value: function _match(fragment, part) {
var dynamicRoutes = Object.keys(this._routes[part] || {});
var _iteratorNormalCompletion8 = true;
var _didIteratorError8 = false;
var _iteratorError8 = undefined;
try {
for (var _iterator8 = dynamicRoutes[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
var route = _step8.value;
// parepare datas for matching
var routeObject = this._routes[part][route];
// match regex
var compiledRegex = this.RegExp(routeObject.regex);
var matchedRegex = compiledRegex.exec(fragment);
// continue if not matched
if (matchedRegex === null) {
continue;
}
var _params = matchedRegex.groups();
var params = this._normalizeMatchedXRegex(_params);
// build matchedURLObject
var matchedURLObject = Object.assign({}, routeObject, { params: params, fragment: fragment });
return matchedURLObject;
}
} catch (err) {
_didIteratorError8 = true;
_iteratorError8 = err;
} finally {
try {
if (!_iteratorNormalCompletion8 && _iterator8.return) {
_iterator8.return();
}
} finally {
if (_didIteratorError8) {
throw _iteratorError8;
}
}
}
return null;
}
}, {
key: '_normalizeMatchedXRegex',
value: function _normalizeMatchedXRegex() {
var matchedRegex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var params = {};
for (var attribute in matchedRegex) {
var value = matchedRegex[attribute];
// convert to real number if attribute is numeric
if (this._isNumeric(value)) {
value = parseFloat(value);
}
params[attribute] = value;
}
return params;
}
}, {
key: '_addRouteCache',
value: function _addRouteCache(fragment, cacheObject) {
cacheObject = this._immutable(cacheObject);
cacheObject.cache = true;
this._routes.cache[fragment] = cacheObject;
}
}, {
key: '_immutable',
value: function _immutable(object) {
return JSON.parse(JSON.stringify(object));
}
}, {
key: '_getRouteCache',
value: function _getRouteCache(fragment) {
return this._routes.cache[fragment] || null;
}
}, {
key: '_promiseHandler',
value: function _promiseHandler(name) {
if (!this.promise[name]) {
return;
}
var resolve = void 0;
// promise can resolved only once therefore shift()
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
while ((resolve = this.promise[name].shift()) !== undefined) {
resolve.apply(undefined, args);
}
}
}, {
key: '_convertRouteToXRegexExp',
value: function _convertRouteToXRegexExp() {
var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// remove whitespaces
var variableURLRegex = this.RegExp('{{(?<variableURL>[a-z]+)}}', 'g');
url = url.replace(/[\/|+*?.()]/g, '\\$&');
url = variableURLRegex.replace(url, '(?<${variableURL}>[\\d\\w?()|{}_.,-]+)');
if (strict) {
url = '^' + url + '$';
}
return url;
}
}, {
key: '_isDynamicURL',
value: function _isDynamicURL() {
var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var isDynamicURL = /{{[a-z]+}}/.test(url);
return isDynamicURL;
}
}, {
key: '_isValidRoute',
value: function _isValidRoute(route) {
var result = !!this._getURLType(route);
return result;
}
}, {
key: '_getURLType',
value: function _getURLType() {
var route = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
if (!/^(\/|\?|#)/.test(route)) {
throw '\n\t\t\t\tSomething gong wrong. Cant determine ' + route + '. \n\t\t\t\tPlease prefix your route with "/" for pathname,\n\t\t\t\t"?" for search or "#" for hash route.\n\t\t\t';
}
var _createURL2 = this.createURL('' + this.tmpDomain + route),
pathname = _createURL2.pathname,
search = _createURL2.search,
hash = _createURL2.hash;
var validRoute = null;
// only "/"
if (!pathname[1] && !search && !hash) {
validRoute = 'pathname';
}
// only pathname e.g. /a/b.html
else if (pathname[1] && !search && !hash) {
validRoute = 'pathname';
}
// only search e.g. ?a=1&b=2
else if (!pathname[1] && search && !hash) {
validRoute = 'search';
}
// only hash e.g. #myhash
else if (!pathname[1] && !search && hash) {
validRoute = 'hash';
}
// not valid route e.g. /a/b.html?a=1&b2
else {
validRoute = null;
}
return validRoute;
}
}, {
key: '_preventDefault',
value: function _preventDefault(event) {
if (event instanceof Event) {
event.preventDefault();
}
}
}, {
key: '_stopPropagation',
value: function _stopPropagation(event) {
if (event instanceof Event) {
event.stopPropagation();
}
}
}, {
key: '_isNumeric',
value: function _isNumeric(value) {
return (/^[+-]?\d+(\.\d+)?$/.test(value)
);
}
}, {
key: '_constructURL',
value: function _constructURL() {
var route = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var params = arguments[1];
if (!route) {
throw 'Please pass at least route';
}
var routeObject = this.which(route);
if (routeObject === null) {
throw 'route: ' + route + ' does not exists!';
}
var url = null;
if (routeObject && routeObject.type === 'static') {
url = this._constructStaticURL(routeObject.route);
}
if (routeObject && routeObject.type === 'dynamic') {
url = this._constructDynamicURL(routeObject.route, params);
}
return url;
}
}, {
key: '_constructStaticURL',
value: function _constructStaticURL() {
var route = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var staticURL = route;
return staticURL;
}
}, {
key: '_constructDynamicURL',
value: function _constructDynamicURL() {
var route = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var curlyBracketsRegex = /\{\{|\}\}/;
var url = route;
var _iteratorNormalCompletion9 = true;
var _didIteratorError9 = false;
var _iteratorError9 = undefined;
try {
var _loop = function _loop() {
var param = _step9.value;
url = url.replace('{{' + param + '}}', function () {
return params[param];
});
};
for (var _iterator9 = Object.keys(params)[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
_loop();
}
} catch (err) {
_didIteratorError9 = true;
_iteratorError9 = err;
} finally {
try {
if (!_iteratorNormalCompletion9 && _iterator9.return) {
_iterator9.return();
}
} finally {
if (_didIteratorError9) {
throw _iteratorError9;
}
}
}
if (curlyBracketsRegex.test(url)) {
throw '\n\t\t\t\tSometing gone wrong. Cant resolve passed params: "' + JSON.stringify(params) + '".\n\t\t\t\tGenerated url: "' + url + '" by method _constructDynamicURL;\n\t\t\t';
}
return url;
}
}, {
key: 'match',
value: function match(fragment) {
var cache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var matchedObjects = this.whoami(fragment, cache);
if (!matchedObjects.length) {
return undefined;
}
var _iteratorNormalCompletion10 = true;
var _didIteratorError10 = false;
var _iteratorError10 = undefined;
try {
for (var _iterator10 = matchedObjects[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
var matchedObject = _step10.value;
var name = matchedObject.name,
params = matchedObject.params;
this.trigger(name, params);
}
} catch (err) {
_didIteratorError10 = true;
_iteratorError10 = err;
} finally {
try {
if (!_iteratorNormalCompletion10 && _iterator10.return) {
_iterator10.return();
}
} finally {
if (_didIteratorError10) {
throw _iteratorError10;
}
}
}
}
}, {
key: 'whoami',
value: function whoami(fragment) {
var cache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var changepart = ['pathname', 'search', 'hash'];
var matchedUrlObjects = this._matchURL(fragment, changepart, cache);
return matchedUrlObjects;
}
}, {
key: 'which',
value: function which(name) {
var allRoutes = this.getRoutes();
var _iteratorNormalCompletion11 = true;
var _didIteratorError11 = false;
var _iteratorError11 = undefined;
try {
for (var _iterator11 = Object.keys(allRoutes)[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
var route = _step11.value;
var routeObject = allRoutes[route];
if (routeObject.name === name) {
return routeObject;
}
}
} catch (err) {
_didIteratorError11 = true;
_iteratorError11 = err;
} finally {
try {
if (!_iteratorNormalCompletion11 && _iterator11.return) {
_iterator11.return();
}
} finally {
if (_didIteratorError11) {
throw _iteratorError11;
}
}
}
return null;
}
}, {
key: 'constructURL',
value: function constructURL(route) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var url = this._constructURL(route, params);
return url;
}
}, {
key: 'go',
value: function go(route) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var url = this._constructURL(route, params);
this.pushState(null, null, encodeURI(url));
}
}, {
key: 'redirect',
value: function redirect(url) {
var soft = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var encodedURI = encodeURI(url);
if (soft) {
this.pushState(null, null, encodeURI(encodedURI));
} else {
location.href = encodedURI;
}
}
}, {
key: 'start',
value: function start() {
this._runRoute = true;
var href = location.href;
var _createURL3 = this.createURL(href),
fragment = _createURL3.fragment;
var matchedUrlObjects = this.whoami(fragment);
if (!matchedUrlObjects.length) {
return undefined;
}
var _iteratorNormalCompletion12 = true;
var _didIteratorError12 = false;
var _iteratorError12 = undefined;
try {
for (var _iterator12 = matchedUrlObjects[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
var matchedURL = _step12.value;
var name = matchedURL.name;
this.trigger(name, matchedURL);
}
} catch (err) {
_didIteratorError12 = true;
_iteratorError12 = err;
} finally {
try {
if (!_iteratorNormalCompletion12 && _iterator12.return) {
_iterator12.return();
}
} finally {
if (_didIteratorError12) {
throw _iteratorError12;
}
}
}
}
}, {
key: 'stop',
value: function stop() {
this._runRoute = false;
}
}, {
key: 'routes',
get: function get() {
return this._refs.get(this).get('routes');
}
}, {
key: 'globalScope',
get: function get() {
var _ref = this._refs.get(this);
return _ref && _ref.get('globalScope');
}
}, {
key: 'scope',
get: function get() {
var _ref = this._refs.get(this);
return _ref && _ref.get('scope');
}
}, {
key: 'bind',
get: function get() {
return this._refs.get(this).get('bind');
}
}, {
key: 'queryString',
get: function get() {
return this._refs.get(this).get('helper').queryString;
}
}]);
return Router;
}());
_export('Router', Router);
}
};
});
//# sourceMappingURL=router.js.map