This commit is contained in:
pwy3282040@msecure.co
2025-12-27 00:17:46 +09:00
commit 87405e897e
34 changed files with 6264 additions and 0 deletions

41
.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

36
README.md Normal file
View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

18
eslint.config.mjs Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

8
next.config.ts Normal file
View File

@@ -0,0 +1,8 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
reactCompiler: true,
};
export default nextConfig;

39
package.json Normal file
View File

@@ -0,0 +1,39 @@
{
"name": "blog-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@headlessui/react": "^2.2.9",
"@heroicons/react": "^2.2.0",
"@tanstack/react-query": "^5.90.12",
"@uiw/react-md-editor": "^4.0.11",
"axios": "^1.13.2",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"lucide-react": "^0.562.0",
"next": "16.1.1",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-hook-form": "^7.69.0",
"react-markdown": "^10.1.0",
"zustand": "^5.0.9"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@tailwindcss/typography": "^0.5.19",
"@types/node": "^25",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0",
"eslint": "^9",
"eslint-config-next": "16.1.1",
"tailwindcss": "^4",
"typescript": "^5"
}
}

7
postcss.config.mjs Normal file
View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

1
public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
public/window.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

21
src/api/auth.ts Normal file
View File

@@ -0,0 +1,21 @@
// src/api/auth.ts
import { http } from './http';
import { ApiResponse, LoginRequest, LoginResponse, SignupRequest, VerifyRequest } from '@/types';
// 1. 회원가입 (이메일 발송)
export const signup = async (data: SignupRequest) => {
const response = await http.post<ApiResponse<null>>('/api/auth/signup', data);
return response.data;
};
// 2. 이메일 인증 코드 확인
export const verifyEmail = async (data: VerifyRequest) => {
const response = await http.post<ApiResponse<null>>('/api/auth/verify', data);
return response.data;
};
// 3. 로그인 (토큰 발급)
export const login = async (data: LoginRequest) => {
const response = await http.post<ApiResponse<LoginResponse>>('/api/auth/login', data);
return response.data;
};

9
src/api/category.ts Normal file
View File

@@ -0,0 +1,9 @@
// src/api/category.ts
import { http } from './http';
import { ApiResponse, Category } from '@/types';
// 카테고리 트리 구조 조회 (GET /api/categories)
export const getCategories = async () => {
const response = await http.get<ApiResponse<Category[]>>('/api/categories');
return response.data.data; // ApiResponse로 감싸져 있으므로 .data.data 반환
};

44
src/api/http.ts Normal file
View File

@@ -0,0 +1,44 @@
import axios from 'axios';
export const http = axios.create({
baseURL: 'http://localhost:8080', // 백엔드 주소 확인
headers: {
'Content-Type': 'application/json',
},
withCredentials: true, // 쿠키 사용 시 필요
});
// 🟢 요청 인터셉터 추가 (범인 검거 현장)
http.interceptors.request.use(
(config) => {
// 1. 로컬 스토리지에서 zustand가 저장한 데이터 꺼내기
const storage = localStorage.getItem('auth-storage');
if (storage) {
// Zustand는 { state: { ... }, version: 0 } 형태로 저장함
const parsedStorage = JSON.parse(storage);
const token = parsedStorage.state?.accessToken;
// 2. 토큰이 있다면 헤더에 심어주기
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 응답 인터셉터 (에러 처리용, 선택 사항)
http.interceptors.response.use(
(response) => response,
(error) => {
if (error.response && error.response.status === 401) {
// 토큰 만료 시 로그아웃 처리 등을 여기서 할 수 있음
console.error('인증 실패: 토큰이 만료되었거나 유효하지 않습니다.');
}
return Promise.reject(error);
}
);

19
src/api/image.ts Normal file
View File

@@ -0,0 +1,19 @@
import { http } from './http';
import { ApiResponse } from '@/types';
// 이미지 업로드 (POST /api/admin/images)
export const uploadImage = async (file: File) => {
const formData = new FormData();
formData.append('image', file);
// 👇 헤더에 Content-Type을 'multipart/form-data'로 명시하거나,
// 아예 지워서(undefined) 브라우저가 알아서 boundary를 붙이게 해야 합니다.
// 가장 안전한 방법은 'Content-Type': 'multipart/form-data'를 명시하는 것입니다.
const response = await http.post<ApiResponse<string>>('/api/admin/images', formData, {
headers: {
'Content-Type': 'multipart/form-data', // 👈 여기! 이거 추가하면 해결됩니다.
},
});
return response.data;
};

36
src/api/posts.ts Normal file
View File

@@ -0,0 +1,36 @@
// src/api/posts.ts
import { http } from './http';
import { ApiResponse, PostListResponse } from '@/types'; // ApiResponse 타입 추가
import { Post } from '@/types';
export const getPosts = async (page = 0, size = 10, categoryId?: number, search?: string) => {
const params: any = { page, size };
if (categoryId) params.categoryId = categoryId;
if (search) params.search = search;
// 1. 응답 타입을 ApiResponse<PostListResponse>로 변경
const response = await http.get<ApiResponse<PostListResponse>>('/api/posts', { params });
// 2. response.data는 { code, message, data: {...} } 형태입니다.
// 우리가 필요한 건 그 안의 data(실제 게시글 목록)이므로 .data를 한번 더 접근합니다.
return response.data.data;
};
export const getPostBySlug = async (slug: string) => {
const response = await http.get<ApiResponse<Post>>(`/api/posts/${slug}`);
return response.data.data;
};
export interface CreatePostRequest {
title: string;
content: string;
categoryId: number;
}
// 게시글 생성
export const createPost = async (data: CreatePostRequest) => {
// 👇 여기를 수정했습니다! (/api/posts -> /api/admin/posts)
const response = await http.post<ApiResponse<any>>('/api/admin/posts', data);
return response.data;
};

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

37
src/app/globals.css Normal file
View File

@@ -0,0 +1,37 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
.w-md-editor {
border-radius: 0.75rem !important; /* 둥근 모서리 */
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
border-color: #e5e7eb !important;
}
.w-md-editor-toolbar {
border-radius: 0.75rem 0.75rem 0 0 !important;
background-color: #f9fafb !important;
}

41
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,41 @@
// src/app/layout.tsx
import type { Metadata } from 'next';
import './globals.css';
import Providers from './providers';
import Sidebar from '@/components/layout/Sidebar';
import TopHeader from '@/components/layout/TopHeader'; // 👈 import 추가
export const metadata: Metadata = {
title: 'Dev Park Blog',
description: '개발 기록 블로그',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ko">
<body className="bg-[#f8f9fa] text-gray-800">
<Providers>
<div className="min-h-screen flex">
{/* 사이드바 */}
<Sidebar />
{/* 메인 영역 */}
<main className="flex-1 transition-all duration-300 md:ml-72 w-full relative"> {/* 👈 relative 확인 */}
{/* 👇 여기에 TopHeader 추가! */}
<TopHeader />
<div className="max-w-4xl mx-auto p-6 md:p-12 pt-20"> {/* 👈 상단 여백(pt-20) 살짝 추가 */}
{children}
</div>
</main>
</div>
</Providers>
</body>
</html>
);
}

89
src/app/login/page.tsx Normal file
View File

@@ -0,0 +1,89 @@
// src/app/login/page.tsx
'use client';
import { useForm } from 'react-hook-form';
import { useRouter } from 'next/navigation';
import { login } from '@/api/auth';
import { useAuthStore } from '@/store/authStore';
import { LoginRequest } from '@/types';
import Link from 'next/link'; // 👈 추가
import { useState } from 'react';
export default function LoginPage() {
const router = useRouter();
const { login: setLoginState } = useAuthStore();
const [loading, setLoading] = useState(false); // 로딩 상태 추가
const { register, handleSubmit, formState: { errors } } = useForm<LoginRequest>();
const onSubmit = async (data: LoginRequest) => {
setLoading(true);
try {
const res = await login(data);
if (res.code === 'SUCCESS' && res.data) {
setLoginState(res.data.accessToken);
// alert('환영합니다! 😎');
router.push('/');
} else {
alert('로그인 실패: ' + res.message);
}
} catch (error: any) {
console.error(error);
alert('로그인 중 오류가 발생했습니다: ' + (error.response?.data?.message || '서버 오류'));
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
<div className="max-w-md w-full bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
<div className="text-center mb-8">
<h1 className="text-2xl font-bold text-gray-900"> 🔐</h1>
<p className="text-sm text-gray-500 mt-2"> </p>
</div>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
{...register('email', { required: '이메일을 입력해주세요.' })}
type="email"
className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition-all"
placeholder="user@example.com"
/>
{errors.email && <p className="text-red-500 text-xs mt-1">{errors.email.message}</p>}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
{...register('password', { required: '비밀번호를 입력해주세요.' })}
type="password"
className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition-all"
placeholder="••••••••"
/>
{errors.password && <p className="text-red-500 text-xs mt-1">{errors.password.message}</p>}
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-lg transition-colors disabled:bg-gray-400"
>
{loading ? '로그인 중...' : '로그인하기'}
</button>
</form>
{/* 회원가입 링크 추가 */}
<div className="mt-6 text-center text-sm text-gray-500">
?{' '}
<Link href="/signup" className="text-blue-600 font-semibold hover:underline">
</Link>
</div>
</div>
</div>
);
}

57
src/app/page.tsx Normal file
View File

@@ -0,0 +1,57 @@
// src/app/page.tsx
'use client'; // 클라이언트 컴포넌트 선언 (React Query 사용 위해)
import { useQuery } from '@tanstack/react-query';
import { getPosts } from '@/api/posts';
import PostCard from '@/components/post/PostCard';
import { Post } from '@/types';
export default function Home() {
// 1. React Query로 데이터 가져오기
const { data, isLoading, isError } = useQuery({
queryKey: ['posts'], // 캐싱 키
queryFn: () => getPosts(0, 10), // 0페이지, 10개 조회
});
// 2. 로딩 중일 때
if (isLoading) {
return (
<div className="max-w-4xl mx-auto p-6 text-center pt-20">
<div className="animate-pulse text-gray-400"> ...</div>
</div>
);
}
// 3. 에러 났을 때
if (isError) {
return (
<div className="max-w-4xl mx-auto p-6 text-center pt-20 text-red-500">
. .
</div>
);
}
// 4. 데이터 렌더링
return (
<main className="max-w-4xl mx-auto p-6 min-h-screen">
<header className="mb-10 mt-10">
<h1 className="text-3xl font-bold text-gray-900"> 🧑💻</h1>
<p className="text-gray-500 mt-2"> .</p>
</header>
{/* 게시글 목록 그리드 */}
<section className="grid gap-6 md:grid-cols-2">
{data?.content.map((post: Post) => (
<PostCard key={post.id} post={post} />
))}
</section>
{/* 게시글이 하나도 없을 때 */}
{data?.content.length === 0 && (
<div className="text-center py-20 text-gray-500 bg-gray-50 rounded-lg">
.
</div>
)}
</main>
);
}

View File

@@ -0,0 +1,89 @@
// src/app/posts/[slug]/page.tsx
'use client';
import { useQuery } from '@tanstack/react-query';
import { getPostBySlug } from '@/api/posts';
import MarkdownRenderer from '@/components/post/MarkdownRenderer';
import { format } from 'date-fns';
import { useParams, useRouter } from 'next/navigation';
import { ArrowLeft, Calendar, User } from 'lucide-react';
export default function PostDetailPage() {
const { slug } = useParams(); // URL에서 slug 가져오기
const router = useRouter();
// 데이터 조회
const { data: post, isLoading, isError } = useQuery({
queryKey: ['post', slug],
queryFn: () => getPostBySlug(slug as string),
enabled: !!slug, // slug가 있을 때만 실행
});
if (isLoading) return <div className="text-center py-20 animate-pulse"> ... </div>;
if (isError || !post) {
return (
<div className="text-center py-20">
<h2 className="text-2xl font-bold mb-4"> . 😭</h2>
<button onClick={() => router.back()} className="text-blue-500 hover:underline">
</button>
</div>
);
}
return (
<article className="max-w-3xl mx-auto pb-20">
{/* 1. 뒤로가기 버튼 */}
<button
onClick={() => router.back()}
className="flex items-center text-gray-500 hover:text-gray-900 mb-8 transition-colors"
>
<ArrowLeft size={20} className="mr-2" />
</button>
{/* 2. 헤더 영역 (카테고리, 제목, 날짜) */}
<header className="mb-10 text-center">
<span className="inline-block bg-blue-100 text-blue-700 text-sm font-semibold px-3 py-1 rounded-full mb-4">
{post.categoryName}
</span>
<h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-6 leading-tight">
{post.title}
</h1>
<div className="flex items-center justify-center gap-6 text-gray-500 text-sm">
<div className="flex items-center gap-2">
<User size={16} />
<span>Dev Park</span>
</div>
<div className="flex items-center gap-2">
<Calendar size={16} />
<time>{format(new Date(post.createdAt), 'yyyy년 MM월 dd일')}</time>
</div>
</div>
</header>
{/* 구분선 */}
<hr className="border-gray-200 my-10" />
{/* 3. 본문 영역 (마크다운) */}
<div className="bg-white p-6 md:p-10 rounded-2xl shadow-sm border border-gray-100 min-h-[300px]">
{/* 본문이 있으면 렌더링, 없으면 안내 문구 */}
{post.content ? (
<MarkdownRenderer content={post.content} />
) : (
<p className="text-gray-400 italic"> .</p>
)}
</div>
{/* 4. 하단 댓글 영역 (추후 구현 예정 자리) */}
<div className="mt-16">
<h3 className="text-xl font-bold mb-6"></h3>
<div className="bg-gray-50 rounded-xl p-10 text-center text-gray-400">
! 🚀
</div>
</div>
</article>
);
}

23
src/app/providers.tsx Normal file
View File

@@ -0,0 +1,23 @@
// src/app/providers.tsx
'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useState } from 'react';
export default function Providers({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(() => new QueryClient({
defaultOptions: {
queries: {
// 창을 다시 눌렀을 때 불필요한 재요청 방지
refetchOnWindowFocus: false,
retry: 1,
},
},
}));
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}

163
src/app/signup/page.tsx Normal file
View File

@@ -0,0 +1,163 @@
// src/app/signup/page.tsx
'use client';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useRouter } from 'next/navigation';
import { signup, verifyEmail } from '@/api/auth';
import { SignupRequest } from '@/types';
import Link from 'next/link';
export default function SignupPage() {
const router = useRouter();
const [step, setStep] = useState<'FORM' | 'VERIFY'>('FORM'); // 단계 관리
const [loading, setLoading] = useState(false);
const [registeredEmail, setRegisteredEmail] = useState(''); // 인증할 이메일 저장
// React Hook Form 설정
const { register, handleSubmit, formState: { errors }, watch } = useForm<SignupRequest>();
const [verifyCode, setVerifyCode] = useState('');
// 1단계: 회원가입 정보 제출
const onSignupSubmit = async (data: SignupRequest) => {
setLoading(true);
try {
const res = await signup(data);
if (res.code === 'SUCCESS') {
alert(`📧 ${data.email}로 인증 코드를 보냈습니다!`);
setRegisteredEmail(data.email); // 이메일 기억하기
setStep('VERIFY'); // 2단계로 이동
} else {
alert('회원가입 실패: ' + res.message);
}
} catch (error: any) {
alert('오류 발생: ' + (error.response?.data?.message || error.message));
} finally {
setLoading(false);
}
};
// 2단계: 인증 코드 제출
const onVerifySubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!verifyCode) return alert('인증 코드를 입력해주세요.');
setLoading(true);
try {
const res = await verifyEmail({ email: registeredEmail, code: verifyCode });
if (res.code === 'SUCCESS') {
alert('✅ 인증되었습니다! 로그인 페이지로 이동합니다.');
router.push('/login');
} else {
alert('인증 실패: ' + res.message);
}
} catch (error: any) {
alert('오류 발생: ' + (error.response?.data?.message || error.message));
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 px-4 py-12">
<div className="max-w-md w-full bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
{/* 헤더 */}
<div className="text-center mb-8">
<h1 className="text-2xl font-bold text-gray-900"> 🚀</h1>
<p className="text-sm text-gray-500 mt-2">
{step === 'FORM' ? '정보를 입력하고 인증 메일을 받으세요.' : '이메일로 전송된 6자리 코드를 입력하세요.'}
</p>
</div>
{/* STEP 1: 가입 정보 입력 폼 */}
{step === 'FORM' && (
<form onSubmit={handleSubmit(onSignupSubmit)} className="space-y-5">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
{...register('email', {
required: '이메일은 필수입니다.',
pattern: { value: /\S+@\S+\.\S+/, message: '이메일 형식이 올바르지 않습니다.' }
})}
className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 outline-none"
placeholder="user@example.com"
/>
{errors.email && <p className="text-red-500 text-xs mt-1">{errors.email.message}</p>}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
{...register('nickname', { required: '닉네임을 입력해주세요.' })}
className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 outline-none"
placeholder="개발자박씨"
/>
{errors.nickname && <p className="text-red-500 text-xs mt-1">{errors.nickname.message}</p>}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<input
type="password"
{...register('password', { required: '비밀번호를 입력해주세요.', minLength: { value: 6, message: '6자 이상 입력해주세요.' } })}
className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 outline-none"
placeholder="••••••••"
/>
{errors.password && <p className="text-red-500 text-xs mt-1">{errors.password.message}</p>}
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-lg transition-colors disabled:bg-gray-400"
>
{loading ? '처리 중...' : '인증 메일 받기'}
</button>
</form>
)}
{/* STEP 2: 인증 코드 입력 폼 */}
{step === 'VERIFY' && (
<form onSubmit={onVerifySubmit} className="space-y-5">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1"> (6)</label>
<input
type="text"
value={verifyCode}
onChange={(e) => setVerifyCode(e.target.value)}
maxLength={6}
className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 outline-none text-center text-2xl tracking-widest"
placeholder="000000"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 rounded-lg transition-colors disabled:bg-gray-400"
>
{loading ? '확인 중...' : '인증 완료'}
</button>
<button
type="button"
onClick={() => setStep('FORM')}
className="w-full text-sm text-gray-500 hover:underline"
>
</button>
</form>
)}
{/* 하단 링크 */}
<div className="mt-6 text-center text-sm text-gray-500">
?{' '}
<Link href="/login" className="text-blue-600 font-semibold hover:underline">
</Link>
</div>
</div>
</div>
);
}

247
src/app/write/page.tsx Normal file
View File

@@ -0,0 +1,247 @@
'use client';
import { useState, useEffect, Fragment, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import dynamic from 'next/dynamic';
import { getCategories } from '@/api/category';
import { createPost } from '@/api/posts';
import { uploadImage } from '@/api/image'; // 👈 추가
import { useAuthStore } from '@/store/authStore';
import { Listbox, Transition } from '@headlessui/react';
import { CheckIcon, ChevronUpDownIcon, PhotoIcon } from '@heroicons/react/20/solid'; // 👈 아이콘 추가
import { clsx } from 'clsx';
const MDEditor = dynamic(() => import('@uiw/react-md-editor'), { ssr: false });
export default function WritePage() {
const router = useRouter();
const { role, _hasHydrated } = useAuthStore();
const fileInputRef = useRef<HTMLInputElement>(null); // 👈 파일 입력 참조
const [title, setTitle] = useState('');
const [categoryId, setCategoryId] = useState<number | null>(null);
const [content, setContent] = useState<string>('**여기에 내용을 작성하세요.**');
const [isSubmitting, setIsSubmitting] = useState(false);
const [isUploading, setIsUploading] = useState(false); // 👈 이미지 업로드 상태
const { data: categories } = useQuery({
queryKey: ['categories'],
queryFn: getCategories,
});
const selectedCategoryName = (() => {
if (!categoryId || !categories) return '카테고리 선택';
for (const cat of categories) {
if (cat.id === categoryId) return cat.name;
if (cat.children) {
const child = cat.children.find(c => c.id === categoryId);
if (child) return child.name;
}
}
return '카테고리 선택';
})();
useEffect(() => {
if (!_hasHydrated) return;
if (!role || !role.includes('ADMIN')) {
alert('관리자만 접근 가능합니다.');
router.replace('/');
}
}, [role, _hasHydrated, router]);
// 👇 이미지 업로드 핸들러
const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsUploading(true);
try {
// 1. 서버로 이미지 전송
const res = await uploadImage(file);
if (res.code === 'SUCCESS' && res.data) {
const imageUrl = res.data; // 서버가 준 이미지 URL
// 2. 본문에 마크다운 이미지 문법 삽입
// 현재 내용 뒤에 추가하거나, 커서 위치를 찾아서 넣을 수 있습니다.
// 여기서는 간단히 맨 뒤에 한 줄 띄우고 추가합니다.
const imageMarkdown = `\n![${file.name}](${imageUrl})\n`;
setContent((prev) => prev + imageMarkdown);
} else {
alert('이미지 업로드 실패: ' + res.message);
}
} catch (error) {
console.error(error);
alert('이미지 업로드 중 오류가 발생했습니다.');
} finally {
setIsUploading(false);
// 같은 파일을 다시 선택할 수 있도록 input 초기화
if (fileInputRef.current) fileInputRef.current.value = '';
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!title.trim()) return alert('제목을 입력해주세요.');
if (!categoryId) return alert('카테고리를 선택해주세요.');
if (!content.trim()) return alert('내용을 입력해주세요.');
if (!confirm('글을 발행하시겠습니까?')) return;
setIsSubmitting(true);
try {
await createPost({ title, content, categoryId });
alert('글이 성공적으로 발행되었습니다! 🎉');
router.push('/');
} catch (error: any) {
console.error(error);
alert('에러 발생: ' + (error.response?.data?.message || '서버 오류'));
} finally {
setIsSubmitting(false);
}
};
if (!_hasHydrated || !role) {
return <div className="min-h-screen flex justify-center items-center"> ...</div>;
}
return (
<div className="max-w-4xl mx-auto pb-20 z-10 relative">
<h1 className="text-3xl font-bold text-gray-800 mb-8"> </h1>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 relative z-20">
<div className="col-span-1">
<Listbox value={categoryId} onChange={setCategoryId}>
<div className="relative mt-1">
<Listbox.Button className="relative w-full cursor-default rounded-lg bg-white py-3 pl-4 pr-10 text-left border border-gray-300 focus:outline-none focus-visible:border-blue-500 focus-visible:ring-2 focus-visible:ring-white/75 focus-visible:ring-offset-2 focus-visible:ring-offset-blue-300 sm:text-sm transition-all shadow-sm">
<span className={clsx("block truncate", !categoryId && "text-gray-400")}>
{selectedCategoryName}
</span>
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
<ChevronUpDownIcon
className="h-5 w-5 text-gray-400"
aria-hidden="true"
/>
</span>
</Listbox.Button>
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Listbox.Options className="absolute mt-2 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black/5 focus:outline-none sm:text-sm z-50">
{categories?.map((cat) => (
<Fragment key={cat.id}>
<div className="px-4 py-2 text-xs font-bold text-gray-500 bg-gray-50 uppercase tracking-wider">
{cat.name}
</div>
<Listbox.Option
value={cat.id}
className={({ active }) =>
clsx(
'relative cursor-default select-none py-2.5 pl-10 pr-4',
active ? 'bg-blue-50 text-blue-600' : 'text-gray-900'
)
}
>
{({ selected }) => (
<>
<span className={clsx('block truncate font-medium', selected && 'text-blue-600')}>
{cat.name} ()
</span>
{selected && (
<span className="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
<CheckIcon className="h-5 w-5" aria-hidden="true" />
</span>
)}
</>
)}
</Listbox.Option>
{cat.children?.map((child) => (
<Listbox.Option
key={child.id}
value={child.id}
className={({ active }) =>
clsx(
'relative cursor-default select-none py-2.5 pl-10 pr-4',
active ? 'bg-blue-50 text-blue-600' : 'text-gray-700'
)
}
>
{({ selected }) => (
<>
<span className={clsx('block truncate ml-4 border-l-2 border-gray-200 pl-3', selected && 'font-semibold text-blue-600 border-blue-600')}>
{child.name}
</span>
{selected && (
<span className="absolute inset-y-0 left-0 flex items-center pl-3 text-blue-600">
<CheckIcon className="h-5 w-5" aria-hidden="true" />
</span>
)}
</>
)}
</Listbox.Option>
))}
</Fragment>
))}
</Listbox.Options>
</Transition>
</div>
</Listbox>
</div>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="제목을 입력하세요"
className="col-span-3 px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 outline-none font-bold text-lg shadow-sm"
/>
</div>
<div className="relative z-10">
{/* 👇 이미지 업로드 버튼 영역 추가 */}
<div className="flex justify-end mb-2">
<input
type="file"
ref={fileInputRef}
className="hidden"
accept="image/*"
onChange={handleImageUpload}
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={isUploading}
className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-gray-600 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 hover:text-blue-600 transition-colors shadow-sm"
>
{isUploading ? (
<span className="animate-pulse"> ...</span>
) : (
<>
<PhotoIcon className="w-4 h-4" />
<span> </span>
</>
)}
</button>
</div>
<div data-color-mode="light" className="editor-container">
<MDEditor value={content} onChange={(val) => setContent(val || '')} height={500} preview="live" className="rounded-lg border border-gray-200 shadow-sm" />
</div>
</div>
<div className="flex justify-end gap-4 mt-8 relative z-10">
<button type="button" onClick={() => router.back()} className="px-6 py-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 font-medium transition-colors"></button>
<button type="submit" disabled={isSubmitting || isUploading} className="px-8 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-bold shadow-md transition-all transform hover:-translate-y-1 disabled:bg-gray-400">{isSubmitting ? '발행 중...' : '글 발행하기 🚀'}</button>
</div>
</form>
</div>
);
}

View File

@@ -0,0 +1,175 @@
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { getCategories } from '@/api/category';
import { Github, Mail, Menu, X, ChevronRight, Folder, FolderOpen } from 'lucide-react';
import { clsx } from 'clsx';
export default function Sidebar() {
const [isOpen, setIsOpen] = useState(true); // 사이드바 열림/닫힘 상태
const pathname = usePathname();
// 1. 서버에서 카테고리 데이터 가져오기
const { data: categories } = useQuery({
queryKey: ['categories'],
queryFn: getCategories,
});
return (
<>
{/* 📱 모바일용 메뉴 토글 버튼 (화면 왼쪽 위에 고정) */}
<button
onClick={() => setIsOpen(!isOpen)}
className="fixed top-4 left-4 z-50 p-2 bg-white rounded-full shadow-md md:hidden hover:bg-gray-100 transition-colors"
>
{isOpen ? <X size={20} /> : <Menu size={20} />}
</button>
{/* 🖥️ 사이드바 본체 */}
<aside
className={clsx(
// 기본 스타일 & 애니메이션
'fixed top-0 left-0 z-40 h-screen bg-white border-r border-gray-100 transition-all duration-300 ease-in-out overflow-y-auto scrollbar-hide',
// 열렸을 때 vs 닫혔을 때 너비 조절
isOpen ? 'w-72 translate-x-0' : 'w-0 -translate-x-full md:w-20 md:translate-x-0',
'flex flex-col'
)}
>
{/* A. 프로필 영역 */}
<div className={clsx('p-6 text-center transition-opacity duration-200', !isOpen && 'md:opacity-0 md:hidden')}>
<div className="w-24 h-24 mx-auto bg-gray-200 rounded-full mb-4 overflow-hidden shadow-inner ring-4 ring-gray-50">
{/* 프로필 이미지 (임시) */}
<img
src="https://api.dicebear.com/7.x/notionists/svg?seed=Felix"
alt="Profile"
className="w-full h-full object-cover"
/>
</div>
<h2 className="text-xl font-bold text-gray-800">Dev Park</h2>
<p className="text-sm text-gray-500 mt-1"> </p>
<p className="text-xs text-gray-400 mt-3 font-light leading-relaxed">
"코드로 세상을 바꾸고 싶은<br />박개발의 기술 블로그입니다."
</p>
</div>
{/* B. 네비게이션 & 카테고리 */}
<nav className="flex-1 px-4 py-2">
{/* 닫혔을 때(좁은 모드) 메뉴 아이콘 표시 */}
<div className={clsx('flex flex-col items-center gap-4 mt-4', isOpen && 'hidden')}>
<Folder size={24} className="text-gray-400" />
</div>
{/* 열렸을 때 메뉴 목록 */}
<div className={clsx('space-y-1', !isOpen && 'md:hidden')}>
<p className="px-4 text-xs font-bold text-gray-400 uppercase tracking-wider mb-3 mt-4">
Categories
</p>
{/* 로딩 중일 때 스켈레톤 UI */}
{!categories && (
<div className="space-y-2 px-4">
{[1, 2, 3].map((i) => (
<div key={i} className="h-8 bg-gray-100 rounded animate-pulse" />
))}
</div>
)}
{/* 실제 카테고리 렌더링 */}
{categories?.map((cat) => {
// 현재 카테고리(또는 자식)가 선택되었는지 확인
const isActive = pathname.includes(`/category/${cat.id}`);
return (
<div key={cat.id} className="mb-1">
{/* 1차 카테고리 */}
<Link
href={`/category/${cat.id}`}
className={clsx(
'flex items-center justify-between px-4 py-2.5 text-sm font-medium rounded-lg transition-all group',
isActive
? 'bg-blue-50 text-blue-600'
: 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
)}
>
<div className="flex items-center gap-2.5">
{isActive ? <FolderOpen size={16} /> : <Folder size={16} />}
<span>{cat.name}</span>
</div>
{cat.children && cat.children.length > 0 && (
<ChevronRight size={14} className={clsx("text-gray-300 transition-transform", isActive && "rotate-90")} />
)}
</Link>
{/* 2차 카테고리 (자식이 있을 경우) */}
{cat.children && cat.children.length > 0 && (
<div className="ml-5 mt-1 space-y-0.5 border-l-2 border-gray-100 pl-2">
{cat.children.map((child) => {
const isChildActive = pathname.includes(`/category/${child.id}`);
return (
<Link
key={child.id}
href={`/category/${child.id}`}
className={clsx(
"block px-3 py-2 text-sm rounded-md transition-colors",
isChildActive
? "text-blue-600 font-medium bg-blue-50/50"
: "text-gray-500 hover:text-gray-900 hover:bg-gray-50"
)}
>
- {child.name}
</Link>
);
})}
</div>
)}
</div>
);
})}
</div>
</nav>
{/* C. 광고 영역 (거슬리지 않게 하단 배치) */}
<div className={clsx('px-6 pb-6', !isOpen && 'hidden')}>
<div className="p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl border border-dashed border-gray-200 text-center relative overflow-hidden group cursor-pointer hover:border-blue-200 transition-colors">
<div className="absolute top-0 right-0 p-1">
<span className="text-[9px] bg-gray-200 text-gray-500 px-1 rounded">AD</span>
</div>
<p className="text-xs text-blue-500 font-semibold mb-1">AWS Cloud School</p>
<p className="text-[11px] text-gray-500">
<br/>
<span className="underline group-hover:text-blue-600"> &rarr;</span>
</p>
</div>
</div>
{/* D. 소셜 링크 (최하단) */}
<div className={clsx('p-6 border-t border-gray-100 bg-white', !isOpen && 'hidden')}>
<div className="flex justify-center gap-3">
<a
href="https://github.com"
target="_blank"
rel="noreferrer"
className="p-2.5 text-gray-500 bg-gray-50 rounded-full hover:bg-gray-800 hover:text-white transition-all shadow-sm hover:-translate-y-1"
aria-label="Github"
>
<Github size={18} />
</a>
<a
href="mailto:user@example.com"
className="p-2.5 text-gray-500 bg-gray-50 rounded-full hover:bg-blue-500 hover:text-white transition-all shadow-sm hover:-translate-y-1"
aria-label="Email"
>
<Mail size={18} />
</a>
</div>
<p className="text-center text-[10px] text-gray-300 mt-4 font-light">
© 2024 Dev Park. All rights reserved.
</p>
</div>
</aside>
</>
);
}

View File

@@ -0,0 +1,73 @@
// src/components/layout/TopHeader.tsx
'use client';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/store/authStore';
import { useEffect, useState } from 'react';
import { LogOut, PenLine, User, UserPlus } from 'lucide-react';
export default function TopHeader() {
const router = useRouter();
const { isLoggedIn, role, logout } = useAuthStore(); // 👈 role 가져오기
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
const handleLogout = () => {
if (confirm('로그아웃 하시겠습니까?')) {
logout();
alert('로그아웃 되었습니다.');
router.push('/');
}
};
if (!mounted) return null;
return (
<div className="absolute top-6 right-6 z-30 flex items-center gap-3">
{isLoggedIn ? (
<>
{/* 👇 관리자(ADMIN)일 때만 글쓰기 버튼 노출 */}
{role && role.includes('ADMIN') && (
<Link
href="/write"
className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white text-sm font-bold rounded-full shadow-md hover:bg-blue-700 hover:shadow-lg transition-all transform hover:-translate-y-0.5"
>
<PenLine size={16} />
<span></span>
</Link>
)}
<button
onClick={handleLogout}
className="flex items-center gap-2 px-4 py-2 bg-white text-gray-600 text-sm font-medium rounded-full border border-gray-200 shadow-sm hover:bg-gray-50 hover:text-red-500 transition-colors"
>
<LogOut size={16} />
<span className="hidden sm:inline"></span>
</button>
</>
) : (
<>
<Link
href="/login"
className="flex items-center gap-2 px-4 py-2 text-gray-500 text-sm font-medium hover:text-blue-600 transition-colors"
>
<User size={18} />
<span></span>
</Link>
<Link
href="/signup"
className="flex items-center gap-2 px-4 py-2 bg-white text-blue-600 text-sm font-bold rounded-full border border-blue-100 shadow-sm hover:bg-blue-50 hover:shadow-md transition-all"
>
<UserPlus size={16} />
<span></span>
</Link>
</>
)}
</div>
);
}

View File

@@ -0,0 +1,14 @@
// src/components/post/MarkdownRenderer.tsx
import ReactMarkdown from 'react-markdown';
interface MarkdownRendererProps {
content: string;
}
export default function MarkdownRenderer({ content }: MarkdownRendererProps) {
return (
<div className="prose prose-slate max-w-none prose-headings:font-bold prose-a:text-blue-600 hover:prose-a:text-blue-500 prose-img:rounded-xl">
<ReactMarkdown>{content}</ReactMarkdown>
</div>
);
}

View File

@@ -0,0 +1,56 @@
import { Post } from '@/types';
import Link from 'next/link';
import { format } from 'date-fns';
// 🛠️ 헬퍼 함수: 마크다운 문법 제거하고 순수 텍스트만 추출
function getSummary(content?: string) {
if (!content) return '';
return content
.replace(/[#*`_~]/g, '') // 특수문자(#, *, ` 등) 제거
.replace(/\[(.*?)\]\(.*?\)/g, '$1') // 링크에서 텍스트만 남김 [글자](주소) -> 글자
.replace(/\n/g, ' ') // 줄바꿈을 공백으로
.substring(0, 120); // 120자까지만 자르기
}
export default function PostCard({ post }: { post: Post }) {
// 요약문 생성
const summary = getSummary(post.content);
return (
<Link href={`/posts/${post.slug}`} className="block group h-full">
<article className="flex flex-col h-full bg-white rounded-2xl p-6 shadow-[0_2px_8px_rgba(0,0,0,0.04)] hover:shadow-[0_8px_24px_rgba(0,0,0,0.08)] hover:-translate-y-1 transition-all duration-300 border border-gray-100">
{/* 상단 카테고리 & 날짜 */}
<div className="flex items-center justify-between text-xs mb-4">
<span className="px-2.5 py-1 rounded-md bg-slate-100 text-slate-600 font-medium">
{post.categoryName}
</span>
<time className="text-gray-400 font-light">
{format(new Date(post.createdAt), 'MMM dd, yyyy')}
</time>
</div>
{/* 제목 */}
<h2 className="text-xl font-bold text-gray-800 mb-3 group-hover:text-blue-600 transition-colors line-clamp-2">
{post.title}
</h2>
{/* 요약글 (이제 실제 데이터가 나옵니다) */}
<p className="text-gray-500 text-sm line-clamp-3 mb-6 flex-1 leading-relaxed break-words min-h-[3rem]">
{summary}
</p>
{/* 하단 정보 */}
<div className="flex items-center justify-between pt-4 border-t border-gray-50">
<div className="flex items-center gap-2 text-xs text-gray-400">
<span>By Dev Park</span>
</div>
<span className="text-xs font-medium text-blue-500 flex items-center gap-1">
Read more <span className="group-hover:translate-x-1 transition-transform"></span>
</span>
</div>
</article>
</Link>
);
}

59
src/store/authStore.ts Normal file
View File

@@ -0,0 +1,59 @@
// src/store/authStore.ts
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
interface AuthState {
accessToken: string | null;
isLoggedIn: boolean;
role: string | null;
_hasHydrated: boolean; // 👈 추가: 데이터 로딩 완료 여부
login: (token: string) => void;
logout: () => void;
setHydrated: () => void; // 👈 추가: 로딩 완료 상태 변경 함수
}
// ... (getRoleFromToken 함수는 기존과 동일하게 유지하거나, 아래에 포함시켰습니다) ...
const getRoleFromToken = (token: string): string => {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
const decoded = JSON.parse(jsonPayload);
return decoded.role || decoded.roles || decoded.auth || 'USER';
} catch (e) {
return 'USER';
}
};
export const useAuthStore = create(
persist<AuthState>(
(set) => ({
accessToken: null,
isLoggedIn: false,
role: null,
_hasHydrated: false, // 초기값은 로딩 안됨
login: (token: string) => {
const role = getRoleFromToken(token);
const finalRole = Array.isArray(role) ? role[0] : role;
set({ accessToken: token, isLoggedIn: true, role: finalRole });
},
logout: () => set({ accessToken: null, isLoggedIn: false, role: null }),
setHydrated: () => set({ _hasHydrated: true }),
}),
{
name: 'auth-storage',
storage: createJSONStorage(() => localStorage), // 명시적 스토리지 설정
// 👇 핵심: 데이터를 다 불러오면(rehydrate) 실행되는 함수
onRehydrateStorage: () => (state) => {
state?.setHydrated();
},
}
)
);

65
src/types/index.ts Normal file
View File

@@ -0,0 +1,65 @@
// 1. 공통 응답 구조 (API 명세 0번 참고)
export interface ApiResponse<T> {
code: string;
message: string;
data: T;
}
// 2. 게시글 (Post) 타입 (API 명세 2번 참고)
export interface Post {
id: number;
title: string;
slug: string;
categoryName: string;
viewCount: number;
createdAt: string;
content?: string; // 상세 조회시에만 옴
}
// 3. 게시글 목록 페이징 응답
export interface PostListResponse {
content: Post[];
totalPages: number;
totalElements: number;
last: boolean;
}
// 4. 로그인 응답 (API 명세 1-3번 참고)
export interface AuthResponse {
grantType: string;
accessToken: string;
refreshToken: string;
accessTokenExpiresIn: number;
}
// 5. 카테고리 (API 명세 4번 참고)
export interface Category {
id: number;
name: string;
children: Category[];
}
// 1. 회원가입 요청
export interface SignupRequest {
email: string;
password: string;
nickname: string;
}
// 2. 이메일 인증 요청
export interface VerifyRequest {
email: string;
code: string;
}
// 3. 로그인 요청
export interface LoginRequest {
email: string;
password: string;
}
// 4. 로그인 성공 응답 데이터
export interface LoginResponse {
accessToken: string;
refreshToken?: string; // 나중을 위해 추가
}

22
tailwind.config.ts Normal file
View File

@@ -0,0 +1,22 @@
import type { Config } from "tailwindcss";
const config: Config = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [
require('@tailwindcss/typography'), // 👈 아까 추가하려던 게 이겁니다!
],
};
export default config;

34
tsconfig.json Normal file
View File

@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}

4737
yarn.lock Normal file

File diff suppressed because it is too large Load Diff