Skip to content

Commit

Permalink
12/18 라우터 분류
Browse files Browse the repository at this point in the history
  • Loading branch information
BoYoung00 committed Dec 18, 2024
1 parent 34588cc commit ab71b6a
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 105 deletions.
6 changes: 3 additions & 3 deletions src/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ function renderLoginStatus() {

if (user.username) {
return `
<li><a href="/" class="${path === "/" ? "text-blue-600" : "text-gray-600"}">홈</a></li>
<li><a href="/profile" class="${path === "/profile" ? "text-blue-600" : "text-gray-600"}">프로필</a></li>
<li><a href="/" class="${path === "/" ? "text-blue-600 font-bold" : "text-gray-600"}">홈</a></li>
<li><a href="/profile" class="${path === "/profile" ? "text-blue-600 font-bold" : "text-gray-600"}">프로필</a></li>
<li><a href="/login" id="logout" class="text-gray-600">로그아웃</a></li>
`;
} else {
return `
<li><a href="/" class="text-blue-600">홈</a></li>
<li><a href="/" class="text-blue-600 font-bold">홈</a></li>
<li><a href="/login" id="login-but" class="text-gray-600">로그인</a></li>
`;
}
Expand Down
18 changes: 17 additions & 1 deletion src/main.hash.js
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
import "./main.js";
import { resolveRoute } from "./router.js";

document.addEventListener("click", (e) => {
if (e.target && e.target.id === "logout") {
e.preventDefault();
localStorage.clear();
}
});

// 이벤트 초기화
const initializeRouter = () => {
window.addEventListener("hashchange", () => resolveRoute(true));
window.addEventListener("load", () => resolveRoute(true));
};

// 라우터 초기화 호출
initializeRouter();
82 changes: 3 additions & 79 deletions src/main.js
Original file line number Diff line number Diff line change
@@ -1,92 +1,16 @@
import { MainPage } from "./pages/mainPage.js";
import { attachLoginHandler, LoginPage } from "./pages/loginPage.js";
import { ProfilePage } from "./pages/profilePage.js";
import { ErrorPage } from "./pages/errorPage.js";
import { resolveRoute } from "./router.js";

// 로그아웃
document.addEventListener("click", (e) => {
if (e.target && e.target.id === "logout") {
e.preventDefault();
localStorage.clear();
}
});

// 링크 이벤트 처리
const routeHandlers = () => {
document.querySelectorAll("a").forEach((link) => {
link.addEventListener("click", (e) => {
e.preventDefault();
const href = link.getAttribute("href");
navigateTo(href);
});
});
};

// 라우터 설정
const Routes = {
"/": () => MainPage(),
"/login": () => LoginPage(),
"/profile": () => ProfilePage(),
};

// 초기 URL 모드 확인
const isHashMode = window.location.href.includes("index.hash.html");

// 현재 경로 계산
const getCurrentPath = () => {
if (isHashMode) {
const hash = window.location.hash.slice(1); // # 제거
return hash || "/"; // 빈 해시인 경우 홈 경로로 설정
} else {
return window.location.pathname;
}
};

// 공통 라우팅 처리
const resolveRoute = () => {
const path = getCurrentPath();
const user = JSON.parse(localStorage.getItem("user") || "{}");
const root = document.getElementById("root");

// 인증된 사용자 경로 처리
if (path === "/profile" && !user.username) {
navigateTo("/login");
return;
}

const route = Routes[path];
if (route) {
root.innerHTML = route();
} else {
root.innerHTML = ErrorPage();
}

// 로그인 이벤트 핸들러 추가
if (path === "/login") {
attachLoginHandler();
}
// 링크 이벤트 처리
routeHandlers();
};

// 페이지 이동 함수
export const navigateTo = (path) => {
if (isHashMode) {
window.location.hash = `#${path}`;
} else {
window.history.pushState(null, null, path);
}
resolveRoute();
};

// 이벤트 초기화
const initializeRouter = () => {
if (isHashMode) {
window.addEventListener("hashchange", resolveRoute);
} else {
window.addEventListener("popstate", resolveRoute);
}
window.addEventListener("load", resolveRoute);
window.addEventListener("popstate", () => resolveRoute(false));
window.addEventListener("load", () => resolveRoute(false));
};

// 라우터 초기화 호출
Expand Down
46 changes: 24 additions & 22 deletions src/pages/loginPage.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
import { navigateTo } from "../main.js";
import { navigateTo } from "../router.js";

export const LoginPage = () => `
<main class="bg-gray-100 flex items-center justify-center min-h-screen">
<div class="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
<h1 class="text-2xl font-bold text-center text-blue-600 mb-8">항해플러스</h1>
<form id="login-form">
<div class="mb-4">
<input type="text" id="username" placeholder="사용자 이름" class="w-full p-2 border rounded">
export const LoginPage = () => {
return `
<main class="bg-gray-100 flex items-center justify-center min-h-screen">
<div class="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
<h1 class="text-2xl font-bold text-center text-blue-600 mb-8">항해플러스</h1>
<form id="login-form">
<div class="mb-4">
<input type="text" id="username" placeholder="사용자 이름" class="w-full p-2 border rounded">
</div>
<div class="mb-6">
<input type="password" placeholder="비밀번호" id="passwordInput" class="w-full p-2 border rounded">
</div>
<button type="submit" class="w-full bg-blue-600 text-white p-2 rounded font-bold">로그인</button>
</form>
<div class="mt-4 text-center">
<a href="#" class="text-blue-600 text-sm">비밀번호를 잊으셨나요?</a>
</div>
<div class="mb-6">
<input type="password" placeholder="비밀번호" id="passwordInput" class="w-full p-2 border rounded">
<hr class="my-6">
<div class="text-center">
<button class="bg-green-500 text-white px-4 py-2 rounded font-bold">새 계정 만들기</button>
</div>
<button type="submit" class="w-full bg-blue-600 text-white p-2 rounded font-bold">로그인</button>
</form>
<div class="mt-4 text-center">
<a href="#" class="text-blue-600 text-sm">비밀번호를 잊으셨나요?</a>
</div>
<hr class="my-6">
<div class="text-center">
<button class="bg-green-500 text-white px-4 py-2 rounded font-bold">새 계정 만들기</button>
</div>
</div>
</main>
`;
</main>
`;
};

export const attachLoginHandler = () => {
export const loginHandles = () => {
const form = document.getElementById("login-form");
const emailInput = document.getElementById("username");
const passwordInput = document.getElementById("passwordInput");
Expand Down
77 changes: 77 additions & 0 deletions src/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { MainPage } from "./pages/mainPage.js";
import { loginHandles, LoginPage } from "./pages/loginPage.js";
import { ProfilePage } from "./pages/profilePage.js";
import { ErrorPage } from "./pages/errorPage.js";

// 초기 URL 모드
let isHashMode = false;

// 링크 이벤트 처리
const routeHandlers = () => {
document.querySelectorAll("a").forEach((link) => {
link.addEventListener("click", (e) => {
e.preventDefault();
const href = link.getAttribute("href");
navigateTo(href);
});
});
};

const Routes = {
"/": () => MainPage(),
"/login": () => LoginPage(),
"/profile": () => ProfilePage(),
};

// 현재 경로 계산
const getCurrentPath = () => {
if (isHashMode) {
const hash = window.location.hash.slice(1); // # 제거
return hash || "/";
} else {
return window.location.pathname;
}
};

// 공통 라우팅 처리
export const resolveRoute = (isHash = false) => {
isHashMode = isHash;
const path = getCurrentPath();
const user = JSON.parse(localStorage.getItem("user") || null);
const root = document.getElementById("root");
console.log("user", user);

// 인증 경로 가드
if (path === "/profile" && user == null) {
navigateTo("/login");
return;
}
if (path === "/login" && user != null) {
navigateTo("/");
return;
}

const route = Routes[path];

if (route) {
root.innerHTML = route();
} else {
root.innerHTML = ErrorPage();
}

// 로그인 이벤트 핸들러 추가
if (path === "/login") {
loginHandles();
}
routeHandlers();
};

// 페이지 이동 함수
export const navigateTo = (path) => {
if (isHashMode) {
window.location.hash = `#${path}`;
} else {
window.history.pushState(null, null, path);
}
resolveRoute();
};

0 comments on commit ab71b6a

Please sign in to comment.