-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
145 lines (126 loc) · 3.76 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
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
class Router {
/**
* Контейнер встраивания страниц
* @type {Element}
*/
target;
/**
* Список путей до страниц
* @type {Array<{path: string, view: Element}>}
* 1. path - путь до страницы
* 2. view - страница
*/
routes;
/**
* Инициализирует роутер
* @this {Router} объект Router
* @param {{target: Element, routes: Array<{path: string, view: Element}>}} params
* Параметры инициализации
* 1. target - контейнер встривания страниц
* 2. routes - список путей до страниц
* 3. path - путь до страницы
* 4. view - страница
*/
initRouter(params) {
this.target = params.target;
this.routes = params.routes;
this.#mount();
}
/**
* Монтирует роутер
* @private
* @this {Router} объект Router
*/
#mount() {
window.addEventListener("popstate", () => {
this.router();
});
const initNavigation = () => {
document.body.addEventListener("click", (e) => {
if (e.target.matches("[data-link]")) {
e.preventDefault();
this.#navigateTo(e.target.href);
}
});
this.router();
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initNavigation);
} else {
initNavigation();
}
}
/**
* Создаёт регулярное выражение из пути до страницы
* @private
* @this {Router} объект Router
* @param {string} path - путь до страницы
* @returns {RegExp} ругулярное выражение
*/
#pathToRegex(path) {
return new RegExp(
"^" + path.replace(/\//g, "\\/").replace(/:\w+/g, "(.+)") + "$"
);
}
/**
* Направляет на указанный url страницы
* @this {Router} объект Router
* @param {string} url - полный адрес страницы
*/
#navigateTo(url) {
history.pushState(null, null, url);
this.router();
}
/**
* Получает значение параметра из пути до страницы
* @this {Router} объект Router
* @param {string} path - путь до страницы
* @returns {Object<string, string | number | undefined>} значение параметра
*/
getParams(path) {
const local = location.pathname.match(this.#pathToRegex(path));
const values = local.slice(1);
const keys = Array.from(path.matchAll(/:(\w+)/g)).map(
(result) => result[1]
);
return Object.fromEntries(
keys.map((key, i) => {
return [key, values[i]];
})
);
}
/**
* Направляет на указанный endPoint страницы
* @this {Router} объект Router
* @param {string} endPoint - конечная точка путь до страницы
*/
navigate(endPoint) {
history.pushState(null, null, location.origin + endPoint);
location.reload();
}
/**
* Рендерит страницу по указанному пути
* @this {Router} объект Router
*/
async router() {
const potentialMatches = this.routes.map((route) => {
return {
route: route,
result: location.pathname.match(this.#pathToRegex(route.path)),
};
});
let match = potentialMatches.find(
(potentialMatch) => potentialMatch.result !== null
);
if (!match) {
match = {
route: this.routes[0],
result: [location.pathname],
};
}
const elem = await match.route.view();
this.target.innerHTML = "";
this.target.append(elem);
}
}
export default new Router();