Skip to content

Commit

Permalink
refactor: 코드 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
BoYoung00 committed Dec 19, 2024
1 parent baf380c commit 8e2d7f0
Show file tree
Hide file tree
Showing 12 changed files with 169 additions and 174 deletions.
4 changes: 2 additions & 2 deletions src/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const Header = () => `
`;

// 로그인 여부에 따른 렌더링
function renderLoginStatus() {
const renderLoginStatus = () => {
const user = JSON.parse(localStorage.getItem("user") || "{}");
const path = window.location.pathname;

Expand All @@ -26,4 +26,4 @@ function renderLoginStatus() {
<li><a href="/login" id="login-but" class="text-gray-600">로그인</a></li>
`;
}
}
};
31 changes: 31 additions & 0 deletions src/events/loginEvents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { navigateTo } from "../router/router.js";
import { saveLocalStorage } from "../storage/storage.js";

export const loginEvents = () => {
const form = document.getElementById("login-form");
const emailInput = document.getElementById("username");
const passwordInput = document.getElementById("passwordInput");

// 로그인
form.addEventListener("submit", (e) => {
e.preventDefault();
const email = emailInput.value.trim();
const password = passwordInput.value.trim();

if (validateForm(email, password)) {
saveLocalStorage("user", { username: email, email: "", bio: "" });
console.log(localStorage.getItem("user"));
navigateTo("/profile");
}
});

// 유효성 검사
const validateForm = (email) => {
if (!email) {
alert("이메일을 입력해주세요.");
emailInput.focus();
return false;
}
return true;
};
};
41 changes: 41 additions & 0 deletions src/events/mainEvents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { navigateTo } from "../router/router.js";
import { clearLocalStorage, saveLocalStorage } from "../storage/storage.js";

export const mainEvents = () => {
// 헤더 이동
document.addEventListener("click", (e) => {
const target = e.target.closest("a");
if (target) {
e.preventDefault();
e.stopPropagation();
const href = target.getAttribute("href");
if (href) {
navigateTo(href);
}
}
});

// 프로필 수정
document.addEventListener("submit", (e) => {
e.preventDefault();
if (e.target && e.target.id === "profile-form") {
const updatedUser = {
username: document.getElementById("username").value,
email: document.getElementById("email").value,
bio: document.getElementById("bio").value,
};

saveLocalStorage("user", updatedUser);
alert("프로필이 업데이트 되었습니다.");
}
});

// 로그아웃
document.addEventListener("click", (e) => {
if (e.target && e.target.id === "logout") {
e.preventDefault();
clearLocalStorage();
navigateTo("/login");
}
});
};
12 changes: 1 addition & 11 deletions src/main.hash.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
import { navigateTo, resolveRoute } from "./router.js";
import { resolveRoute } from "./router/router.js";

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

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

// 라우터 초기화 호출
initializeRouter();
12 changes: 1 addition & 11 deletions src/main.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
import { navigateTo, resolveRoute } from "./router.js";
import { resolveRoute } from "./router/router.js";

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

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

// 라우터 초기화 호출
initializeRouter();
31 changes: 0 additions & 31 deletions src/pages/loginPage.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { navigateTo } from "../router.js";

export const LoginPage = () => {
return `
<main class="bg-gray-100 flex items-center justify-center min-h-screen">
Expand All @@ -25,32 +23,3 @@ export const LoginPage = () => {
</main>
`;
};

export const loginHandles = () => {
const form = document.getElementById("login-form");
const emailInput = document.getElementById("username");
const passwordInput = document.getElementById("passwordInput");

form.addEventListener("submit", (e) => {
e.preventDefault();
const email = emailInput.value.trim();
const password = passwordInput.value.trim();

if (validateForm(email, password)) {
localStorage.setItem(
"user",
JSON.stringify({ username: email, email: "", bio: "" }),
);
navigateTo("/profile");
}
});

const validateForm = (email) => {
if (!email) {
alert("이메일을 입력해주세요.");
emailInput.focus();
return false;
}
return true;
};
};
18 changes: 2 additions & 16 deletions src/pages/profilePage.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Header } from "../components/Header.js";
import { Footer } from "../components/Footer.js";
import { getLocalStorage } from "../storage/storage.js";

export const ProfilePage = () => {
const user = JSON.parse(localStorage.getItem("user")) || {
const user = getLocalStorage("user") || {
username: "",
email: "",
bio: "",
Expand Down Expand Up @@ -74,18 +75,3 @@ export const ProfilePage = () => {
</div>
`;
};

// 프로필 수정
document.addEventListener("submit", (e) => {
e.preventDefault();
if (e.target && e.target.id === "profile-form") {
const updatedUser = {
username: document.getElementById("username").value,
email: document.getElementById("email").value,
bio: document.getElementById("bio").value,
};

localStorage.setItem("user", JSON.stringify(updatedUser));
alert("프로필이 업데이트 되었습니다.");
}
});
24 changes: 0 additions & 24 deletions src/preferences/user.js

This file was deleted.

79 changes: 0 additions & 79 deletions src/router.js

This file was deleted.

47 changes: 47 additions & 0 deletions src/router/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { ErrorPage } from "../pages/errorPage.js";
import { getLocalStorage } from "../storage/storage.js";
import { eventRegister, Routes } from "./routes.js";

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

const getCurrentPath = () => {
if (isHashMode) {
return window.location.hash.slice(1) || "/";
} else {
return window.location.pathname;
}
};

export const resolveRoute = (isHash = false) => {
isHashMode = isHash;
const path = getCurrentPath();
const user = getLocalStorage("user");
const root = document.getElementById("root");

if (path === "/profile" && !user) {
navigateTo("/login");
return;
}
if (path === "/login" && user) {
navigateTo("/");
return;
}

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

export const navigateTo = (path) => {
if (isHashMode) {
window.location.hash = `#${path}`;
} else {
window.history.pushState(null, null, path);
}
resolveRoute(isHashMode);
};
33 changes: 33 additions & 0 deletions src/router/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { MainPage } from "../pages/mainPage.js";
import { LoginPage } from "../pages/loginPage.js";
import { ProfilePage } from "../pages/profilePage.js";
import { mainEvents } from "../events/mainEvents.js";
import { loginEvents } from "../events/loginEvents.js";

export const PATHS = {
MAIN: "/",
LOGIN: "/login",
PROFILE: "/profile",
};

export const Routes = {
[PATHS.MAIN]: () => MainPage(),
[PATHS.LOGIN]: () => LoginPage(),
[PATHS.PROFILE]: () => ProfilePage(),
};

// 경로별 이벤트 등록
export const eventRegister = (path) => {
switch (path) {
case PATHS.MAIN:
case PATHS.PROFILE:
mainEvents();
break;
case PATHS.LOGIN:
loginEvents();
break;
default:
console.warn(`No events to register for path: ${path}`);
break;
}
};
11 changes: 11 additions & 0 deletions src/storage/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export const saveLocalStorage = (key, value) => {
localStorage.setItem(key, JSON.stringify(value));
};

export const getLocalStorage = (key) => {
return JSON.parse(localStorage.getItem(key));
};

export const clearLocalStorage = () => {
localStorage.clear();
};

0 comments on commit 8e2d7f0

Please sign in to comment.