-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrouter.js
62 lines (53 loc) · 1.43 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
function router() {
let routes = {};
function get(path, callback) {
routes[path] = callback;
}
function navigate(url) {
const parsedUrl = new URL(url);
const callback = routes[parsedUrl.pathname] || routes.default;
callback({
url: parsedUrl,
redirect
});
}
function redirect(path) {
const url = window.location.origin + path;
window.history.pushState(null, null, url);
navigate(url);
}
function handleClick(event) {
if (
"external" in event.target.dataset ||
event.button !== 0 ||
event.metaKey ||
event.shiftKey ||
event.altKey ||
event.ctrlKey
)
return;
if (event.target.tagName === "A") {
event.preventDefault();
window.history.pushState(null, null, event.target.href);
navigate(event.target.href);
}
}
function handlePop() {
navigate(window.location);
}
function listen() {
window.addEventListener("click", handleClick);
window.addEventListener("popstate", handlePop);
navigate(window.location);
}
function close() {
window.removeEventListener("click", handleClick);
window.removeEventListener("popstate", handlePop);
}
return {
get,
listen,
close
};
}
export default router;