-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
89 lines (71 loc) · 2.01 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
/* eslint-disable import/extensions */
// Components
import {
HomeComponent
} from "./components/home.component.js";
import {
ErrorComponent
} from "./components/error.component.js";
import {
ShortLinkComponent
} from "./components/short-link.component.js";
// Routes
const routes = [{
path: "/",
component: HomeComponent
},
{
path: "/404",
component: ErrorComponent
},
];
function renderComponent(component) {
const appDiv = document.querySelector("#app");
appDiv.innerHTML = component.render();
try {
component.injectCode().forEach(codeInfo => {
const element = document.querySelector(codeInfo.querySelector)
if (codeInfo.operation === 'editInnerText') {
element.innerText = codeInfo.newText
} else if (codeInfo.operation === 'editAttribute') {
element.setAttribute(codeInfo.attribute, codeInfo.newValue)
} else if (codeInfo.operation === 'append') {
element.insertAdjacentHTML(codeInfo.position, codeInfo.code)
} else if (codeInfo.operation === 'remove') {
element.remove()
}
});
} catch (error) {
console.log(error);
}
}
const router = () => {
// Get the current path
const currentPath = window.location.pathname || '/';
// const currentPath = window.location.hash.slice(1) || "/"; // way of tutorial
console.log(currentPath);
// Find the component based on the current path
const {
component = ShortLinkComponent
} =
routes.find((route) => {
return route.path === currentPath;
}) || {};
// Render the component in the "app" placeholder
if (component === ShortLinkComponent) {
const slug = currentPath.split("/")[1];
console.log(slug);
if (slug !== "" && slug !== " ") {
component.get(slug);
}
} else {
renderComponent(component)
}
};
const test = () => {
console.log('pathname: ', window.location.pathname);
console.log('hash: ', window.location.hash);
router();
};
window.addEventListener("load", test);
window.addEventListener("hashchange", test);