From 7f4714539ce2b782b46fa7452caeec73035b4064 Mon Sep 17 00:00:00 2001 From: shinisme Date: Mon, 1 Jun 2026 14:57:26 +0900 Subject: [PATCH] =?UTF-8?q?feat:=EC=8A=B9=EA=B5=AC=EB=A6=AC=20w9m1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- week9/m1/.gitignore | 36 ++ week9/m1/README.md | 73 +++ week9/m1/eslint.config.js | 22 + week9/m1/index.html | 13 + week9/m1/public/favicon.svg | 1 + week9/m1/public/icons.svg | 24 + week9/m1/src/App.css | 0 week9/m1/src/App.tsx | 66 ++ week9/m1/src/apis/auth.ts | 68 +++ week9/m1/src/apis/lp.ts | 126 ++++ week9/m1/src/assets/hero.png | Bin 0 -> 13057 bytes week9/m1/src/assets/react.svg | 1 + week9/m1/src/assets/vite.svg | 1 + week9/m1/src/components/CartContainer.tsx | 48 ++ week9/m1/src/components/CartItemCard.tsx | 55 ++ week9/m1/src/components/Footer.tsx | 21 + week9/m1/src/components/HamburgerButton.tsx | 33 + week9/m1/src/components/PlaylistNavbar.tsx | 22 + week9/m1/src/components/Sidebar.tsx | 211 +++++++ week9/m1/src/constants/cartItems.ts | 38 ++ week9/m1/src/constants/key.ts | 18 + week9/m1/src/context/AuthContext.tsx | 112 ++++ week9/m1/src/hooks/queries/useGetLpList.ts | 25 + week9/m1/src/hooks/redux.ts | 5 + week9/m1/src/hooks/useDebounce.ts | 17 + week9/m1/src/hooks/useForm.ts | 72 +++ week9/m1/src/hooks/useLocalStorage.ts | 42 ++ week9/m1/src/hooks/useSidebar.ts | 11 + week9/m1/src/hooks/useThrottle.ts | 36 ++ week9/m1/src/imgs/google.png | Bin 0 -> 2449 bytes week9/m1/src/index.css | 1 + week9/m1/src/layouts/HomeLayout.tsx | 102 ++++ week9/m1/src/layouts/PrivateLayout.tsx | 56 ++ week9/m1/src/main.tsx | 14 + week9/m1/src/pages/CartPage.tsx | 23 + week9/m1/src/pages/GoogleLoginRedirect.tsx | 26 + week9/m1/src/pages/Home.tsx | 577 ++++++++++++++++++ week9/m1/src/pages/Login.tsx | 123 ++++ week9/m1/src/pages/LpDetail.tsx | 632 ++++++++++++++++++++ week9/m1/src/pages/Mypage.tsx | 297 +++++++++ week9/m1/src/pages/NotFoundErr.tsx | 7 + week9/m1/src/pages/SignUp.tsx | 178 ++++++ week9/m1/src/store/cartSlice.ts | 52 ++ week9/m1/src/store/store.ts | 11 + week9/m1/src/types/auth.ts | 53 ++ week9/m1/src/types/cart.ts | 14 + week9/m1/src/types/common.ts | 21 + week9/m1/src/types/lp.ts | 51 ++ week9/m1/src/utils/validate.ts | 27 + week9/m1/tsconfig.json | 7 + week9/m1/vite-env.d.ts | 16 + week9/m1/vite.config.ts | 7 + 52 files changed, 3492 insertions(+) create mode 100644 week9/m1/.gitignore create mode 100644 week9/m1/README.md create mode 100644 week9/m1/eslint.config.js create mode 100644 week9/m1/index.html create mode 100644 week9/m1/public/favicon.svg create mode 100644 week9/m1/public/icons.svg create mode 100644 week9/m1/src/App.css create mode 100644 week9/m1/src/App.tsx create mode 100644 week9/m1/src/apis/auth.ts create mode 100644 week9/m1/src/apis/lp.ts create mode 100644 week9/m1/src/assets/hero.png create mode 100644 week9/m1/src/assets/react.svg create mode 100644 week9/m1/src/assets/vite.svg create mode 100644 week9/m1/src/components/CartContainer.tsx create mode 100644 week9/m1/src/components/CartItemCard.tsx create mode 100644 week9/m1/src/components/Footer.tsx create mode 100644 week9/m1/src/components/HamburgerButton.tsx create mode 100644 week9/m1/src/components/PlaylistNavbar.tsx create mode 100644 week9/m1/src/components/Sidebar.tsx create mode 100644 week9/m1/src/constants/cartItems.ts create mode 100644 week9/m1/src/constants/key.ts create mode 100644 week9/m1/src/context/AuthContext.tsx create mode 100644 week9/m1/src/hooks/queries/useGetLpList.ts create mode 100644 week9/m1/src/hooks/redux.ts create mode 100644 week9/m1/src/hooks/useDebounce.ts create mode 100644 week9/m1/src/hooks/useForm.ts create mode 100644 week9/m1/src/hooks/useLocalStorage.ts create mode 100644 week9/m1/src/hooks/useSidebar.ts create mode 100644 week9/m1/src/hooks/useThrottle.ts create mode 100644 week9/m1/src/imgs/google.png create mode 100644 week9/m1/src/index.css create mode 100644 week9/m1/src/layouts/HomeLayout.tsx create mode 100644 week9/m1/src/layouts/PrivateLayout.tsx create mode 100644 week9/m1/src/main.tsx create mode 100644 week9/m1/src/pages/CartPage.tsx create mode 100644 week9/m1/src/pages/GoogleLoginRedirect.tsx create mode 100644 week9/m1/src/pages/Home.tsx create mode 100644 week9/m1/src/pages/Login.tsx create mode 100644 week9/m1/src/pages/LpDetail.tsx create mode 100644 week9/m1/src/pages/Mypage.tsx create mode 100644 week9/m1/src/pages/NotFoundErr.tsx create mode 100644 week9/m1/src/pages/SignUp.tsx create mode 100644 week9/m1/src/store/cartSlice.ts create mode 100644 week9/m1/src/store/store.ts create mode 100644 week9/m1/src/types/auth.ts create mode 100644 week9/m1/src/types/cart.ts create mode 100644 week9/m1/src/types/common.ts create mode 100644 week9/m1/src/types/lp.ts create mode 100644 week9/m1/src/utils/validate.ts create mode 100644 week9/m1/tsconfig.json create mode 100644 week9/m1/vite-env.d.ts create mode 100644 week9/m1/vite.config.ts diff --git a/week9/m1/.gitignore b/week9/m1/.gitignore new file mode 100644 index 00000000..92ef6c1d --- /dev/null +++ b/week9/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/week9/m1/README.md b/week9/m1/README.md new file mode 100644 index 00000000..7dbf7ebf --- /dev/null +++ b/week9/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/week9/m1/eslint.config.js b/week9/m1/eslint.config.js new file mode 100644 index 00000000..ef614d25 --- /dev/null +++ b/week9/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/week9/m1/index.html b/week9/m1/index.html new file mode 100644 index 00000000..2e9d48ac --- /dev/null +++ b/week9/m1/index.html @@ -0,0 +1,13 @@ + + + + + + + m1 + + +
+ + + diff --git a/week9/m1/public/favicon.svg b/week9/m1/public/favicon.svg new file mode 100644 index 00000000..6893eb13 --- /dev/null +++ b/week9/m1/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/week9/m1/public/icons.svg b/week9/m1/public/icons.svg new file mode 100644 index 00000000..e9522193 --- /dev/null +++ b/week9/m1/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/week9/m1/src/App.css b/week9/m1/src/App.css new file mode 100644 index 00000000..e69de29b diff --git a/week9/m1/src/App.tsx b/week9/m1/src/App.tsx new file mode 100644 index 00000000..a3eb8ba7 --- /dev/null +++ b/week9/m1/src/App.tsx @@ -0,0 +1,66 @@ +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' +import CartPage from './pages/CartPage' + +const publicRoutes:RouteObject[] = [ + { + path: "/", + element: , + errorElement: , + children: [ + {index: true, element: }, + {path: 'home', 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/week9/m1/src/apis/auth.ts b/week9/m1/src/apis/auth.ts new file mode 100644 index 00000000..4afc96aa --- /dev/null +++ b/week9/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/week9/m1/src/apis/lp.ts b/week9/m1/src/apis/lp.ts new file mode 100644 index 00000000..40001ccd --- /dev/null +++ b/week9/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/week9/m1/src/assets/hero.png b/week9/m1/src/assets/hero.png new file mode 100644 index 0000000000000000000000000000000000000000..02251f4b956c55af2d76fd0788124d7eee2b45eb GIT binary patch literal 13057 zcmV+cGycqpP)V|)f$;Qooc7=_G zlYe)HToTQIc!$)^+J1M1y0*T%w!p~7%ux`!eRhO?c80XDxKQ*R^lUUMnA>6NT^?feoZ8xxvP32D&s-9ow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9/m1/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/week9/m1/src/assets/vite.svg b/week9/m1/src/assets/vite.svg new file mode 100644 index 00000000..5101b674 --- /dev/null +++ b/week9/m1/src/assets/vite.svg @@ -0,0 +1 @@ +Vite diff --git a/week9/m1/src/components/CartContainer.tsx b/week9/m1/src/components/CartContainer.tsx new file mode 100644 index 00000000..cf0e37d9 --- /dev/null +++ b/week9/m1/src/components/CartContainer.tsx @@ -0,0 +1,48 @@ +import CartItemCard from './CartItemCard'; +import { clearCart } from '../store/cartSlice'; +import { useAppDispatch, useAppSelector } from '../hooks/redux'; + +const CartContainer = () => { + const dispatch = useAppDispatch(); + const { amount, cartItems, total } = useAppSelector((state) => state.cart); + + if (amount < 1) { + return ( +
+

장바구니

+

장바구니가 비어 있습니다.

+
+ ); + } + + return ( +
+

장바구니

+
    + {cartItems.map((item) => ( + + ))} +
+ +
+
+ + 총 수량 {amount}개 + + + 총 금액 {total.toLocaleString()}원 + +
+ +
+
+ ); +}; + +export default CartContainer; diff --git a/week9/m1/src/components/CartItemCard.tsx b/week9/m1/src/components/CartItemCard.tsx new file mode 100644 index 00000000..7846a767 --- /dev/null +++ b/week9/m1/src/components/CartItemCard.tsx @@ -0,0 +1,55 @@ +import { Minus, Plus } from 'lucide-react'; +import { decrease, increase, removeItem } from '../store/cartSlice'; +import { useAppDispatch } from '../hooks/redux'; +import type { CartItem } from '../types/cart'; + +interface CartItemCardProps { + item: CartItem; +} + +const CartItemCard = ({ item }: CartItemCardProps) => { + const dispatch = useAppDispatch(); + + return ( +
  • + {item.title} + +
    +

    {item.title}

    +

    {item.singer}

    +

    + {item.price.toLocaleString()}원 +

    + +
    + +
    + + {item.amount} + +
    +
  • + ); +}; + +export default CartItemCard; diff --git a/week9/m1/src/components/Footer.tsx b/week9/m1/src/components/Footer.tsx new file mode 100644 index 00000000..5468da44 --- /dev/null +++ b/week9/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/week9/m1/src/components/HamburgerButton.tsx b/week9/m1/src/components/HamburgerButton.tsx new file mode 100644 index 00000000..7d8de971 --- /dev/null +++ b/week9/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/week9/m1/src/components/PlaylistNavbar.tsx b/week9/m1/src/components/PlaylistNavbar.tsx new file mode 100644 index 00000000..2fc109bd --- /dev/null +++ b/week9/m1/src/components/PlaylistNavbar.tsx @@ -0,0 +1,22 @@ +import { ShoppingCart } from 'lucide-react'; +import { useAppSelector } from '../hooks/redux'; + +const PlaylistNavbar = () => { + const amount = useAppSelector((state) => state.cart.amount); + + return ( + + ); +}; + +export default PlaylistNavbar; diff --git a/week9/m1/src/components/Sidebar.tsx b/week9/m1/src/components/Sidebar.tsx new file mode 100644 index 00000000..466f5f98 --- /dev/null +++ b/week9/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/week9/m1/src/constants/cartItems.ts b/week9/m1/src/constants/cartItems.ts new file mode 100644 index 00000000..6aa94cc7 --- /dev/null +++ b/week9/m1/src/constants/cartItems.ts @@ -0,0 +1,38 @@ +import type { CartItem } from '../types/cart'; + +const cartItems: CartItem[] = [ + { + id: 'vancouver', + title: 'Vancouver', + singer: 'BIG Naughty', + price: 25000, + img: 'https://image.bugsm.co.kr/album/images/500/40752/4075248.jpg', + amount: 1, + }, + { + id: 'golden-hour', + title: 'golden hour', + singer: 'JVKE', + price: 28000, + img: 'https://image.bugsm.co.kr/album/images/200/193874/19387484.jpg', + amount: 1, + }, + { + id: 'lemon', + title: 'Lemon', + singer: 'Kenshi Yonezu', + price: 30000, + img: 'https://image.bugsm.co.kr/album/images/200/7222/722272.jpg', + amount: 1, + }, + { + id: 'no-pain', + title: 'NO PAIN', + singer: 'Silica Gel', + price: 22000, + img: 'https://image.bugsm.co.kr/album/images/200/40790/4079061.jpg', + amount: 1, + }, +]; + +export default cartItems; diff --git a/week9/m1/src/constants/key.ts b/week9/m1/src/constants/key.ts new file mode 100644 index 00000000..36f080f2 --- /dev/null +++ b/week9/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/week9/m1/src/context/AuthContext.tsx b/week9/m1/src/context/AuthContext.tsx new file mode 100644 index 00000000..2b7290dc --- /dev/null +++ b/week9/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/week9/m1/src/hooks/queries/useGetLpList.ts b/week9/m1/src/hooks/queries/useGetLpList.ts new file mode 100644 index 00000000..6339a912 --- /dev/null +++ b/week9/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/week9/m1/src/hooks/redux.ts b/week9/m1/src/hooks/redux.ts new file mode 100644 index 00000000..751ffce5 --- /dev/null +++ b/week9/m1/src/hooks/redux.ts @@ -0,0 +1,5 @@ +import { useDispatch, useSelector } from 'react-redux'; +import type { AppDispatch, RootState } from '../store/store'; + +export const useAppDispatch = () => useDispatch(); +export const useAppSelector = useSelector.withTypes(); diff --git a/week9/m1/src/hooks/useDebounce.ts b/week9/m1/src/hooks/useDebounce.ts new file mode 100644 index 00000000..928387ca --- /dev/null +++ b/week9/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/week9/m1/src/hooks/useForm.ts b/week9/m1/src/hooks/useForm.ts new file mode 100644 index 00000000..52a652c2 --- /dev/null +++ b/week9/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/week9/m1/src/hooks/useLocalStorage.ts b/week9/m1/src/hooks/useLocalStorage.ts new file mode 100644 index 00000000..a93c3106 --- /dev/null +++ b/week9/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/week9/m1/src/hooks/useSidebar.ts b/week9/m1/src/hooks/useSidebar.ts new file mode 100644 index 00000000..0068aab1 --- /dev/null +++ b/week9/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/week9/m1/src/hooks/useThrottle.ts b/week9/m1/src/hooks/useThrottle.ts new file mode 100644 index 00000000..2ae0314a --- /dev/null +++ b/week9/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/week9/m1/src/imgs/google.png b/week9/m1/src/imgs/google.png new file mode 100644 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(`l2SlBf5OA*6G# z7~{|+EU0}Vk3nwO)^@3EyT^<^$gngC+fwWicnY!?QtTB5=3Lm;By3R(-ZIcRN;gRb z;rH}hldvsCF=(}U3PKGhPko26CYS&Gh>s8oLf5<4m|-k;uz#}A)&FfnELBuc6bcb^0e=SyIbRsc`#0w~bAhf`ZV;UWzlCWpzSXcF%M9wqx4} zGe=G8eiGFuPHiI=QY)Nch+l2|E6%lzb&3NvH%cN!#rd{D_hj!(+y7GZfwgVWxz_fi zL09p^b)xRlKG?e|`s*1!xo#V~;a8b(6en#X7HX@vE6(jnh+?)4rh7EY;8BwXJrl+U+b=^ei;`by0Hmlnpm&c-2|L;MpkkIw$pES(2pbRA2v7>|XV2 z4Z>gev!&E-G({} 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/week9/m1/src/layouts/PrivateLayout.tsx b/week9/m1/src/layouts/PrivateLayout.tsx new file mode 100644 index 00000000..519b919c --- /dev/null +++ b/week9/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/week9/m1/src/main.tsx b/week9/m1/src/main.tsx new file mode 100644 index 00000000..70c16abe --- /dev/null +++ b/week9/m1/src/main.tsx @@ -0,0 +1,14 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { Provider } from 'react-redux' +import './index.css' +import App from './App.tsx' +import { store } from './store/store.ts' + +createRoot(document.getElementById('root')!).render( + + + + + , +) diff --git a/week9/m1/src/pages/CartPage.tsx b/week9/m1/src/pages/CartPage.tsx new file mode 100644 index 00000000..1fdf2abc --- /dev/null +++ b/week9/m1/src/pages/CartPage.tsx @@ -0,0 +1,23 @@ +import { useEffect } from 'react'; +import CartContainer from '../components/CartContainer'; +import PlaylistNavbar from '../components/PlaylistNavbar'; +import { calculateTotals } from '../store/cartSlice'; +import { useAppDispatch, useAppSelector } from '../hooks/redux'; + +const CartPage = () => { + const dispatch = useAppDispatch(); + const cartItems = useAppSelector((state) => state.cart.cartItems); + + useEffect(() => { + dispatch(calculateTotals()); + }, [cartItems, dispatch]); + + return ( +
    + + +
    + ); +}; + +export default CartPage; diff --git a/week9/m1/src/pages/GoogleLoginRedirect.tsx b/week9/m1/src/pages/GoogleLoginRedirect.tsx new file mode 100644 index 00000000..e98d57ef --- /dev/null +++ b/week9/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/week9/m1/src/pages/Home.tsx b/week9/m1/src/pages/Home.tsx new file mode 100644 index 00000000..d84ffdce --- /dev/null +++ b/week9/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")} + /> +
    + + {/* 내용 */} +
    + +