diff --git a/src/__tests__/advanced.hashRouter.test.js b/src/__tests__/advanced.hashRouter.test.js index ada56064..6ac1de07 100644 --- a/src/__tests__/advanced.hashRouter.test.js +++ b/src/__tests__/advanced.hashRouter.test.js @@ -4,7 +4,7 @@ beforeAll(async () => { // DOM 초기화 window.alert = vi.fn(); document.body.innerHTML = '
'; - await import("../main.hash.js"); + await import("../main.hash.ts"); }); afterAll(() => { diff --git a/src/core/render.ts b/src/core/render.ts index 143d8b85..f156262b 100644 --- a/src/core/render.ts +++ b/src/core/render.ts @@ -9,6 +9,11 @@ export const render = () => { router.navigateTo(window.location.pathname); }); + window.addEventListener("hashchange", () => { + const pathname = window.location.hash.split("#")[1]; + router.navigateTo(pathname); + }); + window.addEventListener("submit", (e) => { e.preventDefault(); }); diff --git a/src/core/router.ts b/src/core/router.ts index 4eb3e1f6..e0589e20 100644 --- a/src/core/router.ts +++ b/src/core/router.ts @@ -4,11 +4,12 @@ import { LoginPage } from "@/pages/Login"; import { ProfilePage } from "@/pages/Profile"; import { userStore } from "@/store/userStore"; -const createRouter = (routes: { [key: string]: () => void }) => { +const createRouter = (routes: Record void>) => { return { navigateTo(path: string) { if (!Object.keys(routes).includes(path)) { - path = "/error"; + routes["/error"](); + return; } history.pushState(null, "", path); @@ -17,6 +18,21 @@ const createRouter = (routes: { [key: string]: () => void }) => { }; }; +const createHashRouter = (routes: Record void>) => { + return { + navigateTo(path: string) { + if (!Object.keys(routes).includes(`${path}`)) { + window.location.hash = `#/error`; + routes["/error"](); + return; + } + + window.location.hash = `#${path}`; + routes[path](); + }, + }; +}; + const routeGuard = (render: () => void) => () => { if (window.location.pathname !== "/login" && !userStore.getUser()) { router.navigateTo("/login"); @@ -38,6 +54,9 @@ const routes = { "/error": ErrorPage.render, }; -const router = createRouter(routes); +const browserRouter = createRouter(routes); +const hashRouter = createHashRouter(routes); + +const router = window.location.hash ? hashRouter : browserRouter; -export { router }; +export { router, hashRouter };