Skip to content

Commit

Permalink
feat: implement hash router
Browse files Browse the repository at this point in the history
  • Loading branch information
2dowon committed Dec 18, 2024
1 parent ecf9f1f commit dd86e42
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
5 changes: 5 additions & 0 deletions src/main.hash.js
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
import "./main.js";
import { useRouter } from "./utils/useRouter";

const { router } = useRouter("hash");

window.addEventListener("hashchange", () => router());
2 changes: 1 addition & 1 deletion src/main.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useRouter } from "./utils/useRouter";

const { router } = useRouter();
const { router } = useRouter("history");

window.addEventListener("load", () => router());
window.addEventListener("popstate", () => router());
25 changes: 20 additions & 5 deletions src/utils/useRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ const PATHNAME_PAGE_MAP = {
"/profile": () => renderProfilePage(),
};

export const useRouter = () => {
export const useRouter = (type) => {
const routeGuard = (path) => {
let pathname = path;
const isLogin = useUserStore.isLogin();

if (pathname === "/profile" && !isLogin) {
pathname = "/login";
} else if (pathname === "/login" && isLogin) {
const refinedPathname = pathname.replace("#", "");

if (refinedPathname === "/profile" && !isLogin) {
pathname = `${type === "hash" ? "#" : ""}/login`;
} else if (refinedPathname === "/login" && isLogin) {
pathname = "/";
}

Expand All @@ -37,7 +39,20 @@ export const useRouter = () => {
render();
};

return { router: historyRouter };
const hashRouter = (hash) => {
let newHash = hash || window.location.hash;
newHash = routeGuard(newHash);

let render = PATHNAME_PAGE_MAP[newHash.replace("#", "")];
if (!render) {
render = () => renderNotFoundPage();
}

history.pushState(null, "", newHash);
render();
};

return { router: type === "history" ? historyRouter : hashRouter };
};

const renderMainPage = () => {
Expand Down

0 comments on commit dd86e42

Please sign in to comment.