diff --git a/week8/m1/.gitignore b/week8/m1/.gitignore new file mode 100644 index 00000000..92ef6c1d --- /dev/null +++ b/week8/m1/.gitignore @@ -0,0 +1,36 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local +package-lock.json +yarn.lock +pnpm-lock.yaml +lerna-lock.json +tsconfig.app.json +tsconfig.jason +tsconfig.node.json +package.json + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? +/package.json +/pnpm-lock.yaml + +.env \ No newline at end of file diff --git a/week8/m1/README.md b/week8/m1/README.md new file mode 100644 index 00000000..7dbf7ebf --- /dev/null +++ b/week8/m1/README.md @@ -0,0 +1,73 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs) +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) + +## React Compiler + +The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: + +```js +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + + // Remove tseslint.configs.recommended and replace with this + tseslint.configs.recommendedTypeChecked, + // Alternatively, use this for stricter rules + tseslint.configs.strictTypeChecked, + // Optionally, add this for stylistic rules + tseslint.configs.stylisticTypeChecked, + + // Other configs... + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` + +You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: + +```js +// eslint.config.js +import reactX from 'eslint-plugin-react-x' +import reactDom from 'eslint-plugin-react-dom' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + // Enable lint rules for React + reactX.configs['recommended-typescript'], + // Enable lint rules for React DOM + reactDom.configs.recommended, + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` diff --git a/week8/m1/eslint.config.js b/week8/m1/eslint.config.js new file mode 100644 index 00000000..ef614d25 --- /dev/null +++ b/week8/m1/eslint.config.js @@ -0,0 +1,22 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + globals: globals.browser, + }, + }, +]) diff --git a/week8/m1/index.html b/week8/m1/index.html new file mode 100644 index 00000000..2e9d48ac --- /dev/null +++ b/week8/m1/index.html @@ -0,0 +1,13 @@ + + + + + + + m1 + + +
+ + + diff --git a/week8/m1/public/favicon.svg b/week8/m1/public/favicon.svg new file mode 100644 index 00000000..6893eb13 --- /dev/null +++ b/week8/m1/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/week8/m1/public/icons.svg b/week8/m1/public/icons.svg new file mode 100644 index 00000000..e9522193 --- /dev/null +++ b/week8/m1/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/week8/m1/src/App.css b/week8/m1/src/App.css new file mode 100644 index 00000000..e69de29b diff --git a/week8/m1/src/App.tsx b/week8/m1/src/App.tsx new file mode 100644 index 00000000..47ca9c76 --- /dev/null +++ b/week8/m1/src/App.tsx @@ -0,0 +1,64 @@ +import './App.css' +import { createBrowserRouter, RouterProvider, type RouteObject } from 'react-router-dom' +import Home from './pages/Home' +import NotFoundErr from './pages/NotFoundErr' +import Login from './pages/Login' +import HomeLayout from './layouts/HomeLayout' +import SignUp from './pages/SignUp' +import MyPage from './pages/Mypage' +import { AuthProvider } from './context/AuthContext' +import PrivateLayout from './layouts/PrivateLayout' +import GoogleLoginRedirect from './pages/GoogleLoginRedirect' +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; +import LpDetailPage from './pages/LpDetail' + +const publicRoutes:RouteObject[] = [ + { + path: "/", + element: , + errorElement: , + children: [ + {index: true, element: }, + {path: 'login', element: }, + {path: 'signup', element: }, + {path: '/v1/auth/google/callback', element: }, //추가 + {path: 'lp/:lpId', element: }, //추가 + {path: '/v1/auth/google/callback', element: }, //구글 로그인 리다이렉트 페이지 추가 + ] + }, +]; + +const privateRoutes:RouteObject[] = [ + { + path: "/", + element: , + errorElement: , + children: [ + {path: 'my', element: }, + ], + }, +]; + +export const queryClient = new QueryClient(); + +function App() { + const router = createBrowserRouter([ + ...publicRoutes, + ...privateRoutes, + ]); + + return ( + <> + + + + + + + + + ) +} + +export default App diff --git a/week8/m1/src/apis/auth.ts b/week8/m1/src/apis/auth.ts new file mode 100644 index 00000000..4afc96aa --- /dev/null +++ b/week8/m1/src/apis/auth.ts @@ -0,0 +1,68 @@ +import axios from "axios"; +import type { ReqSignInDto, + ReqSignUpDto, + ResMyInfoDto, + ResSignInDto, + ResSignUpDto, + ReqUpdateMyInfoDto } from "../types/auth"; +import { useLocalStorage } from "../hooks/useLocalStorage"; +import { LOCAL_STORAGE_KEY } from "../constants/key"; + + +const getAuthHeader = () => { + try { + const token = JSON.parse( + localStorage.getItem(LOCAL_STORAGE_KEY.ACCESS_TOKEN) ?? "null" + ); + return token ? { Authorization: `Bearer ${token}` } : {}; + } catch { + return {}; + } +}; + +export const postSignup = async (body: ReqSignUpDto):Promise => { + const { data } = await axios.post(`${import.meta.env.VITE_SERVER_API_URL}/v1/auth/signup`, body); + return data; +} + +export const postSignin = async (body: ReqSignInDto):Promise => { + const { data } = await axios.post(`${import.meta.env.VITE_SERVER_API_URL}/v1/auth/signin`, body); + return data; +} + +export const getMyInfo = async ():Promise => { + const { getItem } = useLocalStorage(LOCAL_STORAGE_KEY.ACCESS_TOKEN); + const { data } = await axios.get(`${import.meta.env.VITE_SERVER_API_URL}/v1/users/me`, { + headers: { + Authorization: `Bearer ${getItem()}`, + } + }); + return data; +} +// 로그아웃 API +export const postLogout = async () => { + const { data } = await axios.post( + `${import.meta.env.VITE_SERVER_API_URL}/v1/auth/signout`, + {}, + { headers: getAuthHeader() } + ); + return data; +}; + +// 내 정보 수정 API +export const patchMyInfo = async ( + body: ReqUpdateMyInfoDto +): Promise => { + const { data } = await axios.patch( + `${import.meta.env.VITE_SERVER_API_URL}/v1/users`, + body, + { headers: getAuthHeader() } + ); + return data; +}; + +export const deleteAccount = async () => { + await axios.delete(`${import.meta.env.VITE_SERVER_API_URL}/v1/users`, { + headers: getAuthHeader(), + }); +}; \ No newline at end of file diff --git a/week8/m1/src/apis/lp.ts b/week8/m1/src/apis/lp.ts new file mode 100644 index 00000000..40001ccd --- /dev/null +++ b/week8/m1/src/apis/lp.ts @@ -0,0 +1,126 @@ +import axios from "axios" +import type { PaginationDto } from "../types/common" +import type { ResponseLpListDto, ReqCreateLpDto } from "../types/lp"; +import { LOCAL_STORAGE_KEY } from "../constants/key"; + +const getAuthHeader = () => { + try { + const token = JSON.parse( + localStorage.getItem(LOCAL_STORAGE_KEY.ACCESS_TOKEN) ?? "null" + ); + return token ? { Authorization: `Bearer ${token}` } : {}; + } catch { + return {}; + } +}; + +export const getLpList = async (paginationDto: PaginationDto): Promise => { + const { data } = await axios.get(`${import.meta.env.VITE_SERVER_API_URL}/v1/lps`, { + params: paginationDto, + }); + + return data; +}; // LP 목록 조회 API + +export const postLp = async (body: ReqCreateLpDto) => { + const { data } = await axios.post( + `${import.meta.env.VITE_SERVER_API_URL}/v1/lps`, + body, + { headers: getAuthHeader() } + ); + return data; +}; // LP 생성 API 추가 + +export const updateLp = async ({ + lpId, + body, +}: { + lpId: number; + body: Partial; +}) => { + const { data } = await axios.patch( + `${import.meta.env.VITE_SERVER_API_URL}/v1/lps/${lpId}`, + body, + { headers: getAuthHeader() } + ); + return data; +}; // LP 수정 API 추가 + +export const deleteLpApi = async (lpId: number) => { + await axios.delete( + `${import.meta.env.VITE_SERVER_API_URL}/v1/lps/${lpId}`, + { headers: getAuthHeader() } + ); +};// LP 삭제 API 추가 + +export const toggleLike = async (lpId: number) => { + const { data } = await axios.post( + `${import.meta.env.VITE_SERVER_API_URL}/v1/lps/${lpId}/likes`, + {}, + { headers: getAuthHeader() } + ); + return data; +}; // LP 좋아요 토글 API 추가 + +export const postComment = async ({ + lpId, + content, +}: { + lpId: number; + content: string; +}) => { + const { data } = await axios.post( + `${import.meta.env.VITE_SERVER_API_URL}/v1/lps/${lpId}/comments`, + { content }, + { headers: getAuthHeader() } + ); + return data; +}; // 댓글 작성 API 추가 + +export const updateComment = async ({ + lpId, + commentId, + content, +}: { + lpId: number; + commentId: number; + content: string; +}) => { + const { data } = await axios.patch( + `${import.meta.env.VITE_SERVER_API_URL}/v1/lps/${lpId}/comments/${commentId}`, + { content }, + { headers: getAuthHeader() } + ); + return data; +}; // 댓글 수정 API 추가 + +export const deleteComment = async ({ + lpId, + commentId, +}: { + lpId: number; + commentId: number; +}) => { + await axios.delete( + `${import.meta.env.VITE_SERVER_API_URL}/v1/lps/${lpId}/comments/${commentId}`, + { headers: getAuthHeader() } + ); +}; // 댓글 삭제 API 추가 + +export const uploadImage = async (file: File) => { + const formData = new FormData(); + formData.append("file", file); + + const { data } = await axios.post( + `${import.meta.env.VITE_SERVER_API_URL}/v1/uploads`, + formData, + { + headers: { + ...getAuthHeader(), + "Content-Type": "multipart/form-data", + }, + } + ); + + return data.data.imageUrl; +}; // 이미지 업로드 API 추가 \ No newline at end of file diff --git a/week8/m1/src/assets/hero.png b/week8/m1/src/assets/hero.png new file mode 100644 index 00000000..02251f4b Binary files /dev/null and b/week8/m1/src/assets/hero.png differ diff --git a/week8/m1/src/assets/react.svg b/week8/m1/src/assets/react.svg new file mode 100644 index 00000000..6c87de9b --- /dev/null +++ b/week8/m1/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/week8/m1/src/assets/vite.svg b/week8/m1/src/assets/vite.svg new file mode 100644 index 00000000..5101b674 --- /dev/null +++ b/week8/m1/src/assets/vite.svg @@ -0,0 +1 @@ +Vite diff --git a/week8/m1/src/components/Footer.tsx b/week8/m1/src/components/Footer.tsx new file mode 100644 index 00000000..5468da44 --- /dev/null +++ b/week8/m1/src/components/Footer.tsx @@ -0,0 +1,21 @@ +import { Link } from "react-router-dom" + +const Footer = () => { + return ( +
+
+

+ © {new Date().getFullYear()} 돌려돌려LP판 All rights reserved. +

+
+ Privacy Policy + Terms of Service + Contact +
+
+
+ ) +} + +export default Footer +// Footer 컴포넌트는 사이트의 하단에 위치하는 공통 요소로, 저작권 정보와 함께 개인정보 처리방침, 이용약관, 연락처 등의 링크를 포함합니다. 디자인은 간단하면서도 깔끔하게 유지하여 사용자에게 필요한 정보를 제공하는 역할을 합니다. \ No newline at end of file diff --git a/week8/m1/src/components/HamburgerButton.tsx b/week8/m1/src/components/HamburgerButton.tsx new file mode 100644 index 00000000..7d8de971 --- /dev/null +++ b/week8/m1/src/components/HamburgerButton.tsx @@ -0,0 +1,33 @@ +interface HamburgerButtonProps { + isOpen: boolean; + onClick: () => void; +} + +export default function HamburgerButton({ isOpen, onClick }: HamburgerButtonProps) { + return ( + + ); +} diff --git a/week8/m1/src/components/Sidebar.tsx b/week8/m1/src/components/Sidebar.tsx new file mode 100644 index 00000000..466f5f98 --- /dev/null +++ b/week8/m1/src/components/Sidebar.tsx @@ -0,0 +1,211 @@ +import { useRef, useEffect, useState } from "react"; +import { useNavigate, useLocation } from "react-router-dom"; +import { useMutation } from "@tanstack/react-query"; +import { useAuth } from "../context/AuthContext"; + +type ActiveNav = "search" | "mypage"; + +const COLORS = { + bg: "#F4FFFC", + soft: "#E9FFFC", + main: "#0ECFD3", + dark: "#0BAEB3", + text: "#063B3D", + border: "#B8F3EE", + muted: "#5B8C8E", + faint: "#7AA6A8", +}; + +const NAV_ITEMS: { key: ActiveNav; icon: string; label: string; path: string }[] = [ + { key: "search", icon: "🔍", label: "찾기", path: "/" }, + { key: "mypage", icon: "👤", label: "마이페이지", path: "/my" }, +]; + +interface SidebarProps { + isOpen: boolean; + onClose: () => void; +} + +export default function Sidebar({ isOpen, onClose }: SidebarProps) { + const navigate = useNavigate(); + const location = useLocation(); + const sidebarRef = useRef(null); + const { deleteAccount } = useAuth(); + + const [showWithdrawModal, setShowWithdrawModal] = useState(false); + + const activeKey: ActiveNav = + location.pathname.startsWith("/my") ? "mypage" : "search"; + + useEffect(() => { + const handler = (e: MouseEvent) => { + if (isOpen && sidebarRef.current && !sidebarRef.current.contains(e.target as Node)) { + onClose(); + } + }; + + document.addEventListener("mousedown", handler); + return () => document.removeEventListener("mousedown", handler); + }, [isOpen, onClose]); + + const withdrawMutation = useMutation({ + mutationFn: deleteAccount, + onSuccess: () => { + onClose(); + navigate("/login"); + }, + }); + + return ( + <> +
+ + + + {showWithdrawModal && ( +
+
+
+ ⚠️ +

+ 정말 탈퇴하시겠습니까? +

+

+ 탈퇴 시 모든 데이터가 삭제되며 복구할 수 없습니다. +

+
+ + {withdrawMutation.isError && ( +

+ 탈퇴 처리 중 오류가 발생했습니다. +

+ )} + +
+ + + +
+
+
+ )} + + ); +} \ No newline at end of file diff --git a/week8/m1/src/constants/key.ts b/week8/m1/src/constants/key.ts new file mode 100644 index 00000000..36f080f2 --- /dev/null +++ b/week8/m1/src/constants/key.ts @@ -0,0 +1,18 @@ +export const LOCAL_STORAGE_KEY = { + 'ACCESS_TOKEN': 'accessToken', + 'REFRESH_TOKEN': 'refreshToken', + 'USER_ID': 'userId', +} + +export const QUERY_KEY = { + lps: 'lps', +} + +export const NAV_ITEMS = [ + { icon: "💿", label: "전체 LP" }, + { icon: "⭐", label: "즐겨찾기" }, + { icon: "🕒", label: "최근 재생" }, + { icon: "🎸", label: "장르별" }, + { icon: "📅", label: "연도별" }, + { icon: "🔍", label: "찾기" }, +]; \ No newline at end of file diff --git a/week8/m1/src/context/AuthContext.tsx b/week8/m1/src/context/AuthContext.tsx new file mode 100644 index 00000000..2b7290dc --- /dev/null +++ b/week8/m1/src/context/AuthContext.tsx @@ -0,0 +1,112 @@ +import { postSignin } from "../apis/auth"; +import { LOCAL_STORAGE_KEY } from "../constants/key"; +import { useLocalStorage } from "../hooks/useLocalStorage"; +import { type ReqSignInDto } from "../types/auth"; +import { postLogout, deleteAccount as deleteAccountApi } from "../apis/auth"; +import { createContext, useState, useContext, type PropsWithChildren } from "react"; + +interface AuthContextType { + isAuthenticated: boolean; + accessToken: string | null; + refreshToken: string | null; + userId: number | null; + login: (signInData: ReqSignInDto) => Promise; + logout: () => Promise; + deleteAccount: () => Promise; +} + +export const AuthContext = createContext({ + isAuthenticated: false, + accessToken: null, + refreshToken: null, + userId: null, + login: async () => {}, + logout: async () => {}, + deleteAccount: async () => {}, +}); + +export const AuthProvider = ({ children }: PropsWithChildren) => { + const { + getItem: getAccessTokenInStorage, + setItem: setAccessTokenInStorage, + removeItem: removeAccessTokenInStorage, + } = useLocalStorage(LOCAL_STORAGE_KEY.ACCESS_TOKEN); + const { + getItem: getRefreshTokenInStorage, + setItem: setRefreshTokenInStorage, + removeItem: removeRefreshTokenInStorage, + } = useLocalStorage(LOCAL_STORAGE_KEY.REFRESH_TOKEN); + const { + getItem: getUserIdFromStorage, + setItem: setUserIdInStorage, + removeItem: removeUserIdInStorage, + } = useLocalStorage(LOCAL_STORAGE_KEY.USER_ID); + + const [accessToken, setAccessToken] = useState( + getAccessTokenInStorage() + ); + const [refreshToken, setRefreshToken] = useState( + getRefreshTokenInStorage() + ); + const [userId, setUserId] = useState( + getUserIdFromStorage() + ); + + const login = async (signInData: ReqSignInDto) => { + const { data } = await postSignin(signInData); + + if (data) { + setAccessTokenInStorage(data.accessToken); + setRefreshTokenInStorage(data.refreshToken); + setUserIdInStorage(data.id); + + setAccessToken(data.accessToken); + setRefreshToken(data.refreshToken); + setUserId(data.id); + } + }; + + const logout = async () => { + try { + await postLogout(); + } catch (err) { + console.error("Logout API failed:", err); + } finally { + removeAccessTokenInStorage(); + removeRefreshTokenInStorage(); + removeUserIdInStorage(); + + setAccessToken(null); + setRefreshToken(null); + setUserId(null); + } + }; + + const deleteAccount = async () => { + await deleteAccountApi(); + removeAccessTokenInStorage(); + removeRefreshTokenInStorage(); + removeUserIdInStorage(); + + setAccessToken(null); + setRefreshToken(null); + setUserId(null); + }; + + return ( + + {children} + + ); + +}; + +export const useAuth = () => { + const context = useContext(AuthContext); + if (!context) { + throw new Error("useAuth must be used within an AuthProvider"); + } + return context; +}; \ No newline at end of file diff --git a/week8/m1/src/hooks/queries/useGetLpList.ts b/week8/m1/src/hooks/queries/useGetLpList.ts new file mode 100644 index 00000000..6339a912 --- /dev/null +++ b/week8/m1/src/hooks/queries/useGetLpList.ts @@ -0,0 +1,25 @@ +import { useQuery } from "@tanstack/react-query"; +import type { PaginationDto } from "../../types/common"; +import { getLpList } from "../../apis/lp"; +import { QUERY_KEY } from "../../constants/key"; + +function useGetLpList({cursor, search, order, limit}: PaginationDto) { + return useQuery({ + queryKey:[QUERY_KEY.lps], + queryFn: () => getLpList({ + cursor, + search, + order, + limit + }), + // 데이터가 신선하다고 간주하는 시간 ~ 해당 시간 동안에는 캐시된 데이터를 그대로 사용 + staleTime: 1000 * 60 * 5, // ms단위이기 때문에 해당 시간은 5분 의미 + // 사용되지 않는 상태인 쿼리 데이터가 캐시에 남아있는 시간 + // staleTime이 지나고 데이터가 신선하지 않더라도 일정 시간 동안 메모리에 보관 + gcTime: 1000 * 60 * 10, // 10분 + // 조건에 따라 쿼리 실행 여부 제어 + enabled: true + }); +} + +export default useGetLpList; \ No newline at end of file diff --git a/week8/m1/src/hooks/useDebounce.ts b/week8/m1/src/hooks/useDebounce.ts new file mode 100644 index 00000000..928387ca --- /dev/null +++ b/week8/m1/src/hooks/useDebounce.ts @@ -0,0 +1,17 @@ +import { useEffect, useState } from "react"; + +export function useDebounce(value: T, delay: number): T { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const timer = window.setTimeout(() => { + setDebouncedValue(value); + }, delay); + + return () => { + window.clearTimeout(timer); + }; + }, [value, delay]); + + return debouncedValue; +} diff --git a/week8/m1/src/hooks/useForm.ts b/week8/m1/src/hooks/useForm.ts new file mode 100644 index 00000000..52a652c2 --- /dev/null +++ b/week8/m1/src/hooks/useForm.ts @@ -0,0 +1,72 @@ +/* +useForm +→ input 값 관리 + 에러 검증 도와주는 훅 +*/ + +import { useEffect, useState, type ChangeEvent } from "react"; + +/* +useState → 입력값, 에러, touched 상태 저장 +useEffect → 입력값이 바뀔 때마다 검증 실행 +ChangeEvent → input 변경 이벤트 타입 +*/ + +interface UseFormProps { + init_val: T; // input들의 초기값 + validate: (values: T) => Record; // 입력값이 맞는지 검사하는 함수 +} + +function useForm({ init_val, validate }: UseFormProps) { + const [values, setValues] = useState(init_val); // 현재 input 값들 저장 + const [touched, setTouched] = useState>({}); + // 사용자가 해당 input을 한 번이라도 건드렸는지 저장 + + const [errors, setErrors] = useState>({}); + // 각 input의 에러 메시지 저장 + + const handleChange = (name: keyof T, text: string) => { + setValues({ + ...values, // 기존 값 유지 + [name]: text, // 바뀐 input만 새 값으로 바꾸기 + }); + }; + // 사용자가 input에 글자를 입력하면 그 input의 값을 values에 저장 + + const handleBlur = (name: keyof T) => { + setTouched({ + ...touched, // 기존 touched 상태 유지 + [name]: true, // 해당 input은 이제 touched 됐다고 표시 + }); + }; + + const getInputProps = (name: keyof T) => { + const value = values[name]; + + const onChange = ( + e: ChangeEvent + ) => { + handleChange(name, e.target.value); + }; + + const onBlur = () => { + handleBlur(name); + }; + + return { value, onChange, onBlur }; + }; + // input 컴포넌트에 getInputProps("username") 이렇게 쓰면 + // 그 input의 value, onChange, onBlur가 자동으로 연결되도록 해주는 함수 + + useEffect(() => { + const newErrors = validate(values); + setErrors(newErrors); + }, [values, validate]); + /* + values가 바뀔 때마다 validate 함수로 에러 검사 + 검사 결과를 errors에 저장 + */ + + return { values, errors, touched, getInputProps }; +} + +export default useForm; \ No newline at end of file diff --git a/week8/m1/src/hooks/useLocalStorage.ts b/week8/m1/src/hooks/useLocalStorage.ts new file mode 100644 index 00000000..a93c3106 --- /dev/null +++ b/week8/m1/src/hooks/useLocalStorage.ts @@ -0,0 +1,42 @@ +/* +useLocalStorage +→ localStorage 저장/조회/삭제 쉽게 해주는 훅 +새로고침해도 남아 있음 +브라우저 꺼도 남아 있음 +로그인 토큰 저장할 때 자주 씀 +*/ + +export const useLocalStorage = (key: string) => { + // key 이름을 받아서 해당하는 localStorage 조작하는 함수들 만들어줌 + + const setItem = (value: unknown) => { + try { + localStorage.setItem(key, JSON.stringify(value)); + // localStorage는 문자열만 저장할 수 있어서 JSON.stringify로 감싸서 저장 + } catch (err) { + console.log(err); + } + }; + + const getItem = () => { + try { + const item = localStorage.getItem(key); + return item ? JSON.parse(item) : null; + // 저장할 때 JSON.stringify로 감싸줬으니까 꺼낼 때는 JSON.parse로 다시 객체로 만들어주기 + } catch (err) { + console.log(err); + return null; + } + }; + + const removeItem = () => { + try { + localStorage.removeItem(key); + } catch (err) { + console.log(err); + } + }; + // localStorage에서 해당 key 삭제 + + return { setItem, getItem, removeItem }; +}; \ No newline at end of file diff --git a/week8/m1/src/hooks/useSidebar.ts b/week8/m1/src/hooks/useSidebar.ts new file mode 100644 index 00000000..0068aab1 --- /dev/null +++ b/week8/m1/src/hooks/useSidebar.ts @@ -0,0 +1,11 @@ +import { useState } from "react"; + +export function useSidebar() { + const [isOpen, setIsOpen] = useState(false); + + const open = () => setIsOpen(true); + const close = () => setIsOpen(false); + const toggle = () => setIsOpen((prev) => !prev); + + return { isOpen, setIsOpen, open, close, toggle }; +} diff --git a/week8/m1/src/hooks/useThrottle.ts b/week8/m1/src/hooks/useThrottle.ts new file mode 100644 index 00000000..2ae0314a --- /dev/null +++ b/week8/m1/src/hooks/useThrottle.ts @@ -0,0 +1,36 @@ +import { useCallback, useRef } from "react"; + +export function useThrottle void>( + callback: T, + delay: number +) { + const lastRunTime = useRef(0); + const timerRef = useRef(null); + + return useCallback( + (...args: Parameters) => { + const now = Date.now(); + const remainingTime = delay - (now - lastRunTime.current); + + if (remainingTime <= 0) { + if (timerRef.current) { + window.clearTimeout(timerRef.current); + timerRef.current = null; + } + + lastRunTime.current = now; + callback(...args); + return; + } + + if (!timerRef.current) { + timerRef.current = window.setTimeout(() => { + lastRunTime.current = Date.now(); + timerRef.current = null; + callback(...args); + }, remainingTime); + } + }, + [callback, delay] + ); +} diff --git a/week8/m1/src/imgs/google.png b/week8/m1/src/imgs/google.png new file mode 100644 index 00000000..9035a67e Binary files /dev/null and b/week8/m1/src/imgs/google.png differ diff --git a/week8/m1/src/index.css b/week8/m1/src/index.css new file mode 100644 index 00000000..a461c505 --- /dev/null +++ b/week8/m1/src/index.css @@ -0,0 +1 @@ +@import "tailwindcss"; \ No newline at end of file diff --git a/week8/m1/src/layouts/HomeLayout.tsx b/week8/m1/src/layouts/HomeLayout.tsx new file mode 100644 index 00000000..79c59c60 --- /dev/null +++ b/week8/m1/src/layouts/HomeLayout.tsx @@ -0,0 +1,102 @@ +import { Outlet, useNavigate } from "react-router-dom"; +import { useAuth } from "../context/AuthContext"; +import { getMyInfo } from "../apis/auth"; +import { useState, useEffect } from "react"; +import type { ResMyInfoDto } from "../types/auth"; +import Footer from "../components/Footer"; +import Sidebar from "../components/Sidebar"; +import { useMutation } from "@tanstack/react-query"; +import { useSidebar } from "../hooks/useSidebar"; +// 로그인 여부에 따라 헤더에 로그인/회원가입 버튼 또는 사용자 이름과 로그아웃 버튼을 보여주는 레이아웃 + +export default function HomeLayout() { + const navigate = useNavigate(); + const { accessToken, logout } = useAuth(); + + const [data, setData] = useState({} as ResMyInfoDto); + const { isOpen: sidebarOpen, setIsOpen: setSidebarOpen } = useSidebar(); + + const logoutMutation = useMutation({ + mutationFn: logout, + onSuccess: () => navigate("/"), + }); + + useEffect(() => { + if (!accessToken) return; + const myData = async () => { + try { + const response = await getMyInfo(); + setData(response); + } catch { + // 토큰 만료 등으로 실패해도 레이아웃 유지 + } + }; + myData(); + }, [accessToken]); + + return ( +
+ + {/* 헤더 */} + + + {/* 사이드바 */} + setSidebarOpen(false)} /> + + {/* 페이지 콘텐츠 */} +
+ +
+ +
+
+ ); +} diff --git a/week8/m1/src/layouts/PrivateLayout.tsx b/week8/m1/src/layouts/PrivateLayout.tsx new file mode 100644 index 00000000..519b919c --- /dev/null +++ b/week8/m1/src/layouts/PrivateLayout.tsx @@ -0,0 +1,56 @@ +import { Outlet, useNavigate, Navigate } from "react-router-dom"; +import { useAuth } from "../context/AuthContext"; +import { getMyInfo } from "../apis/auth"; +import { useState, useEffect } from "react"; +import type { ResMyInfoDto } from "../types/auth"; + +const PrivateLayout = () => { + const navigate = useNavigate(); + const {accessToken, logout} = useAuth(); + + const handleLogout = async () => { + await logout(); + navigate("/"); + } + + const [data, setData] = useState({} as ResMyInfoDto); + + useEffect(() => { + const myData = async () => { + const response = await getMyInfo(); + console.log(response); + setData(response); + } + + myData(); + }, [accessToken]); + + if (!accessToken) { + return ; // 뒤로 가기 했을 때 history에 로그인 페이지가 남지 않도록 replace 옵션 사용 + } + + return ( +
+ +
+ +
+
+ ) +} + +export default PrivateLayout; \ No newline at end of file diff --git a/week8/m1/src/main.tsx b/week8/m1/src/main.tsx new file mode 100644 index 00000000..bef5202a --- /dev/null +++ b/week8/m1/src/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import './index.css' +import App from './App.tsx' + +createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/week8/m1/src/pages/GoogleLoginRedirect.tsx b/week8/m1/src/pages/GoogleLoginRedirect.tsx new file mode 100644 index 00000000..e98d57ef --- /dev/null +++ b/week8/m1/src/pages/GoogleLoginRedirect.tsx @@ -0,0 +1,26 @@ +import { LOCAL_STORAGE_KEY } from "../constants/key"; +import { useLocalStorage } from "../hooks/useLocalStorage"; +import { useEffect } from "react"; + +const GoogleLoginRedirect = () => { + const {setItem: setAccessToken} = useLocalStorage(LOCAL_STORAGE_KEY.ACCESS_TOKEN); + const {setItem: setRefreshToken} = useLocalStorage(LOCAL_STORAGE_KEY.REFRESH_TOKEN); + + useEffect(() => { + const urlParams = new URLSearchParams(window.location.search); + const accessToken = urlParams.get("accessToken"); + const refreshToken = urlParams.get("refreshToken"); + + if (accessToken) { + setAccessToken(accessToken); + setRefreshToken(refreshToken); + window.location.href = "/my"; + } + }, [setAccessToken, setRefreshToken]); + return ( +
+ 구글 로그인 리다이렉트 페이지 +
+ ); +} +export default GoogleLoginRedirect; \ No newline at end of file diff --git a/week8/m1/src/pages/Home.tsx b/week8/m1/src/pages/Home.tsx new file mode 100644 index 00000000..d84ffdce --- /dev/null +++ b/week8/m1/src/pages/Home.tsx @@ -0,0 +1,577 @@ +import { useState, useEffect, useRef, useCallback } from "react"; +import { useNavigate } from "react-router-dom"; +import { useInfiniteQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import axios from "axios"; +import { postLp, uploadImage } from "../apis/lp"; +import type { ReqCreateLpDto } from "../types/lp"; + +interface Tag { id: number; name: string; } +interface Likes { id: number; userId: number; } +interface Lp { + id: number; title: string; content: string; thumbnail: string; + published: boolean; authorId: number; createdAt: Date; updatedAt: Date; + tags: Tag[]; likes: Likes[]; +} + +interface LpPage { + data: Lp[]; + nextCursor: number | null; +} + +type SortOrder = "newest" | "oldest"; + +const fileToBase64 = (file: File): Promise => + new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result as string); + reader.onerror = reject; + reader.readAsDataURL(file); + }); +const fetchLps = async (sort: SortOrder, cursor?: number): Promise => { + const order = sort === "newest" ? "desc" : "asc"; + const params = new URLSearchParams({ order, limit: "20" }); + if (cursor) params.append("cursor", String(cursor)); + + const { data } = await axios.get( + `${import.meta.env.VITE_SERVER_API_URL}/v1/lps?${params}` + ); + + const list: Lp[] = data?.data?.data ?? data?.data ?? data ?? []; + const nextCursor: number | null = data?.data?.nextCursor ?? null; + return { data: list, nextCursor }; +}; + +// ── 스켈레톤 카드 (카드와 동일 크기) ───────────────── +const SkeletonCard = () => ( +
+); + +const GridSkeleton = ({ count = 10 }: { count?: number }) => ( +
+ {Array.from({ length: count }).map((_, i) => )} +
+); + +const GridError = ({ onRetry }: { onRetry: () => void }) => ( +
+ 💿 +

데이터를 불러오지 못했습니다.

+ +
+); + +// ── LP 카드 ──────────────────────────────────────────── +const LpCard = ({ lp, onClick }: { lp: Lp; onClick: () => void }) => { + const [hovered, setHovered] = useState(false); + + return ( +
setHovered(true)} + onMouseLeave={() => setHovered(false)} + onClick={onClick} + > + {lp.thumbnail ? ( + {lp.title} + ) : ( +
+
+
+
+
+ )} + +
+ {!lp.published && hovered && ( + 미발행 + )} + {hovered && ( + + ❤️ {lp.likes.length} + + )} +
+

{lp.title}

+

{lp.content}

+ {lp.tags.length > 0 && ( +
+ {lp.tags.slice(0, 3).map((tag) => ( + + #{tag.name} + + ))} + {lp.tags.length > 3 && ( + + +{lp.tags.length - 3} + + )} +
+ )} +

+ {new Date(lp.createdAt).toLocaleDateString("ko-KR", { year: "numeric", month: "short", day: "numeric" })} +

+
+
+
+ ); +}; +// ── LP 작성 모달 ─────────────────────────────────────── +interface CreateLpModalProps { + onClose: () => void; +} + +const CreateLpModal = ({ onClose }: CreateLpModalProps) => { + const queryClient = useQueryClient(); + + const [title, setTitle] = useState(""); + const [content, setContent] = useState(""); + const [published, setPublished] = useState(true); + const [thumbnailFile, setThumbnailFile] = useState(null); + const [thumbnailPreview, setThumbnailPreview] = useState(""); + const [tagInput, setTagInput] = useState(""); + const [tags, setTags] = useState([]); + + const overlayRef = useRef(null); + + const createMutation = useMutation({ + mutationFn: async (body: ReqCreateLpDto) => postLp(body), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ["lps"] }); + onClose(); + }, + }); + + const handleFileChange = async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + setThumbnailFile(file); + const preview = await fileToBase64(file); + setThumbnailPreview(preview); + }; + + const handleAddTag = () => { + const trimmed = tagInput.trim(); + if (trimmed && !tags.includes(trimmed)) { + setTags((prev) => [...prev, trimmed]); + } + setTagInput(""); + }; + + const handleRemoveTag = (tag: string) => { + setTags((prev) => prev.filter((t) => t !== tag)); + }; + + const handleTagKeyDown = (e: React.KeyboardEvent) => { + if (e.key === "Enter") { + e.preventDefault(); + handleAddTag(); + } + }; + + const handleSubmit = async () => { + if (!title.trim()) return; + + let thumbnail: string | undefined; + + if (thumbnailFile) { + thumbnail = await uploadImage(thumbnailFile); + } + + createMutation.mutate({ + title: title.trim(), + content: content.trim(), + thumbnail, + published, + tags, + }); + }; + + const handleOverlayClick = (e: React.MouseEvent) => { + if (e.target === overlayRef.current) onClose(); + }; + + return ( +
+
+ {/* 헤더 */} +
+

새 LP 추가

+ +
+ + {/* 썸네일 */} +
+ + {thumbnailPreview && ( + 미리보기 + )} + +
+ + {/* 제목 */} +
+ + setTitle(e.target.value)} + placeholder="LP 제목을 입력하세요" + className="w-full rounded-lg border px-3 py-2 text-sm outline-none transition-colors" + style={{ borderColor: "#e0e9f8", color: "#1e738a" }} // 기본 테두리와 텍스트 색상 + onFocus={(e) => ((e.currentTarget as HTMLElement).style.borderColor = "#3bf6f0")} // 포커스 시 테두리 색상 변경 + onBlur={(e) => ((e.currentTarget as HTMLElement).style.borderColor = "#e0e9f8")} + /> +
+ + {/* 내용 */} +
+ +