-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
97 lines (75 loc) · 2.58 KB
/
index.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
import {
extractRouteParams,
findMatchingRouteIdentifier
} from './core/routeParams';
import {renderTemplates} from './core/templates';
export const createRouter = domEntryPoint => {
let routes = {};
const lastDomEntryPoint = domEntryPoint.cloneNode(true);
let lastRouteHandler = null;
const navigateTo = hashUrl => {
window.location.hash = hashUrl;
};
const otherwise = routeHandler => {
routes['*'] = routeHandler;
};
const addRoute = (hashUrl, routeHandler, data) => {
routes[hashUrl] = routeHandler;
routes[hashUrl].data = data;
return {addRoute, otherwise, navigateTo};
};
const initializeDomElement = () => {
if (!domEntryPoint.parentElement) {
return;
}
const domClone = lastDomEntryPoint.cloneNode(true);
domEntryPoint.parentElement.insertBefore(domClone, domEntryPoint);
if (typeof domEntryPoint.remove === 'undefined') {
domEntryPoint.removeNode(true);
} else {
domEntryPoint.remove();
}
domEntryPoint = domClone;
};
const disposeLastRoute = () => {
if (!lastRouteHandler) return;
if (typeof lastRouteHandler.dispose === 'undefined') return;
lastRouteHandler.dispose(domEntryPoint);
};
const handleRouting = () => {
const defaultRouteIdentifier = '*';
const currentHash = location.hash.slice(1);
const maybeMatchingRouteIdentifier = findMatchingRouteIdentifier(currentHash, Object.keys(routes));
let routeParams = {};
if (maybeMatchingRouteIdentifier) {
routeParams = extractRouteParams(maybeMatchingRouteIdentifier, currentHash);
}
const routeHandler = Object.keys(routes).indexOf(maybeMatchingRouteIdentifier) > -1 ? routes[maybeMatchingRouteIdentifier] : routes[defaultRouteIdentifier];
if (!routeHandler) {
return;
}
disposeLastRoute(routeHandler);
// Memory last routeHandler
lastRouteHandler = routeHandler;
initializeDomElement();
if (typeof routeHandler === 'function') {
routeHandler(domEntryPoint, routeParams, routeHandler.data);
} else {
if (!routeHandler.templateString && !routeHandler.templateId && !routeHandler.templateUrl) {
throw Error(`No template configured for route ${currentHash}`);
}
renderTemplates(routeHandler, domEntryPoint, () => {
if (typeof routeHandler.routeHandler === 'function') {
routeHandler.routeHandler(domEntryPoint, routeParams, routeHandler.data);
}
});
}
};
if (window) {
window.removeEventListener('hashchange', handleRouting);
window.addEventListener('hashchange', handleRouting);
window.removeEventListener('load', handleRouting);
window.addEventListener('load', handleRouting);
}
return {addRoute, otherwise, navigateTo};
};