aboutsummaryrefslogtreecommitdiffstats
path: root/frontend-vanilla/src/router.ts
blob: 46fbe06f6c089d52ded30fa57ae1ca5a78f50cd6 (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
export type Route = {
    path: string;
    params: Record<string, string>;
    query: URLSearchParams;
};

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 url = new URL(window.location.href);
        const path = url.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 = decodeURIComponent(segments[1]);
        }

        return { path: routePath, params, query: url.searchParams };
    }

    navigate(path: string, query?: Record<string, string>) {
        let url = `/v3${path}`;
        if (query) {
            const params = new URLSearchParams(query);
            url += `?${params.toString()}`;
        }
        window.history.pushState({}, '', url);
        this.handleRouteChange();
    }

    updateQuery(updates: Record<string, string>) {
        const url = new URL(window.location.href);
        for (const [key, value] of Object.entries(updates)) {
            if (value) {
                url.searchParams.set(key, value);
            } else {
                url.searchParams.delete(key);
            }
        }
        window.history.pushState({}, '', url.toString());
        this.handleRouteChange();
    }
}

export const router = new Router();