-
Notifications
You must be signed in to change notification settings - Fork 8
/
es-router.js
358 lines (311 loc) · 12.2 KB
/
es-router.js
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
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _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; }; }();
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function isNotDefined(value) {
return typeof value === 'undefined' || value === null;
}
function clone(object) {
return JSON.parse(JSON.stringify(object));
}
var EsRouter = function () {
function EsRouter(_ref) {
var _this = this;
var useHash = _ref.useHash,
routes = _ref.routes,
notStrictRouting = _ref.notStrictRouting,
home = _ref.home,
base = _ref.base,
_ref$routeOnLoad = _ref.routeOnLoad,
routeOnLoad = _ref$routeOnLoad === undefined ? true : _ref$routeOnLoad;
_classCallCheck(this, EsRouter);
this.events = {
startRouteChange: [],
finishRouteChange: [],
paramChange: []
};
this.useHash = useHash;
this.routes = routes;
this.base = base;
this.notStrictRouting = notStrictRouting;
this.queryParams = this.getParamsFromUrl();
if (base && base[base.length - 1] === '/') {
this.base = this.base.substring(0, this.base.length - 1);
}
//get base if needed
if (!base && !useHash) {
var _base = document.getElementsByTagName('base')[0] && document.getElementsByTagName('base')[0].href || '';
this.base = _base.split(window.location.origin)[1];
}
//create initial object based on passed in params
this.allRoutes = Object.assign(routes, {}).reduce(function (prev, route) {
if (route.name === home) {
_this.home = route;
}
if (route.variablePath) {
throw new Error('route objects cannot be initialized with a key of variablePath');
}
var pathSplit = route.route.split('/').filter(function (item) {
return item;
});
var routeSplitNumbers = pathSplit.length;
var variablePathIndex = pathSplit.reduce(function (prev, route, index) {
//check is route is a variable path
var variable = {
id: route.split(':')[1],
index: index
};
return route.includes(':') ? [].concat(_toConsumableArray(prev), [variable]) : [].concat(_toConsumableArray(prev));
}, []);
route.variablePath = variablePathIndex;
if (!prev[routeSplitNumbers]) {
prev[routeSplitNumbers] = [route];
} else {
prev[routeSplitNumbers] = [].concat(_toConsumableArray(prev[routeSplitNumbers]), [route]);
}
return prev;
}, {});
//set up application based on the hash or history
if (useHash) {
if (window.location.href.indexOf('#') === -1) {
window.location.hash = '/';
}
window.addEventListener('hashchange', function (e) {
if (_this.wasChangedByUser) {
_this.wasChangedByUser = false;
return;
}
_this.eventChangeListener.call(_this, e);
});
} else {
window.onpopstate = this.eventChangeListener.bind(this);
}
//do an initial routing
if (routeOnLoad) {
this.path(this.getPathFromUrl());
}
}
//get path we're currently on
_createClass(EsRouter, [{
key: 'getState',
value: function getState() {
return this.currentPathObject;
}
}, {
key: 'getParamsFromUrl',
value: function getParamsFromUrl() {
var queryParamString = this.useHash ? window.location.hash.split('?')[1] : window.location.search.split('?')[1];
return queryParamString && queryParamString.split('&').reduce(function (prev, queryparam) {
var split = queryparam.split('=');
prev[decodeURIComponent(split[0])] = decodeURIComponent(split[1]) || '';
return prev;
}, {}) || {};
}
}, {
key: 'getPathFromUrl',
value: function getPathFromUrl() {
return !this.useHash ? window.location.pathname.split(this.base)[1] || '/' : window.location.hash.split('?')[0].substring(1);
}
}, {
key: 'eventChangeListener',
value: function eventChangeListener() {
var _this2 = this;
var currentQueryParam = this.getParamsFromUrl();
var currentPath = this.getPathFromUrl();
var allNewParams = this.createParamString(currentQueryParam).join('');
var oldParams = this.createParamString(this.queryParams).join('');
//check if QP have changed
if (allNewParams !== oldParams) {
this.queryParams = this.getParamsFromUrl();
this.events.paramChange.forEach(function (item) {
item(_this2.queryParams);
});
}
//check if path has changed
if (currentPath !== this.currentPath) {
this.currentPath = currentPath;
var newPathObject = this.getPreDefinedRoute(this.currentPath);
var oldPathObject = clone(this.currentPathObject);
this.currentPathObject = newPathObject;
this.startRouteChange(oldPathObject, newPathObject);
this.finishRouteChange(oldPathObject, newPathObject);
}
}
//allow items to subscribe to pre and post route changes
}, {
key: 'subscribe',
value: function subscribe(topic, listener) {
var _this3 = this;
if (!topic || !listener) return {};
// Check validity of topic and listener
if (!this.events.hasOwnProperty.call(this.events, topic) || typeof topic !== 'string' || typeof listener !== 'function') return {};
// Add the listener to queue
// Retrieve the index for deletion
var index = this.events[topic].push(listener) - 1;
// Return instance of the subscription for deletion
return {
remove: function remove() {
delete _this3.events[topic][index];
}
};
}
}, {
key: 'unsubscribe',
value: function unsubscribe(passedF) {
var _this4 = this;
var filterFunction = function filterFunction(item) {
return item !== passedF;
};
Object.keys(this.events).forEach(function (item) {
_this4.events[item] = _this4.events[item].filter(filterFunction);
});
}
//add query params to the object, update path, and fire corresponding events
}, {
key: 'search',
value: function search(item, value) {
var _this5 = this;
if (isNotDefined(item)) {
return this.queryParams;
}
if ((typeof item === 'undefined' ? 'undefined' : _typeof(item)) === 'object') {
this.queryParams = Object.assign(this.queryParams, item);
} else if (isNotDefined(value)) {
if (this.queryParams[item]) {
delete this.queryParams[item];
}
} else {
this.queryParams[item] = value;
}
Object.keys(this.queryParams).forEach(function (key) {
if (isNotDefined(_this5.queryParams[key]) && typeof _this5.queryParams[key] !== 'number') {
delete _this5.queryParams[key];
}
});
var currentQueryParam = this.getParamsFromUrl();
var allNewParams = this.createParamString(currentQueryParam).join('');
var oldParams = this.createParamString(this.queryParams).join('');
if (allNewParams === oldParams) {
return undefined;
}
this.path(this.currentPath, true);
this.events.paramChange.forEach(function (item) {
item(_this5.queryParams);
});
return this.queryParams;
}
//get url object corresponding to path
}, {
key: 'getPreDefinedRoute',
value: function getPreDefinedRoute(route) {
var pathSplit = route.split('/').filter(function (item) {
return item;
});
var allRoutes = clone(this.allRoutes);
//find path that is trying to route to
return allRoutes[pathSplit.length] && allRoutes[pathSplit.length].reduce(function (prev, item) {
//if path has already been found, just return
if (prev) {
return prev;
}
//clone the array for possible mutation
var passedInPath = [].concat(_toConsumableArray(pathSplit));
//get useful path parts
var currentItemPath = item.route.split('/').filter(function (item) {
return item;
});
var variableItems = void 0;
//if path has variables, remove them from check
if (item.variablePath && item.variablePath.length) {
variableItems = item.variablePath.reduce(function (prev, variable, index) {
//mutate both original path and checker path
var result = passedInPath.splice(variable.index - index, 1)[0];
currentItemPath.splice(variable.index - index, 1);
//make the variable object
prev[variable.id] = result;
return prev;
}, {});
}
//if the path is a match, return
if (passedInPath.join('') === currentItemPath.join('')) {
var newItem = Object.assign({}, item);
newItem.variablePath = variableItems;
return newItem;
}
return false;
}, 0);
}
}, {
key: 'createParamString',
value: function createParamString(qp) {
return Object.keys(qp).reduce(function (prev, key) {
var keyString = key.toString();
var valueString = qp[key].toString();
if (isNotDefined(valueString) || Array.isArray(valueString) && !valueString.length) {
return prev;
}
return [].concat(_toConsumableArray(prev), [encodeURIComponent(keyString) + '=' + encodeURIComponent(valueString)]);
}, []);
}
//actual routing function
}, {
key: 'path',
value: function path(route, isQueryParam) {
if (!route) {
return;
}
var newPath = route;
var newPathObject = this.getPreDefinedRoute(newPath);
//if path didn't match and is in strict mode, go home
if (!newPathObject && !this.notStrictRouting) {
newPath = this.home.route;
newPathObject = this.home;
}
//run all pre-move functions
if (!isQueryParam) {
this.startRouteChange(this.currentPathObject, newPathObject);
}
//build new url
var paramArray = this.createParamString(this.queryParams);
var paramArrayString = paramArray.length ? '?' + paramArray.join('&') : '';
var newUrl = '' + (this.base || '') + newPath + paramArrayString;
//set new url
if (this.useHash) {
this.wasChangedByUser = true;
window.location.hash = newUrl;
} else {
window.history.pushState(null, null, newUrl);
}
//finally, set current path state
var oldPath = this.currentPathObject && Object.keys(this.currentPathObject).length && clone(this.currentPathObject);
this.currentPathObject = newPathObject;
this.currentPath = route;
//run all functions afterwards
if (!isQueryParam) {
this.finishRouteChange(oldPath, this.currentPathObject);
}
}
}, {
key: 'startRouteChange',
value: function startRouteChange(oldPath, newPath) {
this.events.startRouteChange.forEach(function (item) {
item(oldPath, newPath);
});
}
}, {
key: 'finishRouteChange',
value: function finishRouteChange(oldPath, newPath) {
this.events.finishRouteChange.forEach(function (item) {
item(oldPath, newPath);
});
this.previousQueryParam = clone(this.queryParams);
}
}]);
return EsRouter;
}();
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = EsRouter;
} else {
window.EsRouter = EsRouter;
}