Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[6팀 김혜연] Chapter 1-1. 프레임워크 없이 SPA 만들기 #54

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/components/Footer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const Footer = () => `
<footer class="bg-gray-200 p-4 text-center">
<p>&copy; 2024 항해플러스. All rights reserved.</p>
</footer>
`;
7 changes: 7 additions & 0 deletions src/components/Header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const Header = () => {
return `
<header class="bg-blue-600 text-white p-4 sticky top-0">
<h1 class="text-2xl font-bold">항해플러스</h1>
</header>
`;
};
14 changes: 14 additions & 0 deletions src/components/Layout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Header } from "./Header.js";
import { Footer } from "./Footer.js";
import { Navbar } from "./Navbar.js";

export const Layout = (content) => `
<div class="bg-gray-100 min-h-screen flex justify-center">
<div class="max-w-md w-full">
${Header()}
${Navbar()}
${content}
${Footer()}
</div>
</div>
`;
30 changes: 30 additions & 0 deletions src/components/Navbar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export const Navbar = () => {
const user = JSON.parse(localStorage.getItem("user"));

const currentPath = window.location.hash
? window.location.hash.replace(/^#/, "") || "/"
: window.location.pathname;

const isHomeActive = currentPath === "/";
const isProfileActive = currentPath === "/profile";

const homeLinkClass = isHomeActive
? "text-blue-600 font-bold"
: "text-gray-600";
const profileLinkClass = isProfileActive
? "text-blue-600 font-bold"
: "text-gray-600";

return `
<nav class="bg-white shadow-md p-2 sticky top-14">
<ul class="flex justify-around">
<li><a href="/" data-link class="${homeLinkClass}">홈</a></li>
<li><a href="/profile" data-link class="${profileLinkClass}">프로필</a></li>
${
user
? `<li><a href="/login" id="logout" class="text-gray-600 cursor-pointer">로그아웃</a></li>`
: `<li><a href="/login" data-link class="text-gray-600">로그인</a></li>`
}
</ul>
</nav>`;
};
48 changes: 48 additions & 0 deletions src/lib/eventHandlers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import userStore from "./store.js";

export const setupEventHandlers = (router) => {
const root = document.getElementById("root");

root.addEventListener("click", (e) => {
if (e.target.id === "logout") {
userStore.logout();
}
});

root.addEventListener("submit", (e) => {
if (e.target.id === "login-form") {
e.preventDefault();
const { username } = e.target.elements;

if (!username.value.trim()) {
alert("유저 이름을 입력해 주세요.");
return;
}

try {
userStore.login(username.value);
router.navigate("/");
} catch (error) {
alert(error.message);
}
}

if (e.target.id === "profile-form") {
e.preventDefault();
const { username, email, bio } = e.target.elements;

const userData = {
username: username.value,
email: email.value,
bio: bio.value,
};

try {
userStore.updateProfile(userData);
alert("프로필이 업데이트되었습니다.");
} catch (error) {
alert(error.message);
}
}
});
};
131 changes: 131 additions & 0 deletions src/lib/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { MainPage } from "../pages/MainPage.js";
import { ProfilePage } from "../pages/ProfilePage.js";
import { LoginPage } from "../pages/LoginPage.js";
import { ErrorPage } from "../pages/ErrorPage.js";

const routes = {
"/": MainPage,
"/profile": ProfilePage,
"/login": LoginPage,
"/404": ErrorPage,
};

const routerTypes = {
history: {
getPath: () => window.location.pathname,

updateURL: (url, { replace = false } = {}) => {
const pathname = url.startsWith("http") ? new URL(url).pathname : url;

if (replace) {
history.replaceState(null, null, pathname);
} else {
history.pushState(null, null, pathname);
}
return pathname;
},

setupListeners: (handleRoute) => {
const popstateHandler = () => handleRoute(routerTypes.history.getPath());
window.removeEventListener("popstate", popstateHandler);
window.addEventListener("popstate", popstateHandler);

const clickHandler = (e) => {
const link = e.target.closest("[data-link]");
if (link) {
e.preventDefault();
const path = routerTypes.history.updateURL(link.href);
handleRoute(path);
}
};
document.removeEventListener("click", clickHandler);
document.addEventListener("click", clickHandler);
},
},
hash: {
getPath: () => {
const hash = window.location.hash.replace(/^#/, "");
return hash ? hash : "/";
},

updateURL: (url, { replace = false } = {}) => {
const hashPath = url.startsWith("http")
? new URL(url).hash.replace(/^#/, "")
: url.replace(/^#/, "");
const targetHash = hashPath.startsWith("/") ? hashPath : `/${hashPath}`;

if (replace) {
const currentURL = new URL(window.location.href);
currentURL.hash = targetHash;
history.replaceState(null, null, currentURL.href);
} else {
window.location.hash = targetHash;
}

return targetHash;
},

setupListeners: (handleRoute) => {
const hashChangeHandler = () => handleRoute(routerTypes.hash.getPath());
window.removeEventListener("hashchange", hashChangeHandler);
window.addEventListener("hashchange", hashChangeHandler);

const clickHandler = (e) => {
const link = e.target.closest("[data-link]");
if (link) {
e.preventDefault();
const href = link.getAttribute("href");
const path = routerTypes.hash.updateURL(href);
handleRoute(path);
}
};
document.removeEventListener("click", clickHandler);
document.addEventListener("click", clickHandler);
},
},
};

const createRouter = (type = "history") => {
const router = routerTypes[type];
let rootElement;

const renderPage = (path) => {
const page = routes[path] || routes["/404"];
if (!page) return;
rootElement.innerHTML = page();
};

const handleRoute = (path) => {
const user = JSON.parse(localStorage.getItem("user"));

if (path === "/profile" && !user) {
navigate("/login", { replace: true });
return;
}

if (path === "/login" && user) {
navigate("/", { replace: true });
return;
}

renderPage(path);
};

const navigate = (url, options) => {
const path = router.updateURL(url, options);
handleRoute(path);
return path;
};

const init = (rootElementId) => {
rootElement = document.getElementById(rootElementId);
if (!rootElement) return;

router.setupListeners(handleRoute);
handleRoute(router.getPath());
};

return { init, navigate };
};

export default createRouter;
38 changes: 38 additions & 0 deletions src/lib/store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const userStore = {
getUser() {
const user = localStorage.getItem("user");
return user ? JSON.parse(user) : null;
},

isLoggedIn() {
return !!userStore.getUser();
},

login(username) {
const userData = {
username: username,
email: "",
bio: "",
};

localStorage.setItem("user", JSON.stringify(userData));
return userData;
},

logout() {
localStorage.removeItem("user");
},

updateProfile(userData) {
if (!userStore.isLoggedIn()) {
throw new Error("로그인이 필요합니다.");
}

const currentUser = userStore.getUser();
const updatedUser = { ...currentUser, ...userData };
localStorage.setItem("user", JSON.stringify(updatedUser));
return updatedUser;
},
};

export default userStore;
7 changes: 6 additions & 1 deletion src/main.hash.js
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
import "./main.js";
import createRouter from "./lib/router.js";
import { setupEventHandlers } from "./lib/eventHandlers.js";

const hashRouter = createRouter("hash");
hashRouter.init("root");
setupEventHandlers(hashRouter);
Loading
Loading