-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.js
More file actions
82 lines (70 loc) · 2.02 KB
/
router.js
File metadata and controls
82 lines (70 loc) · 2.02 KB
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
import { EVENT_NAVIGATION } from "./globals.js";
import { store } from "./store.js";
class Router {
constructor() {
this._error = undefined;
window.onhashchange = ({ newURL }) => {
const fragment =
newURL.indexOf("#") === -1
? "/"
: newURL.substring(newURL.indexOf("#") + 1);
this.navigate(fragment);
};
// If the user routes to a specific URL from the beginning, it should load the appropriate page.
setTimeout(() => {
const current = this.currentRoute();
this.navigate(current);
});
}
routes = [];
defineError = (cb) => {
this._error = cb;
};
add = (path, cb) => {
this.routes.push({ path, cb });
return this;
};
remove = (path) => {
for (let i = 0; i < this.routes.length; i += 1) {
if (this.routes[i].path === path) {
this.routes.slice(i, 1);
return this;
}
}
return this;
};
currentRoute = () => {
return window.location.href.indexOf("#") === -1
? "/"
: window.location.href.substring(window.location.href.indexOf("#") + 1);
};
next = () => {
const current = this.currentRoute();
let currentIndex = -1;
this.routes.forEach((e, i) => {
if (e.path === current) currentIndex = i;
});
const prevRoute =
this.routes[
currentIndex === 0 ? this.routes.length - 1 : currentIndex - 1
];
this.navigate(prevRoute.path);
};
previous = () => {
const current = this.currentRoute();
let currentIndex = -1;
this.routes.forEach((e, i) => {
if (e.path === current) currentIndex = i;
});
const nextRoute = this.routes[(currentIndex + 1) % this.routes.length];
this.navigate(nextRoute.path);
};
navigate = (routingUrl = "") => {
window.history.pushState(null, null, "/#" + routingUrl);
const routes = this.routes.filter((r) => r.path === routingUrl);
if (routes && routes[0]) routes[0].cb();
else this._error();
store.dispatchEvent(new CustomEvent(EVENT_NAVIGATION));
};
}
export default Router;