-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
486 lines (453 loc) · 20.6 KB
/
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
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
import {
Loader
} from './loader.js';
import {
RoutingRule
} from '../routing-rule.js';
import {
Render
} from './render.js';
import { Swissknife } from '../util/swissknife.js';
window.SwimAppController = [];
window.SwimAppControllersAndArgsMapping = {};
window.SwimAppCurrentController = null;
window.SwimAppStylesheet = window.SwimAppStylesheet || [];
window.SwimAppPreviousState = [];
export const Router = {
pauseRouting: false,
interrupt: null,
init: (context) => {
window.addEventListener('popstate', async () => {
if (Router.pauseRouting) {
return;
}
const newPath = location.pathname + location.search;
const exitResult = await Router.exit(window.SwimAppPreviousState, newPath, RoutingRule, context);
if (exitResult) {
Router.routing(window.SwimAppPreviousState, newPath, RoutingRule, context);
window.SwimAppPreviousState = newPath; // eslint-disable-line
} else {
history.go(1);
}
});
(function (original) {
history.originalPushState = history.pushState;
history.pushState = async function (data, title, newPath) {
if (Router.pauseRouting) {
return;
}
const exitResult = await Router.exit(location.pathname + location.search, newPath, RoutingRule, context);
if (exitResult) {
window.SwimAppPreviousState = newPath;
Router.routing(location.pathname + location.search, newPath, RoutingRule, context);
if (Router.interrupt) {
Router.interrupt();
}
return original.apply(this, arguments);
}
};
})(history.pushState);
(function (original) {
history.replaceState = async function (data, title, newPath) {
if (Router.pauseRouting) {
return;
}
const exitResult = await Router.exit(location.pathname + location.search, newPath, RoutingRule, context);
if (exitResult) {
window.SwimAppPreviousState = newPath;
Router.routing(location.pathname + location.search, newPath, RoutingRule, context);
return original.apply(this, arguments);
}
};
})(history.replaceState);
Router.routing('', location.pathname + location.search, RoutingRule, context);
window.SwimAppPreviousState = location.pathname + location.search;
// overwrite link tag original behavior
document.querySelectorAll('a').forEach((el) => {
el.addEventListener('click', overWriteLinkBehavior);
});
document.addEventListener('DOMNodeInserted', (e) => {
if (e.target && e.target.classList && e.target.classList.contains('skip-swim-router')) {
return;
}
if (e.target.tagName === 'A') {
const htmlElement = e.target;
htmlElement.addEventListener('click', overWriteLinkBehavior);
} else if (e.target.querySelectorAll && e.target.querySelectorAll('a').length > 0) {
e.target.querySelectorAll('a').forEach((el) => {
el.addEventListener('click', overWriteLinkBehavior);
});
}
});
function overWriteLinkBehavior (e) {
const isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
const isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);
const isWin = /(win32)/i.test(navigator.platform);
if (e.currentTarget.target === '_blank' ||
((isMacLike || isIOS) && e.metaKey === true) ||
((isWin) && e.ctrlKey === true) ||
e.currentTarget.hasAttribute('not-in-app')
) {
return;
}
if (e.currentTarget.href.indexOf(location.origin) !== -1) {
e.preventDefault();
e.stopPropagation();
if (e.currentTarget && e.currentTarget.href) {
if (e.currentTarget.href.indexOf(location.origin) === -1) {
return;
}
}
const newPath = e.currentTarget.href.replace(location.origin, '');
let originPath = location.pathname;
if (location.search) {
originPath += location.search;
}
if (`${originPath}#` === newPath) {
return;
}
history.pushState({}, '', newPath);
}
}
},
exit: async (previousPath, path, routers, context) => {
const currentRoutingPathArray = Router.getRoutingPathArray(path, routers);
const previousRoutingPathArray = Router.getRoutingPathArray(previousPath, routers);
// should be exit controller
let differenceRoutinPathFromPrevious = previousRoutingPathArray.filter((routingPath) => {
for (let i = 0; i < currentRoutingPathArray.length; i++) {
if (routingPath.fullPath === currentRoutingPathArray[i].fullPath) {
return false;
}
}
return true;
});
differenceRoutinPathFromPrevious = differenceRoutinPathFromPrevious.reverse();
for (let i = 0; i < differenceRoutinPathFromPrevious.length; i++) {
const controllerInstance = Router.findControllerInstance(differenceRoutinPathFromPrevious[i].matchRoutingRule.controller);
if (!controllerInstance) {
continue;
}
const result = await controllerInstance.exit();
if (!result) {
return false;
}
clearContextArgs(context.args, differenceRoutinPathFromPrevious[i].matchRoutingRule.controller.id);
}
return true;
},
routing: async (previousPath, path, routers, context) => {
if (!context.args) {
context.args = {};
}
const currentRoutingPathArray = Router.getRoutingPathArray(path, routers);
const previousRoutingPathArray = Router.getRoutingPathArray(previousPath, routers);
// should be enter controller
let currentIndex = 0;
let previousIndex = 0;
const differenceRoutinPathFromCurrent = [];
if (previousRoutingPathArray.length > 0) {
while (
currentIndex < currentRoutingPathArray.length &&
previousIndex < previousRoutingPathArray.length
) {
if (previousRoutingPathArray[previousIndex].fullPath !== currentRoutingPathArray[currentIndex].fullPath) { // 發現不一樣就把所有後面的 path push 到 diff 裡頭
break;
}
currentIndex = currentIndex + 1;
previousIndex = previousIndex + 1;
}
}
for (let i = currentIndex; i < currentRoutingPathArray.length; i++) {
differenceRoutinPathFromCurrent.push(currentRoutingPathArray[i]);
}
// edge case: child routing rule to parent routing rule
if (
differenceRoutinPathFromCurrent.length === 0 &&
previousPath !== path
) {
differenceRoutinPathFromCurrent.push(currentRoutingPathArray[currentRoutingPathArray.length - 1]);
}
for (let i = 0; i < differenceRoutinPathFromCurrent.length; i++) {
const routingPath = differenceRoutinPathFromCurrent[i];
const pathFragment = routingPath.pathFragment;
const regexp = routingPath.regexp;
const routingRule = routingPath.matchRoutingRule;
// get parent controller
const currentRoutingPathIndex = currentRoutingPathArray.indexOf(routingPath);
const parentController = currentRoutingPathIndex === 0 ? null : currentRoutingPathArray[currentRoutingPathIndex - 1].matchRoutingRule.controller;
const parentControllerInstance = Router.findControllerInstance(parentController);
if (parentControllerInstance && parentControllerInstance.elHTML) {
parentControllerInstance.elHTML.querySelector('.child-router').innerHTML = '<div class="spinner"><div></div><div></div><div></div><div></div></div>';
parentControllerInstance.elHTML.querySelector('.child-router').addClass('loading');
const elChildRouter = parentControllerInstance.elHTML.querySelector('.child-router');
if (elChildRouter) {
elChildRouter.getAttributeNames().forEach((attrName) => {
if (attrName.indexOf('on-') === 0) {
const funcName = elChildRouter.getAttribute(attrName).replace(/controller\./gi, '');
if (parentControllerInstance[funcName]) {
parentControllerInstance.elHTML.addEventListener(attrName.replace(/^on-/gi, ''), (e) => {
parentControllerInstance[funcName](e);
});
}
}
});
}
}
// prepare context args from url
const variableFromURL = Router.extractVariableFromUrl(routingRule.path, pathFragment, regexp);
setupContextArgs(context.args, variableFromURL, routingRule.controller.id, true);
// prepare context args from routing rule
let somethingWrongInPrepareData = false;
if (routingRule.prepareData) {
const result = await Router.prepareData(routingRule.prepareData, context.args);
somethingWrongInPrepareData = result.somethingWrongInPrepareData;
setupContextArgs(context.args, result.data, routingRule.controller.id);
}
if (somethingWrongInPrepareData) {
console.warn(`something wrong in ${routingRule.controller.id} prepare data$`);
}
// load dependency
// as server side render appealed to performance, so skip to load dependencies in render server
// if u need to use third-paty libary in render function please use npm install and add varaible to fake-browser.js
if (!context.isServerSideRender) {
const loader = new Loader();
if (routingRule.dependency) {
await loader.load(routingRule.dependency);
}
}
// execute controller
let htmlPath = null;
if (routingRule.html) {
htmlPath = routingRule.html;
}
await Router.executeController(routingRule.controller, context, htmlPath, parentControllerInstance);
}
document.querySelectorAll('.child-router').forEach((el) => {
el.style.visibility = '';
});
document.querySelectorAll('.loading').forEach((el) => {
el.removeClass('loading');
});
if (!context.isUpdateDOMFirstRunRouting) {
let cursorIndex = 0;
let firstHTMLExistsController = window.SwimAppController[cursorIndex];
while (!firstHTMLExistsController.elHTML) {
cursorIndex += 1;
firstHTMLExistsController = window.SwimAppController[cursorIndex];
}
const elContainer = firstHTMLExistsController.elShadowHTML.parentElement;
let child = elContainer.lastElementChild;
while (child) {
elContainer.removeChild(child);
child = elContainer.lastElementChild;
}
elContainer.appendChild(firstHTMLExistsController.elHTML);
}
context.isUpdateDOMFirstRunRouting = true; // eslint-disable-line
},
findMatchRoute: (currentPath, routers) => {
for (let i = 0; i < routers.length; i++) {
const path = routers[i].path;
const isEnd = routers[i].children === undefined;
const regexp = Router.buildRegExp(path, isEnd);
if (regexp.test(currentPath)) {
return routers[i];
}
}
},
findControllerInstance: (type) => {
if (!type) {
return null;
}
return window.SwimAppController.filter((instance) => {
return instance instanceof type;
})[0];
},
// server side: constructor -> render
// client side first time: constructor -> enter -> render -> postRender -> exit
// client side seconds time: enter -> render -> postRender -> exit
executeController: async (Controller, context, htmlPath, parentController, skipControllerLiveTimeCycle) => {
// 如果已經有 instance 就不要在執行 initalize
const instances = window.SwimAppController.filter((instance) => {
return instance instanceof Controller;
});
let controllerInstance = null;
let elHTML = null;
if (instances.length === 0) {
if (htmlPath) {
const loader = new Loader();
let html = await loader.loadHTML(htmlPath);
html = Render.appendStylesheetToHeadAndRemoveLoaded(html);
elHTML = html.toDom();
}
controllerInstance = new Controller(elHTML, parentController, context.args, context);
window.SwimAppController.push(controllerInstance);
} else {
controllerInstance = instances[0];
}
window.AppCurrentController = controllerInstance; // eslint-disable-line
if (!skipControllerLiveTimeCycle) {
if (!context.isServerSideRender) { // client side only
// client side every time enter router
await controllerInstance.enter(context.args);
if (controllerInstance.render) {
await controllerInstance.render();
}
if (controllerInstance.postRender) {
await controllerInstance.postRender();
}
} else if (controllerInstance.render) {
await controllerInstance.render(true);
}
}
return controllerInstance;
},
prepareData: (prepareFuncs, args) => {
return new Promise(async (resolve) => { // eslint-disable-line
let somethingWrongInPrepareData = false;
const data = {};
const tempArgs = {
...args
};
if (prepareFuncs && prepareFuncs.length > 0) {
for (let i = 0; i < prepareFuncs.length; i++) {
const prepareData = await prepareFuncs[i].func(tempArgs);
if (prepareData === null || prepareData === undefined) {
somethingWrongInPrepareData = true;
}
const key = prepareFuncs[i].key;
tempArgs[key] = prepareData;
data[key] = prepareData;
}
}
resolve({
somethingWrongInPrepareData,
data
});
});
},
buildRegExp: (path, isEnd) => {
const arrayOfPath = path.split('?')[0].split('/');
const arrayRegString = [];
const arrayUrlParams = [];
for (let j = 0; j < arrayOfPath.length; j++) {
if (arrayOfPath[j].substring(0, 1) === '{') {
arrayUrlParams.push(arrayOfPath[j].replace(/{/gi, '').replace(/}/gi, ''));
arrayRegString.push('([0-9a-zA-Z_\\-\\}\\{]+)');
} else {
arrayRegString.push(arrayOfPath[j]);
}
}
if (isEnd) {
return new RegExp('^' + arrayRegString.join('\\/') + '(\\?.*)?$');
} else {
return new RegExp('^' + arrayRegString.join('\\/'));
}
},
extractVariableFromUrl: (routingPath, currentPath, regexp) => {
const arrayRoutingPath = routingPath.split('?');
routingPath = arrayRoutingPath[0];
const keys = routingPath.match(regexp);
const values = Array.isArray(currentPath) ? currentPath.join('/').match(regexp) : currentPath.match(regexp);
const args = {};
if (keys !== null && keys !== undefined && keys.length > 1 && keys.length === values.length) {
for (let j = 1; j < keys.length; j++) {
if (keys[j] === undefined) {
continue;
}
const key = keys[j].replace(/{/gi, '').replace(/}/gi, '');
const value = values[j];
args[key] = value;
}
}
// 怎麼記得 location.search -> currentPath 現在好像又改回 currentPath;
// currentPath 會有 queryString 不知道為什麼這裡要這樣處理
// if (location.search !== '?' && currentPath.indexOf('?') === -1) {
// currentPath += location.search;
// }
if (arrayRoutingPath.length === 2 && currentPath.indexOf('?') !== -1) {
const arrayQueryStringFromRouting = arrayRoutingPath[1].split('&');
const arrayQueryStringFromCurrentPath = currentPath.split('?')[1].split('&');
for (let i = 0; i < arrayQueryStringFromRouting.length; i++) {
for (let j = 0; j < arrayQueryStringFromCurrentPath.length; j++) {
if (arrayQueryStringFromCurrentPath[j].indexOf(arrayQueryStringFromRouting[i] + '=') !== -1) {
const queryKey = arrayQueryStringFromRouting[i];
const queryValue = arrayQueryStringFromCurrentPath[j].split('=')[1];
args[queryKey] = queryValue;
}
}
}
}
return args;
},
getRoutingPathArray: (path, routingRules) => {
const results = [];
let currentPath = path;
let currentRoutingRules = routingRules;
let isEnd = !(path.length > 0);
let fullPath = '';
while (!isEnd) {
const matchRoutingRule = Router.findMatchRoute(currentPath, currentRoutingRules);
let regexp = Router.buildRegExp(matchRoutingRule.path, isEnd);
isEnd = matchRoutingRule.children === undefined || currentPath.split('?')[0].replace(regexp, '').length === 0;
// re-generate regexp
if (isEnd) {
regexp = Router.buildRegExp(matchRoutingRule.path, isEnd);
}
fullPath += currentPath.match(regexp)[0];
results.push({
fullPath,
pathFragment: currentPath.match(regexp)[0],
matchRoutingRule,
regexp
});
currentRoutingRules = matchRoutingRule.children;
currentPath = currentPath.replace(regexp, '');
}
return results;
}
};
function setupContextArgs (argsReference, args, controllerId, isVariableFromUri) {
if (!window.SwimAppControllersAndArgsMapping[controllerId]) {
window.SwimAppControllersAndArgsMapping[controllerId] = [];
}
for (const key in args) {
if (typeof args[key] === 'object' || typeof args[key] === 'function') {
argsReference[key] = args[key];
continue;
}
if (isVariableFromUri) {
argsReference[`_${key}`] = decodeURIComponent(args[key]);
} else {
argsReference[`_${key}`] = args[key];
}
if (argsReference[`${key}`] === undefined && argsReference[`_${key}`] !== undefined) {
Object.defineProperty(argsReference, key, {
set: (newValue) => {
argsReference[`_${key}`] = newValue;
document.body.dispatchEvent(new CustomEvent(`CONTEXT_${Swissknife.CamelToUnderscoreSnake(key).toUpperCase()}_CHANGED`, {
bubbles: true,
detail: {
newValue: newValue
}
}));
},
get: () => {
return argsReference[`_${key}`];
},
configurable: true
});
}
if (window.SwimAppControllersAndArgsMapping[controllerId].indexOf(key) === -1) {
window.SwimAppControllersAndArgsMapping[controllerId].push(key);
}
}
}
function clearContextArgs (argsReference, controllerId) {
const controllerArgs = window.SwimAppControllersAndArgsMapping[controllerId];
for (let i = 0; i < controllerArgs.length; i++) {
const key = controllerArgs[i];
delete argsReference[key];
}
}