-
Notifications
You must be signed in to change notification settings - Fork 78
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
Anne-Hyeyeon
wants to merge
16
commits into
hanghae-plus:main
Choose a base branch
from
Anne-Hyeyeon:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
113e912
refactor: 프로젝트 구조 변경
Anne-Hyeyeon e79bcb8
feat: 함수형 라우터 구현
Anne-Hyeyeon 3c456f1
fix: 라우터 네비게이트 기능 추가
Anne-Hyeyeon 8943f69
refactor: 이벤트 핸들러 분리
Anne-Hyeyeon 1cb516c
feat: 유저 관련 기능 함수 추가
Anne-Hyeyeon 3ee995a
fix: 로그아웃 후 로그인 페이지로 리다이렉팅이 되는 오류 수정
Anne-Hyeyeon d694c80
refactor: footer, header 컴포넌트 분리
Anne-Hyeyeon cbead1a
fix: layout 생성 후 적용
Anne-Hyeyeon 631674e
fix: DOMContentLoaded 이벤트 리스너 삭제
Anne-Hyeyeon 19753aa
refactor: 스토어명 변경
Anne-Hyeyeon 976dd36
fix: logout button을 a로 수정
Anne-Hyeyeon 61e6767
fix: 로그아웃 후 로그인 페이지로 리다이렉팅하도록 수정
Anne-Hyeyeon 4642a70
fix: 잘못된 플레이스홀더 수정
Anne-Hyeyeon 359788b
feat: hash router 추가
Anne-Hyeyeon a930a90
fix: navbar 동작 방식 수정
Anne-Hyeyeon 8e3f9b5
fix: logout 동작 수정
Anne-Hyeyeon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Empty file.
Empty file.
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
// src/lib/router.js | ||
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, | ||
|
||
navigate: (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) => { | ||
if (e.target.matches("[data-link]")) { | ||
e.preventDefault(); | ||
const path = routerTypes.history.navigate(e.target.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) { | ||
router.navigate("/login", { replace: true }); | ||
return; | ||
} | ||
renderPage(path); | ||
}; | ||
|
||
const init = (rootElementId) => { | ||
rootElement = document.getElementById(rootElementId); | ||
if (!rootElement) return; | ||
|
||
router.setupListeners(handleRoute); | ||
handleRoute(router.getPath()); | ||
}; | ||
|
||
return { init, navigate: router.navigate }; | ||
}; | ||
|
||
export const router = createRouter("history"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,241 +1,5 @@ | ||
const MainPage = () => ` | ||
<div class="bg-gray-100 min-h-screen flex justify-center"> | ||
<div class="max-w-md w-full"> | ||
<header class="bg-blue-600 text-white p-4 sticky top-0"> | ||
<h1 class="text-2xl font-bold">항해플러스</h1> | ||
</header> | ||
import { router } from "./lib/router.js"; | ||
|
||
<nav class="bg-white shadow-md p-2 sticky top-14"> | ||
<ul class="flex justify-around"> | ||
<li><a href="/" class="text-blue-600">홈</a></li> | ||
<li><a href="/profile" class="text-gray-600">프로필</a></li> | ||
<li><a href="#" class="text-gray-600">로그아웃</a></li> | ||
</ul> | ||
</nav> | ||
|
||
<main class="p-4"> | ||
<div class="mb-4 bg-white rounded-lg shadow p-4"> | ||
<textarea class="w-full p-2 border rounded" placeholder="무슨 생각을 하고 계신가요?"></textarea> | ||
<button class="mt-2 bg-blue-600 text-white px-4 py-2 rounded">게시</button> | ||
</div> | ||
|
||
<div class="space-y-4"> | ||
|
||
<div class="bg-white rounded-lg shadow p-4"> | ||
<div class="flex items-center mb-2"> | ||
<img src="https://via.placeholder.com/40" alt="프로필" class="rounded-full mr-2"> | ||
<div> | ||
<p class="font-bold">홍길동</p> | ||
<p class="text-sm text-gray-500">5분 전</p> | ||
</div> | ||
</div> | ||
<p>오늘 날씨가 정말 좋네요. 다들 좋은 하루 보내세요!</p> | ||
<div class="mt-2 flex justify-between text-gray-500"> | ||
<button>좋아요</button> | ||
<button>댓글</button> | ||
<button>공유</button> | ||
</div> | ||
</div> | ||
|
||
<div class="bg-white rounded-lg shadow p-4"> | ||
<div class="flex items-center mb-2"> | ||
<img src="https://via.placeholder.com/40" alt="프로필" class="rounded-full mr-2"> | ||
<div> | ||
<p class="font-bold">김철수</p> | ||
<p class="text-sm text-gray-500">15분 전</p> | ||
</div> | ||
</div> | ||
<p>새로운 프로젝트를 시작했어요. 열심히 코딩 중입니다!</p> | ||
<div class="mt-2 flex justify-between text-gray-500"> | ||
<button>좋아요</button> | ||
<button>댓글</button> | ||
<button>공유</button> | ||
</div> | ||
</div> | ||
|
||
<div class="bg-white rounded-lg shadow p-4"> | ||
<div class="flex items-center mb-2"> | ||
<img src="https://via.placeholder.com/40" alt="프로필" class="rounded-full mr-2"> | ||
<div> | ||
<p class="font-bold">이영희</p> | ||
<p class="text-sm text-gray-500">30분 전</p> | ||
</div> | ||
</div> | ||
<p>오늘 점심 메뉴 추천 받습니다. 뭐가 좋을까요?</p> | ||
<div class="mt-2 flex justify-between text-gray-500"> | ||
<button>좋아요</button> | ||
<button>댓글</button> | ||
<button>공유</button> | ||
</div> | ||
</div> | ||
|
||
<div class="bg-white rounded-lg shadow p-4"> | ||
<div class="flex items-center mb-2"> | ||
<img src="https://via.placeholder.com/40" alt="프로필" class="rounded-full mr-2"> | ||
<div> | ||
<p class="font-bold">박민수</p> | ||
<p class="text-sm text-gray-500">1시간 전</p> | ||
</div> | ||
</div> | ||
<p>주말에 등산 가실 분 계신가요? 함께 가요!</p> | ||
<div class="mt-2 flex justify-between text-gray-500"> | ||
<button>좋아요</button> | ||
<button>댓글</button> | ||
<button>공유</button> | ||
</div> | ||
</div> | ||
|
||
<div class="bg-white rounded-lg shadow p-4"> | ||
<div class="flex items-center mb-2"> | ||
<img src="https://via.placeholder.com/40" alt="프로필" class="rounded-full mr-2"> | ||
<div> | ||
<p class="font-bold">정수연</p> | ||
<p class="text-sm text-gray-500">2시간 전</p> | ||
</div> | ||
</div> | ||
<p>새로 나온 영화 재미있대요. 같이 보러 갈 사람?</p> | ||
<div class="mt-2 flex justify-between text-gray-500"> | ||
<button>좋아요</button> | ||
<button>댓글</button> | ||
<button>공유</button> | ||
</div> | ||
</div> | ||
</div> | ||
</main> | ||
|
||
<footer class="bg-gray-200 p-4 text-center"> | ||
<p>© 2024 항해플러스. All rights reserved.</p> | ||
</footer> | ||
</div> | ||
</div> | ||
`; | ||
|
||
const ErrorPage = () => ` | ||
<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 text-center" style="max-width: 480px"> | ||
<h1 class="text-2xl font-bold text-blue-600 mb-4">항해플러스</h1> | ||
<p class="text-4xl font-bold text-gray-800 mb-4">404</p> | ||
<p class="text-xl text-gray-600 mb-8">페이지를 찾을 수 없습니다</p> | ||
<p class="text-gray-600 mb-8"> | ||
요청하신 페이지가 존재하지 않거나 이동되었을 수 있습니다. | ||
</p> | ||
<a href="/" class="bg-blue-600 text-white px-4 py-2 rounded font-bold"> | ||
홈으로 돌아가기 | ||
</a> | ||
</div> | ||
</main> | ||
`; | ||
|
||
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> | ||
<div class="mb-4"> | ||
<input type="text" placeholder="이메일 또는 전화번호" class="w-full p-2 border rounded"> | ||
</div> | ||
<div class="mb-6"> | ||
<input type="password" placeholder="비밀번호" 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> | ||
<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> | ||
`; | ||
|
||
const ProfilePage = () => ` | ||
<div id="root"> | ||
<div class="bg-gray-100 min-h-screen flex justify-center"> | ||
<div class="max-w-md w-full"> | ||
<header class="bg-blue-600 text-white p-4 sticky top-0"> | ||
<h1 class="text-2xl font-bold">항해플러스</h1> | ||
</header> | ||
|
||
<nav class="bg-white shadow-md p-2 sticky top-14"> | ||
<ul class="flex justify-around"> | ||
<li><a href="/" class="text-gray-600">홈</a></li> | ||
<li><a href="/profile" class="text-blue-600">프로필</a></li> | ||
<li><a href="#" class="text-gray-600">로그아웃</a></li> | ||
</ul> | ||
</nav> | ||
|
||
<main class="p-4"> | ||
<div class="bg-white p-8 rounded-lg shadow-md"> | ||
<h2 class="text-2xl font-bold text-center text-blue-600 mb-8"> | ||
내 프로필 | ||
</h2> | ||
<form> | ||
<div class="mb-4"> | ||
<label | ||
for="username" | ||
class="block text-gray-700 text-sm font-bold mb-2" | ||
>사용자 이름</label | ||
> | ||
<input | ||
type="text" | ||
id="username" | ||
name="username" | ||
value="홍길동" | ||
class="w-full p-2 border rounded" | ||
/> | ||
</div> | ||
<div class="mb-4"> | ||
<label | ||
for="email" | ||
class="block text-gray-700 text-sm font-bold mb-2" | ||
>이메일</label | ||
> | ||
<input | ||
type="email" | ||
id="email" | ||
name="email" | ||
value="[email protected]" | ||
class="w-full p-2 border rounded" | ||
/> | ||
</div> | ||
<div class="mb-6"> | ||
<label | ||
for="bio" | ||
class="block text-gray-700 text-sm font-bold mb-2" | ||
>자기소개</label | ||
> | ||
<textarea | ||
id="bio" | ||
name="bio" | ||
rows="4" | ||
class="w-full p-2 border rounded" | ||
> | ||
안녕하세요, 항해플러스에서 열심히 공부하고 있는 홍길동입니다.</textarea | ||
> | ||
</div> | ||
<button | ||
type="submit" | ||
class="w-full bg-blue-600 text-white p-2 rounded font-bold" | ||
> | ||
프로필 업데이트 | ||
</button> | ||
</form> | ||
</div> | ||
</main> | ||
|
||
<footer class="bg-gray-200 p-4 text-center"> | ||
<p>© 2024 항해플러스. All rights reserved.</p> | ||
</footer> | ||
</div> | ||
</div> | ||
</div> | ||
`; | ||
|
||
document.body.innerHTML = ` | ||
${MainPage()} | ||
${ProfilePage()} | ||
${LoginPage()} | ||
${ErrorPage()} | ||
`; | ||
document.addEventListener("DOMContentLoaded", () => { | ||
router.init("root"); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
export const ErrorPage = () => ` | ||
<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 text-center" style="max-width: 480px"> | ||
<h1 class="text-2xl font-bold text-blue-600 mb-4">항해플러스</h1> | ||
<p class="text-4xl font-bold text-gray-800 mb-4">404</p> | ||
<p class="text-xl text-gray-600 mb-8">페이지를 찾을 수 없습니다</p> | ||
<p class="text-gray-600 mb-8"> | ||
요청하신 페이지가 존재하지 않거나 이동되었을 수 있습니다. | ||
</p> | ||
<a href="/" class="bg-blue-600 text-white px-4 py-2 rounded font-bold"> | ||
홈으로 돌아가기 | ||
</a> | ||
</div> | ||
</main> | ||
`; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
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> | ||
<div class="mb-4"> | ||
<input type="text" placeholder="이메일 또는 전화번호" class="w-full p-2 border rounded"> | ||
</div> | ||
<div class="mb-6"> | ||
<input type="password" placeholder="비밀번호" 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> | ||
<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> | ||
`; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
혜연님 안녕하세요 14팀 이주영이에요.
혹시 matches("data-link")라고 하신 이유가 따로 있을까요? 그냥 처음 보는 형태라 궁금해서 여쭤봐요
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@CodyMan0
주영님 안녕하세요! 코드 관련 질문 주셔서 감사합니다.
HTML5 커스텀 속성
HTML5에서는 data-* 접두사를 사용하여 커스텀 속성(Custom Data Attribute)을 만들 수 있습니다.
저는 data-* 뒤에 link를 붙여 SPA 라우팅 처리를 위한 일종의 마커를 만들었습니다.
data-link 속성을 가진 링크는 SPA 라우팅으로 처리
모든 링크에 이벤트 리스너를 다는 대신, SPA 라우팅으로 처리해야 하는 링크에만 적용하기 위해 data-link 마커를 이용했습니다.
파일 다운로드나 외부 링크 이동 등의 동작이 필요할 경우 a 태그는 SPA 라우팅의 적용을 받으면 안 되기 때문입니다.
물론 저희 프로젝트는 모든 a 태그에 SPA 라우팅을 적용해야 합니다. 따라서 어떻게 보면 불필요한 기능이라고도 할 수 있지만,
프로젝트를 진행하며 알아낸 지식을 사용해 보고 싶어 일부러 적용해 본 것입니다 ㅎㅎ
결론 : SPA 라우팅이 적용되어야 하는 a 태그와 브라우저 기본 동작이 실행되어야 하는 a 태그를 구분하기 위해 마커 추가.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
크으~~ 노하우 감사합니다! 이해했습니다 감사합니다 :)