blob: 08a9e02f4f13628e490423d3cdcc8e928188400e (
plain) (
blame)
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
|
export type Route = {
path: string;
params: Record<string, string>;
};
export class Router extends EventTarget {
constructor() {
super();
window.addEventListener('popstate', () => this.handleRouteChange());
}
private handleRouteChange() {
this.dispatchEvent(new CustomEvent('route-changed', { detail: this.getCurrentRoute() }));
}
getCurrentRoute(): Route {
const path = window.location.pathname.replace(/^\/v3\//, '');
const segments = path.split('/').filter(Boolean);
let routePath = '/';
const params: Record<string, string> = {};
if (segments[0] === 'feed' && segments[1]) {
routePath = '/feed';
params.feedId = segments[1];
} else if (segments[0] === 'tag' && segments[1]) {
routePath = '/tag';
params.tagName = segments[1];
}
return { path: routePath, params };
}
navigate(path: string) {
window.history.pushState({}, '', `/v3${path}`);
this.handleRouteChange();
}
}
export const router = new Router();
|