From 1fe081b27c274d4645cb24741eb6f16fa8ef3815 Mon Sep 17 00:00:00 2001 From: rladydqls99 Date: Fri, 20 Dec 2024 00:54:06 +0900 Subject: [PATCH] feat: advanced test pass --- src/components/Header.js | 8 +++---- src/main.js | 46 +++++++++++++++++++++++++++++++++++++--- 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/components/Header.js b/src/components/Header.js index 9db1962c..3d5ebc56 100644 --- a/src/components/Header.js +++ b/src/components/Header.js @@ -7,12 +7,12 @@ const Header = () => ` diff --git a/src/main.js b/src/main.js index 3b53ffe7..50b90df4 100644 --- a/src/main.js +++ b/src/main.js @@ -14,6 +14,11 @@ import { const $root = document.getElementById("root"); +const hashRoutes = [ + { path: "#/", component: () => Layout(HomePage) }, + { path: "#/profile", component: () => Layout(ProfilePage) }, + { path: "#/login", component: () => LoginPage }, +]; const routes = [ { path: "/", component: () => Layout(HomePage) }, { path: "/profile", component: () => Layout(ProfilePage) }, @@ -26,6 +31,10 @@ const router = (path) => { if (_path === "/profile" && !isAuthenticated()) { _path = "/login"; } + if (_path === "/login" && isAuthenticated()) { + _path = "/"; + } + const route = routes.find((route) => route.path === _path); window.history.pushState(null, "", _path); @@ -38,8 +47,34 @@ const router = (path) => { $root.innerHTML = ErrorPage(); } }; +const hashRouter = (path) => { + let _path = path ?? window.location.hash; + + const routeName = _path.replace("#/", ""); + + if (routeName === "profile" && !isAuthenticated()) { + window.location.hash = "#/login"; + return; + } + if (routeName === "login" && isAuthenticated()) { + window.location.hash = "#/"; + return; + } + + const route = hashRoutes.find((route) => route.path === `#/${routeName}`); + window.location.hash = `#/${routeName}`; -const setProfile = () => { + if (route) { + $root.innerHTML = route.component(); + if (routeName === "profile" && isAuthenticated()) { + setProfile(); + } + } else { + $root.innerHTML = ErrorPage(); + } +}; + +export const setProfile = () => { const user = getUserFromStorage(); const profileForm = document.getElementById("profile-form"); @@ -76,11 +111,14 @@ const handleLogout = () => { }; window.addEventListener("DOMContentLoaded", () => { - router(); + window.location.hash ? hashRouter() : router(); }); window.addEventListener("popstate", () => { router(); }); +window.addEventListener("hashchange", () => { + hashRouter(); +}); window.addEventListener("click", (e) => { if (e.target.tagName === "A" && e.target.pathname) { e.preventDefault(); @@ -89,7 +127,9 @@ window.addEventListener("click", (e) => { handleLogout(); return; } - router(e.target.pathname); + window.location.hash + ? hashRouter(e.target.pathname) + : router(e.target.pathname); } }); window.addEventListener("submit", (e) => {