Compare commits

19 Commits

Author SHA1 Message Date
박원엽
dbfd84a8ab Refine chess board visual style
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m10s
2026-06-24 09:55:30 +09:00
박원엽
cc4fb0f947 feat: add chess resign and undo actions
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m16s
2026-06-24 09:01:13 +09:00
박원엽
924dd8b372 feat: add Maia chess game UI
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m11s
2026-06-19 14:49:28 +09:00
wypark
a828be323a .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m13s
2026-06-07 12:20:18 +09:00
wypark
8fedc8657e .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m5s
2026-06-07 11:43:52 +09:00
wypark
b466fa98c9 Simplify macOS layout structure
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m7s
2026-06-07 00:14:52 +09:00
wypark
eb2e713b24 .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m10s
2026-06-06 23:59:25 +09:00
wypark
091f97968b .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m9s
2026-06-06 23:22:46 +09:00
박원엽
f1668f08f2 .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m7s
2026-06-02 16:58:36 +09:00
박원엽
3fe1b0e6d5 .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m9s
2026-06-02 16:40:39 +09:00
박원엽
49fc7b5331 .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m10s
2026-06-02 15:34:30 +09:00
박원엽
d1a0340eb0 . 2026-06-02 15:26:54 +09:00
박원엽
895b19d284 .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m7s
2026-06-02 15:07:00 +09:00
박원엽
a56e95e6de .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m10s
2026-06-02 14:54:18 +09:00
박원엽
0b6ce404e1 .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m11s
2026-06-02 14:39:23 +09:00
박원엽
e3654a7bd5 .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m15s
2026-06-02 14:09:38 +09:00
박원엽
f26713e0ea .
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m9s
2026-05-29 14:51:46 +09:00
박원엽
b371200515 Polish macOS layer styling
All checks were successful
Deploy blog-frontend / build-and-deploy (push) Successful in 2m10s
2026-05-29 14:18:02 +09:00
박원엽
8e854a1afa . 2026-05-29 12:56:23 +09:00
49 changed files with 3622 additions and 860 deletions

105
LOG.md
View File

@@ -1,7 +1,108 @@
# Work Log # Work Log
## 2026-06-24
- Refined the chess board visual style to match the app's glass/control surfaces instead of the previous heavy wood-and-token treatment.
- Removed the circular chip backgrounds from pieces, kept high-contrast glyphs with subtle outlines, softened square/highlight colors, and tightened coordinate labels for a cleaner chess UI.
- Rebalanced chess board sizing and layout columns so the board window, actual board, side panel, and Dock spacing feel less awkward on a 1280x720 desktop viewport.
- Validation: `npm run lint` passed and `npm run build` passed. Browser verification on `http://localhost:3124/play/chess` with a temporary local puzzle API confirmed 64 squares, 32 rendered pieces, a 350px visible board above the Dock, balanced 480px/320px board-panel windows, and no console errors. The temporary API was stopped after verification.
- Recommended next task: verify the real authenticated `/chess/play/{gameId}` board against the Maia backend at common laptop heights and tune only the board size formula if the live game info panel changes vertical rhythm.
## 2026-06-19
- Added Maia game resign and undo API wrappers, then wired the play screen with in-progress-only "무르기" and "기권" actions plus a persistent "새 게임" link back to the setup screen.
- Locked board/actions during move, undo, and resign requests, updated the game cache from backend responses as the single source of truth, and refreshed history/stat queries after successful state changes.
- Added resigned-loss labeling so play, recent games, and history can show `기권패` for `RESIGNED` losses while still grouping them under losses.
- Validation: `npm run lint` passed and `npm run build` passed. Authenticated browser verification against the live Maia backend was not run in this session.
- Recommended next task: test resign and undo with an authenticated real game, including black-player games where Maia's opening white move must remain after undo.
- Reworked the shared chess board UI with a bordered board surface, high-contrast chip-style pieces, stronger selected/legal/last-move highlights, and transform-based piece movement transitions so player and Maia moves read as motion instead of instant jumps.
- Connected the daily puzzle board to the shared `ChessBoard` component, removing duplicated piece rendering and adding drag/drop support for puzzle moves.
- Updated Maia play state so optimistic player moves are highlighted locally while pending, then Maia's returned move can animate from the server response; changed the pending overlay into a small status pill so it no longer hides the board.
- Validation: `npm run lint` passed and `npm run build` passed. A local dev server is running on `http://localhost:3124`; browser verification with a temporary local puzzle API confirmed 64 squares, 32 piece-layer nodes, 0.42s piece transition styling, square selection/legal target markers, and no console errors. The temporary API was stopped after verification.
- Recommended next task: verify `/chess/play/{gameId}` against the real Maia backend with an authenticated account to tune the exact Maia response timing and capture/promotion edge cases.
- Added the authenticated Maia chess frontend: `/chess` lobby with rating/color/model and advanced settings, `/chess/play/[gameId]` playable board with backend FEN synchronization and PGN copy, and `/chess/history` account game history with outcome filters.
- Extended the chess API client and shared types for Maia game create/list/stats/detail/PGN/move endpoints while leaving the public `/api/chess-puzzles/**` puzzle request unchanged.
- Updated the Dock/menu/shell route handling so Chess opens the Maia lobby, with the existing public puzzle page still available at `/play/chess`.
- Validation: `npm run lint` passed and `npm run build` passed. A foreground `next dev --port 3122` startup reached Ready, but persistent detached/browser verification could not be completed because sandbox-launched background dev processes exited or hung before serving requests.
- Recommended next task: verify `/chess`, `/chess/play/{gameId}`, and `/chess/history` in an authenticated browser session against a reachable backend, especially real Maia move latency/error responses.
## 2026-06-07
- Fixed admin pages being pushed outside the visible content area by removing viewport-based `md:w-[80vw]` widths from the admin route shell and Markdown editor container.
- Changed admin containers to use the remaining shell content width (`w-full` with `max-w-[1400px]`) so the sidebar margin no longer combines with an extra viewport-width layout.
- Validation: `npm run lint` passed and `npm run build` passed. Authenticated browser verification was not possible in the current session because `/admin` redirects to login without an admin token.
- Recommended next task: verify `/admin` and `/admin/posts/new` in an authenticated browser session at desktop widths around 1280px and 1440px.
- Fixed the admin dashboard traffic chart visibility by giving bar columns a real height context, so percentage-based bar heights render instead of collapsing.
- Added fallback traffic points from recent/popular post data when the dashboard API or `traffic` array is empty, keeping the graph visible while the backend traffic aggregation is unavailable.
- Validation: `npm run lint` passed and `npm run build` passed. Browser navigation to `/admin` was attempted on `http://localhost:3112/`, but the current browser session was unauthenticated and rendered the login screen, so the admin chart itself was validated by code path and build checks rather than a live authenticated screenshot.
- Recommended next task: verify `/admin` with an authenticated admin session against the production API to confirm the real `traffic` payload replaces the fallback graph.
- Simplified the macOS-inspired layout by removing duplicated navigation surfaces: the desktop shortcut icon layer, the home page's inner Finder sidebar, and app navigation links from the system menu bar.
- Reworked the global sidebar into a cleaner library panel focused on profile, search, and categories, with a quieter compact profile row and no duplicated app shortcuts.
- Kept app-level movement in the Dock, category/search movement in the sidebar, and current-context/status information in the menu bar so each shell area has a clearer role.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on `http://localhost:3112/` confirmed no horizontal overflow, no desktop shortcut duplicates, the simplified home window, the Korean sidebar header, and no browser console warnings/errors. The local backend remained unavailable, so the home page showed empty post states.
- Recommended next task: test the simplified sidebar with real production categories and long category names, then tune category row spacing if the populated tree feels too dense.
## 2026-06-06
- Reworked the macOS-inspired shell into a fuller desktop illusion: full-width system menu bar, floating Finder-style sidebar window, viewport-centered Dock, desktop wallpaper layers, and desktop shortcut icons for major destinations.
- Rebuilt the public home screen as a Finder window with a locations sidebar, disk/status strip, file-like post rows, Spotlight-style search results, and stronger shared window glass treatment.
- Extended the OS treatment across archive, category, reader, login/signup, admin shell, post cards, and list rows, including file icons, Reader window framing, and cleanup of a stale mojibake notice-category check.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on `http://localhost:3112/`, `/archive`, and `/login` confirmed no horizontal overflow, desktop/mobile menu and Dock visibility rules, shared window surfaces, and no browser console warnings/errors. The default local API data rendered empty post states during the browser pass.
- Recommended next task: run a visual pass against `NEXT_PUBLIC_API_URL=https://blogserver.wypark.me` so populated post lists and one real reader page can be tuned with long Korean titles and real content.
- Fixed the desktop Dock so route changes from Dock menu links no longer leave focus-held open state behind when the Dock is not pinned.
- Kept the saved `dock-pinned-v2` preference unchanged during navigation and only released transient Dock focus/hover state after menu clicks and pathname changes.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on `http://localhost:3111/` confirmed that after unpinning the Dock, clicking the Dock archive menu navigates to `/archive`, the pin button remains `aria-pressed=false`, and the Dock collapses after the pointer leaves.
- Recommended next task: do one visual pass on the Dock at narrow desktop widths to confirm the collapse animation still feels smooth around the sidebar offset.
## 2026-06-02
- Refined the public layout after desktop/mobile review: the shell now guards horizontal overflow, uses route-aware bottom padding, hides the top menubar on mobile, and opens the mobile sidebar/search panel from the Dock.
- Reworked the Dock so mobile uses it as the primary navigation hub, while desktop keeps a folded Dock that expands on hover/focus and includes a pin toggle.
- Smoothed the desktop Dock hide/show interaction by separating hover-open, closing, and fully-collapsed states; the Dock now keeps the expanded hit area during the closing animation so re-entering mid-collapse reverses smoothly.
- Changed the desktop Dock's default state to pinned/open and added distinct soft pastel tones to Dock buttons, including stronger visual treatment for pin/unpin and auth actions.
- Softened the Dock button palette to quieter pastel tones and made the light-mode Dock bar read as a cleaner white glass surface.
- Fixed the Dock pin toggle so mouse-based unpinning no longer leaves button focus holding the Dock open, and changed the Dock Home button to a white neutral tone.
- Reworked the Dock material away from cute pastel tiles into a more macOS-like neutral frosted glass texture with translucent white glass buttons.
- Corrected the Dock button direction so only Home stays white, while the other actions keep subtle pastel tints with a translucent macOS-style glass material.
- Increased Dock button translucency contrast so the buttons remain glassy while sitting slightly more opaque than the Dock background.
- Rebalanced the home page around latest posts with popular posts as a supporting panel, converted the post detail page into a quieter reader surface, and hardened Markdown/code/table wrapping against mobile overflow.
- Added a client-side archive explorer with year, month, category, and compact/comfort density controls over the existing server-fetched post list.
- Rebuilt the chess page with safer viewport-aware board sizing, quieter puzzle panels, and enough layout clearance for the Dock.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on a local `next start` server confirmed no horizontal overflow on `/`, `/archive`, and `/play/chess` at mobile width, mobile Dock-centered navigation opens the sidebar panel without overflow, desktop CSS loads, the mobile Dock is hidden on desktop, and the desktop Dock starts folded with a pin control. The live chess board itself could not be verified because the local backend chess API was unavailable, so `/play/chess` rendered the error state.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on a local `next start` server confirmed the desktop Dock starts as a small bottom tab, uses 560ms transitions for tab/panel geometry, and expands into the larger Dock hit area when opened.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on a local `next start` server confirmed the Dock opens by default and Home/Archive/Chess/Login/Signup/Pin buttons render distinct pastel colors.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on `http://localhost:3106/` confirmed the light-mode Dock bar renders as a cleaner white glass surface and the Dock button colors use quieter pastel tones.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on `http://localhost:3107/` confirmed the Dock Home button renders white and mouse-based unpinning collapses the Dock after the pointer leaves.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on `http://localhost:3108/` confirmed the Dock uses neutral translucent glass material, with non-home buttons rendering as subtle white glass rather than pastel color tiles.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on `http://localhost:3109/` confirmed Home stays white while the other Dock buttons keep pastel-tinted translucent glass backgrounds with button-level blur.
- Validation: `npm run lint` passed and `npm run build` passed. In-app browser verification on `http://localhost:3110/` confirmed Dock buttons remain translucent but render slightly more opaque than the Dock background for clearer contrast.
- Recommended next task: run a browser pass against a reachable backend API, especially one real post detail route and the populated chess puzzle board, then tune any remaining content-specific long-title or board-height edge cases.
## 2026-05-29 ## 2026-05-29
- Fixed post detail 404s caused by double-encoding dynamic route slugs that already arrive percent-encoded from URLs such as `/posts/soft-delete%2C-hard-delete`.
- Updated the public post fetch helper to decode a route slug once before encoding it for the backend API path, preserving normal Korean/special-character slug requests while avoiding `%252C`-style API lookups.
- Validation: `npm run lint` passed and `npm run build` passed. A local production server with `NEXT_PUBLIC_API_URL=https://blogserver.wypark.me` returned real post titles for `/posts/soft-delete%2C-hard-delete`, `/posts/destructuring-%26-component%ED%95%A8%EC%88%98`, and `/posts/rtr-(refresh-token-rotation)`.
- Recommended next task: deploy the slug normalization fix before re-checking affected live post URLs in Search Console or the browser.
- Added a category post-list page size control with 9/18/27 options, defaulting to 9 and persisting the user's choice in `localStorage` under `categoryPageSize`.
- Wired the selected category page size into the React Query key and `getPostsByCategory` request size, resetting to page 1 when the size changes while preserving search behavior.
- Adjusted the category page toolbar so search, page-size controls, and grid/list controls stack cleanly on narrow screens and align in one row on desktop.
- Validation: `npm run lint` passed and `npm run build` passed. Static verification confirms the category query uses `pageSize` and the page-size selector persists to `localStorage`; interactive browser verification was skipped because no local browser/Playwright automation runtime is available in this environment.
- Recommended next task: verify the category toolbar in a real browser after deploy, especially mobile widths and the 18/27 page-size transitions.
- Investigated Google Search Console crawlability concerns for the live site.
- Checked live `robots.txt`, `sitemap.xml`, homepage, sample post pages, and backend post API with a Googlebot user agent; public post URLs in the sitemap returned 200 with no `X-Robots-Tag` or meta robots block.
- Confirmed the non-www production host `blog.wypark.me` is the relevant host; its home/archive initial HTML currently contains no `/posts/` links because public lists are client-side rendered.
- Identified crawlability risk areas: home/archive rely on client-side post-list fetching, local builds generate a static-only sitemap when the backend API is unreachable, sitemap `lastmod` values can be timezone-skewed when backend timestamps omit an offset, and canonical URLs are not currently emitted.
- Validation: `npm run build` passed. As expected without a local backend, build-time sitemap generation logged `fetch failed` and produced only static sitemap entries in the local `.next` output.
- Converted home and archive pages to server-rendered public post lists through a dedicated `src/api/publicPosts.ts` fetch helper so first HTML now includes discoverable `/posts/` links.
- Added centralized site metadata utilities, canonical metadata for public pages/posts, dynamic sitemap generation, KST-aware API date parsing for `lastmod`, and robots/site URL reuse.
- Validation: `npm run lint` passed and `npm run build` passed. A local production server with `NEXT_PUBLIC_API_URL=https://blogserver.wypark.me` returned 22 `/posts/` links on `/`, 204 on `/archive`, canonical URLs for both pages, and sitemap output with 104 URLs including 102 post URLs.
- Recommended next task: deploy the SEO crawlability fix, then resubmit `https://blog.wypark.me/sitemap.xml` and a representative post URL in Google Search Console URL Inspection.
- Redesigned the app shell into a macOS-inspired blog OS with pastel desktop background tokens, translucent menu bar, quick-launch Dock, and reusable window surfaces. - Redesigned the app shell into a macOS-inspired blog OS with pastel desktop background tokens, translucent menu bar, quick-launch Dock, and reusable window surfaces.
- Applied the window treatment to the home dashboard, post reader, archive, category view, auth screens, chess puzzle view, and admin management shells. - Applied the window treatment to the home dashboard, post reader, archive, category view, auth screens, chess puzzle view, and admin management shells.
- Restored the missing local `chess.js` install in `node_modules` so build verification could run; no dependency version changes were intended. - Restored the missing local `chess.js` install in `node_modules` so build verification could run; no dependency version changes were intended.
@@ -14,3 +115,7 @@
- Validation: `npm run lint` passed, `npm run build` passed. The build logged a sitemap fetch warning because the backend API at the local default was not reachable, but the command completed successfully. - Validation: `npm run lint` passed, `npm run build` passed. The build logged a sitemap fetch warning because the backend API at the local default was not reachable, but the command completed successfully.
- Browser verification: previously started this app on `http://localhost:3100` because ports 3000 and 3001 were already occupied; confirmed desktop background gradients, menu bar, Dock, and window surfaces on `/`, `/archive`, and `/login`. For this follow-up, the dev/standalone server started successfully in foreground but exited when launched as a background non-interactive process, so browser verification was skipped after lint/build passed. - Browser verification: previously started this app on `http://localhost:3100` because ports 3000 and 3001 were already occupied; confirmed desktop background gradients, menu bar, Dock, and window surfaces on `/`, `/archive`, and `/login`. For this follow-up, the dev/standalone server started successfully in foreground but exited when launched as a background non-interactive process, so browser verification was skipped after lint/build passed.
- Recommended next task: review the remaining older Korean strings in admin/editor flows and normalize any mojibake that predates this redesign. - Recommended next task: review the remaining older Korean strings in admin/editor flows and normalize any mojibake that predates this redesign.
- Unified the macOS-inspired layer system by splitting window, card, control, sidebar, menu bar, and Dock border/shadow/blur tokens, with stronger dark-mode card separation.
- Applied the layer tokens across shared surfaces, the menu bar, Dock, sidebar controls, search/toggles, home dashboard panels, reader navigation cards, and admin dashboard/editor panels.
- Validation: `npm run lint` passed, `npm run build` passed, and in-app browser verification on `http://localhost:3100/` confirmed distinct light/dark computed border, shadow, and backdrop blur values for the menu bar, main window, internal cards, and Dock.
- Recommended next task: do a visual pass on lower-traffic admin list/modal screens and convert any remaining ad hoc hover fills to the shared card/control tokens.

View File

@@ -1,5 +1,22 @@
import { http } from './http'; import { http } from './http';
import { ApiResponse, ChessPuzzle } from '@/types'; import {
ApiResponse,
ChessGameCreateRequest,
ChessGamePageResponse,
ChessGamePgnResponse,
ChessGameResponse,
ChessGameStatsResponse,
ChessMoveRequest,
ChessPuzzle,
} from '@/types';
const requireApiData = <T>(response: ApiResponse<T>, fallbackMessage: string) => {
if (!response.data) {
throw new Error(response.message || fallbackMessage);
}
return response.data;
};
export const getTodayChessPuzzle = async (timezone = 'Asia/Seoul') => { export const getTodayChessPuzzle = async (timezone = 'Asia/Seoul') => {
const response = await http.get<ApiResponse<ChessPuzzle>>('/api/chess-puzzles/today', { const response = await http.get<ApiResponse<ChessPuzzle>>('/api/chess-puzzles/today', {
@@ -8,3 +25,61 @@ export const getTodayChessPuzzle = async (timezone = 'Asia/Seoul') => {
return response.data.data; return response.data.data;
}; };
export const createChessGame = async (data: ChessGameCreateRequest) => {
const response = await http.post<ApiResponse<ChessGameResponse>>('/api/chess/games', data);
return requireApiData(response.data, '대국을 생성하지 못했습니다.');
};
export const getChessGames = async ({
page = 0,
size = 20,
sort = 'updatedAt,desc',
}: {
page?: number;
size?: number;
sort?: string;
} = {}) => {
const response = await http.get<ApiResponse<ChessGamePageResponse>>('/api/chess/games', {
params: { page, size, sort },
});
return requireApiData(response.data, '대국 기록을 불러오지 못했습니다.');
};
export const getChessGameStats = async () => {
const response = await http.get<ApiResponse<ChessGameStatsResponse>>('/api/chess/games/stats');
return requireApiData(response.data, '대국 통계를 불러오지 못했습니다.');
};
export const getChessGame = async (gameId: string) => {
const response = await http.get<ApiResponse<ChessGameResponse>>(`/api/chess/games/${gameId}`);
return requireApiData(response.data, '대국 상세를 불러오지 못했습니다.');
};
export const getChessGamePgn = async (gameId: string) => {
const response = await http.get<ApiResponse<ChessGamePgnResponse>>(`/api/chess/games/${gameId}/pgn`);
return requireApiData(response.data, 'PGN을 불러오지 못했습니다.');
};
export const postChessMove = async (gameId: string, data: ChessMoveRequest) => {
const response = await http.post<ApiResponse<ChessGameResponse>>(`/api/chess/games/${gameId}/moves`, data);
return requireApiData(response.data, '착수를 처리하지 못했습니다.');
};
export const resignChessGame = async (gameId: string) => {
const response = await http.post<ApiResponse<ChessGameResponse>>(`/api/chess/games/${gameId}/resign`);
return requireApiData(response.data, '기권을 처리하지 못했습니다.');
};
export const undoChessMove = async (gameId: string) => {
const response = await http.post<ApiResponse<ChessGameResponse>>(`/api/chess/games/${gameId}/undo`);
return requireApiData(response.data, '무르기를 처리하지 못했습니다.');
};

75
src/api/publicPosts.ts Normal file
View File

@@ -0,0 +1,75 @@
import { ApiResponse, Post, PostListResponse } from '@/types';
export const PUBLIC_POSTS_REVALIDATE_SECONDS = 300;
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
type PublicPostListParams = {
page?: number;
size?: number;
keyword?: string;
category?: string;
tag?: string;
sort?: string;
};
const buildPostListUrl = (params: PublicPostListParams = {}) => {
const searchParams = new URLSearchParams();
Object.entries({
...params,
sort: params.sort || 'createdAt,desc',
}).forEach(([key, value]) => {
if (value !== undefined && value !== '') {
searchParams.set(key, String(value));
}
});
return `${API_URL}/api/posts?${searchParams.toString()}`;
};
const encodeSlugPathSegment = (slug: string) => {
try {
return encodeURIComponent(decodeURIComponent(slug));
} catch {
return encodeURIComponent(slug);
}
};
export const fetchPublicPosts = async (
params: PublicPostListParams = {},
): Promise<PostListResponse | null> => {
try {
const response = await fetch(buildPostListUrl(params), {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
next: { revalidate: PUBLIC_POSTS_REVALIDATE_SECONDS },
});
if (!response.ok) return null;
const json = (await response.json()) as ApiResponse<PostListResponse>;
return json.data;
} catch (error) {
console.error('Public posts fetch error:', error);
return null;
}
};
export const fetchPublicPost = async (slug: string): Promise<Post | null> => {
try {
const response = await fetch(`${API_URL}/api/posts/${encodeSlugPathSegment(slug)}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
next: { revalidate: 60 },
});
if (!response.ok) return null;
const json = (await response.json()) as ApiResponse<Post>;
return json.data;
} catch (error) {
console.error('Public post fetch error:', error);
return null;
}
};

View File

@@ -29,10 +29,17 @@ import {
Category, Category,
DashboardPostStat, DashboardPostStat,
DashboardRange, DashboardRange,
DashboardTrafficPoint,
PageMeta, PageMeta,
Post, Post,
} from '@/types'; } from '@/types';
const dashboardRangeDays: Record<DashboardRange, number> = {
'7d': 7,
'30d': 30,
'90d': 90,
};
const countCategories = (categories: Category[] = []): number => { const countCategories = (categories: Category[] = []): number => {
return categories.reduce((count, category) => { return categories.reduce((count, category) => {
return count + 1 + countCategories(category.children || []); return count + 1 + countCategories(category.children || []);
@@ -89,11 +96,51 @@ const toPostStat = (post: Post): DashboardPostStat => ({
createdAt: post.createdAt, createdAt: post.createdAt,
}); });
const formatKstDateKey = (date: Date) => {
return new Intl.DateTimeFormat('sv-SE', {
timeZone: 'Asia/Seoul',
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(date);
};
const getFallbackTraffic = (
posts: Post[],
range: DashboardRange,
): DashboardTrafficPoint[] => {
const days = dashboardRangeDays[range];
const today = new Date();
const points = Array.from({ length: days }, (_, index) => {
const date = new Date(today);
date.setDate(today.getDate() - (days - 1 - index));
return {
date: formatKstDateKey(date),
views: 0,
};
});
const pointMap = new Map(points.map((point) => [point.date, point]));
posts.forEach((post) => {
const createdAt = new Date(post.createdAt);
if (Number.isNaN(createdAt.getTime())) return;
const dateKey = formatKstDateKey(createdAt);
const point = pointMap.get(dateKey);
if (!point) return;
point.views += post.viewCount;
});
return points;
};
function RecentPostRow({ post }: { post: Post }) { function RecentPostRow({ post }: { post: Post }) {
return ( return (
<Link <Link
href={`/posts/${post.slug}`} href={`/posts/${post.slug}`}
className="group flex items-center justify-between gap-4 rounded-lg px-3 py-3 transition hover:bg-black/[0.03] dark:hover:bg-white/10" className="group flex items-center justify-between gap-4 rounded-lg px-3 py-3 transition hover:bg-[var(--card-bg)]"
> >
<div className="min-w-0"> <div className="min-w-0">
<p className="truncate text-sm font-semibold text-[var(--color-text)] transition group-hover:text-[var(--color-accent)]">{post.title}</p> <p className="truncate text-sm font-semibold text-[var(--color-text)] transition group-hover:text-[var(--color-accent)]">{post.title}</p>
@@ -123,7 +170,7 @@ function RecentCommentRow({ comment }: { comment: AdminComment }) {
return ( return (
<Link <Link
href={`/posts/${comment.postSlug}`} href={`/posts/${comment.postSlug}`}
className="flex items-center gap-3 rounded-lg px-3 py-3 transition hover:bg-black/[0.03] dark:hover:bg-white/10" className="flex items-center gap-3 rounded-lg px-3 py-3 transition hover:bg-[var(--card-bg)]"
> >
{content} {content}
</Link> </Link>
@@ -249,6 +296,11 @@ export default function AdminPage() {
() => dashboard?.topPosts ?? (popularData?.content ?? []).map(toPostStat), () => dashboard?.topPosts ?? (popularData?.content ?? []).map(toPostStat),
[dashboard?.topPosts, popularData?.content], [dashboard?.topPosts, popularData?.content],
); );
const fallbackTraffic = useMemo(
() => getFallbackTraffic([...(latestData?.content ?? []), ...(popularData?.content ?? [])], range),
[latestData?.content, popularData?.content, range],
);
const trafficPoints = dashboard?.traffic?.length ? dashboard.traffic : fallbackTraffic;
return ( return (
<div className="space-y-8"> <div className="space-y-8">
@@ -301,10 +353,10 @@ export default function AdminPage() {
/> />
<AdminDashboardTrafficChart <AdminDashboardTrafficChart
points={dashboard?.traffic ?? []} points={trafficPoints}
range={range} range={range}
onRangeChange={setRange} onRangeChange={setRange}
isFallback={isFallback} isFallback={isFallback || !dashboard?.traffic?.length}
/> />
<div className="grid gap-6 xl:grid-cols-[1fr_0.8fr]"> <div className="grid gap-6 xl:grid-cols-[1fr_0.8fr]">

View File

@@ -1,148 +1,54 @@
'use client'; import type { Metadata } from 'next';
import { Archive } from 'lucide-react';
import { useMemo } from 'react'; import { fetchPublicPosts } from '@/api/publicPosts';
import { useQuery } from '@tanstack/react-query'; import ArchiveExplorer from '@/components/post/ArchiveExplorer';
import { format } from 'date-fns';
import Link from 'next/link';
import { Archive, Calendar, ChevronRight, FileText, Loader2 } from 'lucide-react';
import { getPosts } from '@/api/posts';
import EmptyState from '@/components/ui/EmptyState';
import StatusBadge from '@/components/ui/StatusBadge';
import Surface from '@/components/ui/Surface';
import WindowSurface from '@/components/ui/WindowSurface'; import WindowSurface from '@/components/ui/WindowSurface';
import { Post, PostListResponse } from '@/types'; import { SITE_NAME } from '@/lib/site';
import { PostListResponse } from '@/types';
const getTotalElements = (data?: PostListResponse) => { export const dynamic = 'force-dynamic';
export const revalidate = 300;
export const metadata: Metadata = {
title: 'Archive',
alternates: {
canonical: '/archive',
},
openGraph: {
title: `Archive | ${SITE_NAME}`,
url: '/archive',
siteName: SITE_NAME,
type: 'website',
},
};
const getTotalElements = (data?: PostListResponse | null) => {
return data?.page?.totalElements ?? data?.totalElements ?? 0; return data?.page?.totalElements ?? data?.totalElements ?? 0;
}; };
export default function ArchivePage() { export default async function ArchivePage() {
const { data, isLoading } = useQuery({ const data = await fetchPublicPosts({ page: 0, size: 1000, sort: 'createdAt,desc' });
queryKey: ['posts', 'all'], const posts = data?.content || [];
queryFn: () => getPosts({ page: 0, size: 1000 }),
staleTime: 1000 * 60 * 5,
});
const archiveGroups = useMemo(() => {
if (!data?.content) return {};
const groups: { [year: string]: { [month: string]: Post[] } } = {};
data.content.forEach((post) => {
const date = new Date(post.createdAt);
const year = date.getFullYear().toString();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
if (!groups[year]) groups[year] = {};
if (!groups[year][month]) groups[year][month] = [];
groups[year][month].push(post);
});
return groups;
}, [data]);
const sortedYears = useMemo(() => {
return Object.keys(archiveGroups).sort((a, b) => Number(b) - Number(a));
}, [archiveGroups]);
const totalPosts = getTotalElements(data); const totalPosts = getTotalElements(data);
if (isLoading) {
return ( return (
<div className="flex min-h-[50vh] items-center justify-center"> <main className="mx-auto min-w-0 max-w-[1180px] px-0 py-3 md:py-6">
<Loader2 className="animate-spin text-[var(--color-accent)]" size={40} />
</div>
);
}
return (
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6">
<WindowSurface <WindowSurface
title="Archive" title="Finder"
subtitle={`${totalPosts.toLocaleString()} posts`} subtitle={`Archive · ${totalPosts.toLocaleString()} posts`}
bodyClassName="p-5 md:p-8" bodyClassName="p-4 md:p-7"
> >
<div className="mb-10 border-b border-[var(--color-line)] pb-7 text-center md:text-left"> <div className="mb-7 min-w-0 border-b border-[var(--color-line)] pb-6 text-center md:text-left">
<h1 className="mb-3 flex items-center justify-center gap-3 text-3xl font-bold tracking-normal text-[var(--color-text)] md:justify-start"> <h1 className="mb-3 flex min-w-0 items-center justify-center gap-3 text-3xl font-bold tracking-normal text-[var(--color-text)] md:justify-start">
<Archive className="text-[var(--color-accent)]" size={32} /> <Archive className="shrink-0 text-[var(--color-accent)]" size={32} />
<span></span> <span className="min-w-0 break-words"></span>
</h1> </h1>
<p className="text-[var(--color-text-muted)]"> <p className="break-words text-sm leading-6 text-[var(--color-text-muted)] md:text-base">
<span className="font-bold text-[var(--color-accent)]">{totalPosts}</span> . <span className="font-bold text-[var(--color-accent)]">{totalPosts.toLocaleString()}</span> .
</p> </p>
</div> </div>
{sortedYears.length > 0 ? ( <ArchiveExplorer posts={posts} />
<div className="relative space-y-12">
<div className="absolute bottom-4 left-4 top-4 hidden w-px bg-[var(--color-line)] md:block" />
{sortedYears.map((year) => {
const months = archiveGroups[year];
const sortedMonths = Object.keys(months).sort((a, b) => Number(b) - Number(a));
return (
<div key={year} className="relative">
<div className="mb-6 flex items-center gap-4">
<div className="z-10 hidden h-9 w-9 items-center justify-center rounded-full border-4 border-[var(--window-bg-strong)] bg-[var(--color-accent-soft)] shadow-[var(--shadow-control)] md:flex">
<div className="h-2.5 w-2.5 rounded-full bg-[var(--color-accent)]" />
</div>
<h2 className="text-2xl font-bold text-[var(--color-text)]">{year}</h2>
</div>
<div className="space-y-8 md:pl-12">
{sortedMonths.map((month) => {
const posts = months[month];
const sortedPosts = [...posts].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
return (
<div key={month} className="group">
<h3 className="mb-4 flex items-center gap-2 text-lg font-bold text-[var(--color-text-muted)]">
<Calendar size={18} className="text-[var(--color-text-subtle)]" />
{month}
<StatusBadge tone="neutral">{posts.length}</StatusBadge>
</h3>
<div className="grid gap-3">
{sortedPosts.map((post) => (
<Link
key={post.id}
href={`/posts/${post.slug}`}
className="group/item block"
>
<Surface interactive className="flex items-center justify-between gap-4 p-4 shadow-none">
<div className="min-w-0 flex-1">
<h4 className="truncate text-base font-semibold text-[var(--color-text)] transition-colors group-hover/item:text-[var(--color-accent)]">
{post.title}
</h4>
<div className="mt-1.5 flex items-center gap-2 text-xs text-[var(--color-text-subtle)]">
<StatusBadge tone="neutral" className="px-1.5 py-0.5">{post.categoryName || '미분류'}</StatusBadge>
<span>·</span>
<span className="tabular-nums">
{format(new Date(post.createdAt), 'yyyy.MM.dd')}
</span>
</div>
</div>
<ChevronRight className="text-[var(--color-text-subtle)] transition-colors group-hover/item:text-[var(--color-accent)]" size={20} />
</Surface>
</Link>
))}
</div>
</div>
);
})}
</div>
</div>
);
})}
</div>
) : (
<EmptyState
title="아직 작성된 기록이 없습니다."
icon={<FileText size={48} />}
className="py-20"
/>
)}
</WindowSurface> </WindowSurface>
</main> </main>
); );

View File

@@ -3,16 +3,29 @@
import { use, useState } from 'react'; import { use, useState } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { clsx } from 'clsx'; import { clsx } from 'clsx';
import { ChevronLeft, ChevronRight, LayoutGrid, List, Loader2, Search as SearchIcon } from 'lucide-react'; import { ChevronLeft, ChevronRight, FolderOpen, LayoutGrid, List, Loader2, Search as SearchIcon } from 'lucide-react';
import { getPostsByCategory } from '@/api/posts'; import { getPostsByCategory } from '@/api/posts';
import PostCard from '@/components/post/PostCard'; import PostCard from '@/components/post/PostCard';
import PostListItem from '@/components/post/PostListItem'; import PostListItem from '@/components/post/PostListItem';
import PostSearch from '@/components/post/PostSearch'; import PostSearch from '@/components/post/PostSearch';
import EmptyState from '@/components/ui/EmptyState'; import EmptyState from '@/components/ui/EmptyState';
import SegmentedControl from '@/components/ui/SegmentedControl';
import Surface from '@/components/ui/Surface'; import Surface from '@/components/ui/Surface';
import WindowSurface from '@/components/ui/WindowSurface'; import WindowSurface from '@/components/ui/WindowSurface';
const PAGE_SIZE = 10; const PAGE_SIZE_OPTIONS = [
{ label: '9개', value: '9' },
{ label: '18개', value: '18' },
{ label: '27개', value: '27' },
] as const;
const DEFAULT_PAGE_SIZE = '9';
const CATEGORY_PAGE_SIZE_STORAGE_KEY = 'categoryPageSize';
type PageSizeOption = (typeof PAGE_SIZE_OPTIONS)[number]['value'];
const isPageSizeOption = (value: string | null): value is PageSizeOption => {
return PAGE_SIZE_OPTIONS.some((option) => option.value === value);
};
const isNoticeCategoryName = (categoryName: string) => { const isNoticeCategoryName = (categoryName: string) => {
const normalizedName = categoryName.toLowerCase(); const normalizedName = categoryName.toLowerCase();
@@ -27,6 +40,12 @@ export default function CategoryPage({ params }: { params: Promise<{ id: string
const [page, setPage] = useState(0); const [page, setPage] = useState(0);
const [keyword, setKeyword] = useState(''); const [keyword, setKeyword] = useState('');
const [pageSize, setPageSize] = useState<PageSizeOption>(() => {
if (typeof window === 'undefined') return DEFAULT_PAGE_SIZE;
const savedSize = localStorage.getItem(CATEGORY_PAGE_SIZE_STORAGE_KEY);
return isPageSizeOption(savedSize) ? savedSize : DEFAULT_PAGE_SIZE;
});
const [viewMode, setViewMode] = useState<'grid' | 'list'>(() => { const [viewMode, setViewMode] = useState<'grid' | 'list'>(() => {
if (isNoticeCategory || typeof window === 'undefined') return isNoticeCategory ? 'list' : 'grid'; if (isNoticeCategory || typeof window === 'undefined') return isNoticeCategory ? 'list' : 'grid';
@@ -47,9 +66,15 @@ export default function CategoryPage({ params }: { params: Promise<{ id: string
setPage(0); setPage(0);
}; };
const handlePageSizeChange = (nextSize: PageSizeOption) => {
setPage(0);
setPageSize(nextSize);
localStorage.setItem(CATEGORY_PAGE_SIZE_STORAGE_KEY, nextSize);
};
const { data: postsData, isLoading, error, isPlaceholderData } = useQuery({ const { data: postsData, isLoading, error, isPlaceholderData } = useQuery({
queryKey: ['posts', 'category', apiCategoryName, page, keyword], queryKey: ['posts', 'category', apiCategoryName, page, pageSize, keyword],
queryFn: () => getPostsByCategory(apiCategoryName, page, PAGE_SIZE, keyword), queryFn: () => getPostsByCategory(apiCategoryName, page, Number(pageSize), keyword),
placeholderData: (previousData) => previousData, placeholderData: (previousData) => previousData,
}); });
@@ -87,31 +112,43 @@ export default function CategoryPage({ params }: { params: Promise<{ id: string
return ( return (
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6"> <main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6">
<WindowSurface <WindowSurface
title={apiCategoryName} title="Finder"
subtitle={apiCategoryName}
bodyClassName="p-5 md:p-6" bodyClassName="p-5 md:p-6"
> >
<div className="mb-8 flex flex-col justify-between gap-4 border-b border-[var(--color-line)] pb-5 md:flex-row md:items-center"> <div className="mb-8 flex flex-col justify-between gap-4 border-b border-[var(--color-line)] pb-5 md:flex-row md:items-center">
<h1 className="flex shrink-0 items-baseline gap-2 text-2xl font-bold tracking-normal text-[var(--color-text)]"> <h1 className="flex min-w-0 items-center gap-3 text-2xl font-bold tracking-normal text-[var(--color-text)]">
{apiCategoryName} <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-control)]">
<FolderOpen size={20} />
</span>
<span className="min-w-0 truncate">{apiCategoryName}</span>
<span className="text-lg font-normal text-[var(--color-text-subtle)]"> </span> <span className="text-lg font-normal text-[var(--color-text-subtle)]"> </span>
</h1> </h1>
<div className="flex w-full items-center gap-3 md:w-auto"> <div className="flex w-full flex-col gap-3 md:w-auto md:flex-row md:items-center">
<PostSearch <PostSearch
onSearch={handleSearch} onSearch={handleSearch}
placeholder={`${apiCategoryName} 검색`} placeholder={`${apiCategoryName} 검색`}
className="w-full md:w-64" className="w-full md:w-64"
/> />
<div className="flex shrink-0 items-center gap-1 rounded-full border border-[var(--color-line)] bg-[var(--color-control)] p-1 shadow-[var(--shadow-control)] backdrop-blur-xl"> <SegmentedControl
ariaLabel="페이지당 게시글 수"
options={PAGE_SIZE_OPTIONS}
value={pageSize}
onChange={handlePageSizeChange}
className="justify-center"
/>
<div className="flex shrink-0 items-center gap-1 rounded-full border border-[var(--control-border)] bg-[var(--color-control)] p-1 shadow-[var(--shadow-control)] backdrop-blur-[18px]">
<button <button
type="button" type="button"
onClick={() => handleViewModeChange('grid')} onClick={() => handleViewModeChange('grid')}
className={clsx( className={clsx(
'rounded-full p-2 transition-all duration-150', 'rounded-full p-2 transition-all duration-150',
activeViewMode === 'grid' activeViewMode === 'grid'
? 'bg-[var(--window-bg-strong)] text-[var(--color-accent)] shadow-sm' ? 'bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-sm'
: 'text-[var(--color-text-subtle)] hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10', : 'text-[var(--color-text-subtle)] hover:bg-[var(--card-bg)] hover:text-[var(--color-text)]',
)} )}
title="카드로 보기" title="카드로 보기"
aria-label="카드로 보기" aria-label="카드로 보기"
@@ -125,8 +162,8 @@ export default function CategoryPage({ params }: { params: Promise<{ id: string
className={clsx( className={clsx(
'rounded-full p-2 transition-all duration-150', 'rounded-full p-2 transition-all duration-150',
activeViewMode === 'list' activeViewMode === 'list'
? 'bg-[var(--window-bg-strong)] text-[var(--color-accent)] shadow-sm' ? 'bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-sm'
: 'text-[var(--color-text-subtle)] hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10', : 'text-[var(--color-text-subtle)] hover:bg-[var(--card-bg)] hover:text-[var(--color-text)]',
)} )}
title="리스트로 보기" title="리스트로 보기"
aria-label="리스트로 보기" aria-label="리스트로 보기"
@@ -173,7 +210,7 @@ export default function CategoryPage({ params }: { params: Promise<{ id: string
type="button" type="button"
onClick={handlePrevPage} onClick={handlePrevPage}
disabled={page === 0} disabled={page === 0}
className="rounded-full p-2 text-[var(--color-text-muted)] transition-colors hover:bg-black/[0.04] hover:text-[var(--color-text)] disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent dark:hover:bg-white/10" className="rounded-full p-2 text-[var(--color-text-muted)] transition-colors hover:bg-[var(--card-bg)] hover:text-[var(--color-text)] disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent"
aria-label="이전 페이지" aria-label="이전 페이지"
> >
<ChevronLeft size={24} /> <ChevronLeft size={24} />
@@ -187,7 +224,7 @@ export default function CategoryPage({ params }: { params: Promise<{ id: string
type="button" type="button"
onClick={handleNextPage} onClick={handleNextPage}
disabled={isLast || isPlaceholderData} disabled={isLast || isPlaceholderData}
className="rounded-full p-2 text-[var(--color-text-muted)] transition-colors hover:bg-black/[0.04] hover:text-[var(--color-text)] disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent dark:hover:bg-white/10" className="rounded-full p-2 text-[var(--color-text-muted)] transition-colors hover:bg-[var(--card-bg)] hover:text-[var(--color-text)] disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent"
aria-label="다음 페이지" aria-label="다음 페이지"
> >
<ChevronRight size={24} /> <ChevronRight size={24} />

View File

@@ -0,0 +1,11 @@
import type { Metadata } from 'next';
import ChessHistoryClient from '@/components/chess/ChessHistoryClient';
export const metadata: Metadata = {
title: '대국 기록 | WYPark Blog',
description: 'Maia 체스 대국 기록과 결과를 확인합니다.',
};
export default function ChessHistoryPage() {
return <ChessHistoryClient />;
}

11
src/app/chess/page.tsx Normal file
View File

@@ -0,0 +1,11 @@
import type { Metadata } from 'next';
import ChessHomeClient from '@/components/chess/ChessHomeClient';
export const metadata: Metadata = {
title: 'Maia 체스 | WYPark Blog',
description: 'Maia3 봇과 체스를 두고 대국 기록과 PGN을 확인합니다.',
};
export default function ChessPage() {
return <ChessHomeClient />;
}

View File

@@ -0,0 +1,19 @@
import type { Metadata } from 'next';
import ChessGamePlayClient from '@/components/chess/ChessGamePlayClient';
export const metadata: Metadata = {
title: 'Maia 대국 | WYPark Blog',
description: 'Maia 체스 대국을 이어서 진행하고 PGN을 확인합니다.',
};
type ChessGamePageProps = {
params: Promise<{
gameId: string;
}>;
};
export default async function ChessGamePage({ params }: ChessGamePageProps) {
const { gameId } = await params;
return <ChessGamePlayClient gameId={gameId} />;
}

View File

@@ -24,22 +24,37 @@
Consolas, Consolas,
"Liberation Mono", "Liberation Mono",
monospace; monospace;
--color-page: #f7f4fb; --color-page: #edf4ff;
--desktop-bg: --desktop-bg:
linear-gradient(135deg, rgba(255, 232, 238, 0.78) 0%, rgba(255, 232, 238, 0) 36%), linear-gradient(118deg, rgba(95, 174, 255, 0.22) 0%, rgba(95, 174, 255, 0) 35%),
linear-gradient(155deg, rgba(218, 235, 255, 0.86) 6%, rgba(218, 235, 255, 0) 50%), linear-gradient(152deg, rgba(255, 158, 194, 0.2) 10%, rgba(255, 158, 194, 0) 48%),
linear-gradient(42deg, rgba(222, 251, 236, 0.74) 48%, rgba(222, 251, 236, 0) 88%), linear-gradient(46deg, rgba(124, 220, 185, 0.18) 46%, rgba(124, 220, 185, 0) 82%),
linear-gradient(180deg, #fbf8ff 0%, #eef5ff 100%); linear-gradient(180deg, #f9fcff 0%, #eaf3ff 48%, #f8f2ff 100%);
--window-bg: rgba(255, 255, 255, 0.58); --desktop-sheen:
--window-bg-strong: rgba(255, 255, 255, 0.78); linear-gradient(120deg, rgba(255, 255, 255, 0.48) 0 1px, transparent 1px 100%),
--window-titlebar: rgba(255, 255, 255, 0.5); repeating-linear-gradient(90deg, rgba(255, 255, 255, 0.12) 0 1px, transparent 1px 18px);
--window-border: rgba(255, 255, 255, 0.62); --desktop-icon-bg: rgba(255, 255, 255, 0.44);
--menubar-bg: rgba(255, 255, 255, 0.48); --desktop-icon-bg-hover: rgba(255, 255, 255, 0.64);
--dock-bg: rgba(255, 255, 255, 0.5); --desktop-icon-border: rgba(255, 255, 255, 0.62);
--sidebar-bg: rgba(255, 255, 255, 0.46); --window-bg: rgba(255, 255, 255, 0.66);
--color-surface: rgba(255, 255, 255, 0.58); --window-bg-strong: rgba(255, 255, 255, 0.86);
--color-surface-strong: rgba(255, 255, 255, 0.82); --window-titlebar: rgba(255, 255, 255, 0.58);
--color-control: rgba(255, 255, 255, 0.54); --window-border: rgba(255, 255, 255, 0.74);
--window-titlebar-border: rgba(39, 54, 82, 0.1);
--card-bg: rgba(255, 255, 255, 0.46);
--card-bg-strong: rgba(255, 255, 255, 0.68);
--card-border: rgba(39, 54, 82, 0.11);
--card-border-hover: rgba(39, 54, 82, 0.18);
--control-border: rgba(39, 54, 82, 0.12);
--menubar-bg: rgba(255, 255, 255, 0.58);
--menubar-border: rgba(255, 255, 255, 0.72);
--dock-bg: rgba(248, 250, 252, 0.54);
--dock-border: rgba(255, 255, 255, 0.68);
--sidebar-bg: rgba(255, 255, 255, 0.58);
--sidebar-border: rgba(255, 255, 255, 0.68);
--color-surface: var(--card-bg);
--color-surface-strong: var(--card-bg-strong);
--color-control: rgba(255, 255, 255, 0.56);
--color-line: rgba(39, 54, 82, 0.13); --color-line: rgba(39, 54, 82, 0.13);
--color-text: #1d1d1f; --color-text: #1d1d1f;
--color-text-muted: #62646d; --color-text-muted: #62646d;
@@ -48,10 +63,13 @@
--color-accent-hover: #0071e3; --color-accent-hover: #0071e3;
--color-accent-soft: rgba(0, 102, 204, 0.1); --color-accent-soft: rgba(0, 102, 204, 0.1);
--color-danger-soft: rgba(255, 59, 48, 0.1); --color-danger-soft: rgba(255, 59, 48, 0.1);
--shadow-window: 0 26px 80px rgba(70, 92, 130, 0.16), 0 1px 0 rgba(255, 255, 255, 0.7) inset; --shadow-window: 0 34px 96px rgba(47, 74, 112, 0.22), 0 16px 34px rgba(47, 74, 112, 0.1), 0 1px 0 rgba(255, 255, 255, 0.8) inset;
--shadow-panel: 0 22px 56px rgba(70, 92, 130, 0.13); --shadow-sidebar: 18px 20px 64px rgba(47, 74, 112, 0.16), 0 1px 0 rgba(255, 255, 255, 0.56) inset;
--shadow-card: 0 10px 30px rgba(70, 92, 130, 0.08); --shadow-menubar: 0 12px 32px rgba(47, 74, 112, 0.13), 0 1px 0 rgba(255, 255, 255, 0.62) inset;
--shadow-control: 0 12px 26px rgba(70, 92, 130, 0.1); --shadow-panel: var(--shadow-sidebar);
--shadow-card: 0 14px 34px rgba(70, 92, 130, 0.09), 0 1px 0 rgba(255, 255, 255, 0.5) inset;
--shadow-dock: 0 28px 78px rgba(15, 23, 42, 0.18), 0 12px 32px rgba(15, 23, 42, 0.12), 0 1px 0 rgba(255, 255, 255, 0.68) inset, 0 -1px 0 rgba(15, 23, 42, 0.06) inset;
--shadow-control: 0 12px 26px rgba(70, 92, 130, 0.1), 0 1px 0 rgba(255, 255, 255, 0.46) inset;
--focus-ring: 0 0 0 4px rgba(0, 102, 204, 0.14); --focus-ring: 0 0 0 4px rgba(0, 102, 204, 0.14);
--background: var(--color-page); --background: var(--color-page);
--foreground: var(--color-text); --foreground: var(--color-text);
@@ -66,23 +84,38 @@
} }
html[data-theme="dark"] { html[data-theme="dark"] {
--color-page: #11131d; --color-page: #0c101a;
--desktop-bg: --desktop-bg:
linear-gradient(135deg, rgba(88, 56, 104, 0.42) 0%, rgba(88, 56, 104, 0) 38%), linear-gradient(118deg, rgba(44, 128, 204, 0.34) 0%, rgba(44, 128, 204, 0) 38%),
linear-gradient(150deg, rgba(43, 73, 110, 0.5) 10%, rgba(43, 73, 110, 0) 54%), linear-gradient(150deg, rgba(125, 66, 139, 0.3) 12%, rgba(125, 66, 139, 0) 55%),
linear-gradient(42deg, rgba(38, 91, 72, 0.38) 48%, rgba(38, 91, 72, 0) 88%), linear-gradient(46deg, rgba(30, 118, 89, 0.26) 46%, rgba(30, 118, 89, 0) 84%),
linear-gradient(180deg, #131620 0%, #07090f 100%); linear-gradient(180deg, #111827 0%, #080b12 100%);
--window-bg: rgba(27, 29, 39, 0.64); --desktop-sheen:
--window-bg-strong: rgba(34, 36, 48, 0.82); linear-gradient(120deg, rgba(255, 255, 255, 0.08) 0 1px, transparent 1px 100%),
--window-titlebar: rgba(255, 255, 255, 0.06); repeating-linear-gradient(90deg, rgba(255, 255, 255, 0.035) 0 1px, transparent 1px 18px);
--window-border: rgba(255, 255, 255, 0.14); --desktop-icon-bg: rgba(22, 25, 34, 0.5);
--menubar-bg: rgba(24, 26, 36, 0.58); --desktop-icon-bg-hover: rgba(40, 44, 58, 0.72);
--dock-bg: rgba(24, 26, 36, 0.62); --desktop-icon-border: rgba(255, 255, 255, 0.16);
--sidebar-bg: rgba(22, 24, 33, 0.56); --window-bg: rgba(25, 29, 40, 0.72);
--color-surface: rgba(27, 29, 39, 0.64); --window-bg-strong: rgba(39, 43, 58, 0.88);
--color-surface-strong: rgba(34, 36, 48, 0.82); --window-titlebar: rgba(255, 255, 255, 0.09);
--color-control: rgba(255, 255, 255, 0.08); --window-border: rgba(255, 255, 255, 0.18);
--color-line: rgba(255, 255, 255, 0.12); --window-titlebar-border: rgba(255, 255, 255, 0.13);
--card-bg: rgba(43, 46, 60, 0.5);
--card-bg-strong: rgba(52, 55, 70, 0.66);
--card-border: rgba(255, 255, 255, 0.14);
--card-border-hover: rgba(255, 255, 255, 0.22);
--control-border: rgba(255, 255, 255, 0.13);
--menubar-bg: rgba(14, 17, 26, 0.68);
--menubar-border: rgba(255, 255, 255, 0.16);
--dock-bg: rgba(18, 20, 28, 0.56);
--dock-border: rgba(255, 255, 255, 0.16);
--sidebar-bg: rgba(21, 24, 34, 0.64);
--sidebar-border: rgba(255, 255, 255, 0.14);
--color-surface: var(--card-bg);
--color-surface-strong: var(--card-bg-strong);
--color-control: rgba(255, 255, 255, 0.085);
--color-line: rgba(255, 255, 255, 0.13);
--color-text: #f5f5f7; --color-text: #f5f5f7;
--color-text-muted: #b2b5bf; --color-text-muted: #b2b5bf;
--color-text-subtle: #8f939f; --color-text-subtle: #8f939f;
@@ -90,19 +123,26 @@ html[data-theme="dark"] {
--color-accent-hover: #46a6ff; --color-accent-hover: #46a6ff;
--color-accent-soft: rgba(41, 151, 255, 0.16); --color-accent-soft: rgba(41, 151, 255, 0.16);
--color-danger-soft: rgba(255, 69, 58, 0.16); --color-danger-soft: rgba(255, 69, 58, 0.16);
--shadow-window: 0 30px 90px rgba(0, 0, 0, 0.44), 0 1px 0 rgba(255, 255, 255, 0.08) inset; --shadow-window: 0 32px 100px rgba(0, 0, 0, 0.54), 0 14px 36px rgba(0, 0, 0, 0.28), 0 1px 0 rgba(255, 255, 255, 0.1) inset;
--shadow-panel: 0 24px 60px rgba(0, 0, 0, 0.36); --shadow-sidebar: 18px 0 46px rgba(0, 0, 0, 0.38), -1px 0 0 rgba(255, 255, 255, 0.08) inset;
--shadow-card: 0 10px 30px rgba(0, 0, 0, 0.24); --shadow-menubar: 0 18px 46px rgba(0, 0, 0, 0.32), 0 1px 0 rgba(255, 255, 255, 0.09) inset;
--shadow-control: 0 14px 30px rgba(0, 0, 0, 0.26); --shadow-panel: var(--shadow-sidebar);
--shadow-card: 0 16px 34px rgba(0, 0, 0, 0.32), 0 1px 0 rgba(255, 255, 255, 0.08) inset;
--shadow-dock: 0 30px 86px rgba(0, 0, 0, 0.48), 0 12px 34px rgba(0, 0, 0, 0.34), 0 1px 0 rgba(255, 255, 255, 0.14) inset, 0 -1px 0 rgba(0, 0, 0, 0.36) inset;
--shadow-control: 0 14px 30px rgba(0, 0, 0, 0.28), 0 1px 0 rgba(255, 255, 255, 0.08) inset;
--focus-ring: 0 0 0 4px rgba(41, 151, 255, 0.18); --focus-ring: 0 0 0 4px rgba(41, 151, 255, 0.18);
--background: var(--color-page); --background: var(--color-page);
--foreground: var(--color-text); --foreground: var(--color-text);
color-scheme: dark; color-scheme: dark;
} }
html {
overflow-x: hidden;
}
body { body {
min-height: 100vh; min-height: 100vh;
overflow-x: hidden; overflow-x: clip;
background: var(--desktop-bg); background: var(--desktop-bg);
background-attachment: fixed; background-attachment: fixed;
color: var(--foreground); color: var(--foreground);
@@ -117,6 +157,74 @@ body {
text-rendering: optimizeLegibility; text-rendering: optimizeLegibility;
} }
.desktop-shell {
position: relative;
isolation: isolate;
min-height: 100vh;
background: var(--desktop-bg);
}
.desktop-shell::before,
.desktop-shell::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
}
.desktop-shell::before {
z-index: 0;
background:
var(--desktop-sheen),
radial-gradient(ellipse at 20% 15%, rgba(255, 255, 255, 0.42), transparent 42%),
var(--desktop-bg);
}
.desktop-shell::after {
z-index: 0;
background-image:
repeating-linear-gradient(0deg, rgba(255, 255, 255, 0.06) 0 1px, transparent 1px 3px),
linear-gradient(180deg, transparent, rgba(255, 255, 255, 0.18));
opacity: 0.32;
mix-blend-mode: soft-light;
}
html[data-theme="dark"] .desktop-shell::after {
opacity: 0.22;
}
.window-surface {
position: relative;
}
.window-surface::before {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.42), transparent 22rem),
linear-gradient(90deg, rgba(255, 255, 255, 0.18), transparent 28%);
opacity: 0.52;
}
html[data-theme="dark"] .window-surface::before {
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.08), transparent 22rem),
linear-gradient(90deg, rgba(255, 255, 255, 0.05), transparent 28%);
opacity: 0.72;
}
.window-surface > * {
position: relative;
}
pre,
code,
table {
max-width: 100%;
}
::selection { ::selection {
background: var(--color-accent-soft); background: var(--color-accent-soft);
color: var(--color-text); color: var(--color-text);
@@ -221,7 +329,7 @@ samp,
.hover\:bg-gray-100:hover, .hover\:bg-gray-100:hover,
.hover\:bg-gray-200:hover, .hover\:bg-gray-200:hover,
.focus\:bg-white:focus { .focus\:bg-white:focus {
background-color: rgba(255, 255, 255, 0.58); background-color: var(--card-bg-strong);
} }
.hover\:bg-blue-50:hover { .hover\:bg-blue-50:hover {
@@ -264,16 +372,16 @@ input:not([type="checkbox"]):not([type="radio"]),
textarea, textarea,
select { select {
background-color: var(--color-control); background-color: var(--color-control);
border-color: var(--color-line); border-color: var(--control-border);
color: var(--color-text); color: var(--color-text);
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.42) inset; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.42) inset;
backdrop-filter: blur(20px); backdrop-filter: blur(18px);
} }
input:not([type="checkbox"]):not([type="radio"]):focus, input:not([type="checkbox"]):not([type="radio"]):focus,
textarea:focus, textarea:focus,
select:focus { select:focus {
background-color: var(--window-bg-strong); background-color: var(--card-bg-strong);
border-color: var(--color-accent); border-color: var(--color-accent);
} }
@@ -330,7 +438,7 @@ html[data-theme="dark"] .hover\:bg-gray-50:hover,
html[data-theme="dark"] .hover\:bg-gray-100:hover, html[data-theme="dark"] .hover\:bg-gray-100:hover,
html[data-theme="dark"] .hover\:bg-gray-200:hover, html[data-theme="dark"] .hover\:bg-gray-200:hover,
html[data-theme="dark"] .focus\:bg-white:focus { html[data-theme="dark"] .focus\:bg-white:focus {
background-color: rgba(255, 255, 255, 0.11); background-color: var(--card-bg-strong);
} }
html[data-theme="dark"] .hover\:bg-blue-50:hover { html[data-theme="dark"] .hover\:bg-blue-50:hover {
@@ -351,44 +459,45 @@ html[data-theme="dark"] .disabled\:bg-gray-400:disabled {
html[data-theme="dark"] input:not([type="checkbox"]):not([type="radio"]), html[data-theme="dark"] input:not([type="checkbox"]):not([type="radio"]),
html[data-theme="dark"] textarea, html[data-theme="dark"] textarea,
html[data-theme="dark"] select { html[data-theme="dark"] select {
background-color: rgba(255, 255, 255, 0.08); background-color: var(--color-control);
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.08) inset;
} }
html[data-theme="dark"] input:not([type="checkbox"]):not([type="radio"]):focus, html[data-theme="dark"] input:not([type="checkbox"]):not([type="radio"]):focus,
html[data-theme="dark"] textarea:focus, html[data-theme="dark"] textarea:focus,
html[data-theme="dark"] select:focus { html[data-theme="dark"] select:focus {
background-color: rgba(255, 255, 255, 0.11); background-color: var(--card-bg-strong);
} }
.w-md-editor { .w-md-editor {
border-radius: 0.5rem !important; border-radius: 0.5rem !important;
border-color: var(--color-line) !important; border-color: var(--card-border) !important;
background-color: var(--window-bg-strong) !important; background-color: var(--card-bg-strong) !important;
box-shadow: var(--shadow-card); box-shadow: var(--shadow-card);
backdrop-filter: blur(24px); backdrop-filter: blur(20px);
} }
.w-md-editor-toolbar { .w-md-editor-toolbar {
border-radius: 0.5rem 0.5rem 0 0 !important; border-radius: 0.5rem 0.5rem 0 0 !important;
border-color: var(--color-line) !important; border-color: var(--window-titlebar-border) !important;
background-color: var(--window-titlebar) !important; background-color: var(--window-titlebar) !important;
} }
html[data-theme="dark"] .w-md-editor { html[data-theme="dark"] .w-md-editor {
background-color: var(--window-bg-strong) !important; background-color: var(--card-bg-strong) !important;
border-color: var(--color-line) !important; border-color: var(--card-border) !important;
} }
html[data-theme="dark"] .w-md-editor-toolbar { html[data-theme="dark"] .w-md-editor-toolbar {
background-color: var(--window-titlebar) !important; background-color: var(--window-titlebar) !important;
border-color: var(--color-line) !important; border-color: var(--window-titlebar-border) !important;
} }
.wy-editor-shell { .wy-editor-shell {
--color-canvas-default: transparent; --color-canvas-default: transparent;
--color-canvas-subtle: transparent; --color-canvas-subtle: transparent;
--color-border-default: var(--color-line); --color-border-default: var(--card-border);
--color-border-muted: var(--color-line); --color-border-muted: var(--card-border);
--color-fg-default: var(--color-text); --color-fg-default: var(--color-text);
--color-fg-muted: var(--color-text-muted); --color-fg-muted: var(--color-text-muted);
--color-accent-fg: var(--color-accent); --color-accent-fg: var(--color-accent);
@@ -399,14 +508,15 @@ html[data-theme="dark"] .w-md-editor-toolbar {
min-height: 520px; min-height: 520px;
overflow: hidden; overflow: hidden;
border-radius: 0.5rem !important; border-radius: 0.5rem !important;
border: 1px solid var(--color-line) !important; border: 1px solid var(--card-border) !important;
background-color: var(--window-bg-strong) !important; background-color: var(--card-bg-strong) !important;
color: var(--color-text) !important; color: var(--color-text) !important;
box-shadow: var(--shadow-card) !important; box-shadow: var(--shadow-card) !important;
backdrop-filter: blur(20px);
} }
.wy-editor-shell .w-md-editor-toolbar { .wy-editor-shell .w-md-editor-toolbar {
border-color: var(--color-line) !important; border-color: var(--window-titlebar-border) !important;
background-color: var(--window-titlebar) !important; background-color: var(--window-titlebar) !important;
} }

View File

@@ -5,6 +5,7 @@ import './globals.css';
import Providers from './providers'; import Providers from './providers';
import DesktopShell from '@/components/layout/DesktopShell'; import DesktopShell from '@/components/layout/DesktopShell';
import { THEME_INIT_SCRIPT } from '@/components/theme/theme'; import { THEME_INIT_SCRIPT } from '@/components/theme/theme';
import { DEFAULT_DESCRIPTION, SITE_NAME, SITE_URL } from '@/lib/site';
const pretendard = localFont({ const pretendard = localFont({
src: './fonts/PretendardVariable.woff2', src: './fonts/PretendardVariable.woff2',
@@ -14,8 +15,23 @@ const pretendard = localFont({
}); });
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'WYPark Blog', metadataBase: new URL(SITE_URL),
description: '개발 블로그', title: {
default: SITE_NAME,
template: `%s | ${SITE_NAME}`,
},
description: DEFAULT_DESCRIPTION,
alternates: {
canonical: '/',
},
openGraph: {
title: SITE_NAME,
description: DEFAULT_DESCRIPTION,
url: '/',
siteName: SITE_NAME,
type: 'website',
locale: 'ko_KR',
},
}; };
export default function RootLayout({ export default function RootLayout({
@@ -54,3 +70,4 @@ export default function RootLayout({
</html> </html>
); );
} }

View File

@@ -3,7 +3,7 @@
import { Suspense, useState } from 'react'; import { Suspense, useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation'; import { useRouter, useSearchParams } from 'next/navigation';
import { Loader2 } from 'lucide-react'; import { Loader2, LockKeyhole, UserRound } from 'lucide-react';
import { login } from '@/api/auth'; import { login } from '@/api/auth';
import WindowSurface from '@/components/ui/WindowSurface'; import WindowSurface from '@/components/ui/WindowSurface';
import { useAuthStore } from '@/store/authStore'; import { useAuthStore } from '@/store/authStore';
@@ -61,12 +61,15 @@ function LoginForm() {
return ( return (
<div className="flex min-h-[calc(100vh-14rem)] items-center justify-center px-1 py-8"> <div className="flex min-h-[calc(100vh-14rem)] items-center justify-center px-1 py-8">
<WindowSurface <WindowSurface
title="Login" title="Login Window"
subtitle="WYPark OS" subtitle="WYPark OS"
className="w-full max-w-md" className="w-full max-w-md"
bodyClassName="p-8" bodyClassName="p-8"
> >
<div className="mb-8 text-center"> <div className="mb-8 text-center">
<div className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-2xl border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-card)]">
<UserRound size={34} strokeWidth={1.9} />
</div>
<h1 className="text-3xl font-bold text-[var(--color-text)]"></h1> <h1 className="text-3xl font-bold text-[var(--color-text)]"></h1>
<p className="mt-2 text-[var(--color-text-muted)]"> .</p> <p className="mt-2 text-[var(--color-text-muted)]"> .</p>
</div> </div>
@@ -103,7 +106,7 @@ function LoginForm() {
disabled={loading} disabled={loading}
className="flex w-full items-center justify-center gap-2 rounded-lg bg-[var(--color-accent)] py-3 font-bold text-white transition-colors hover:bg-[var(--color-accent-hover)] disabled:cursor-not-allowed disabled:opacity-60" className="flex w-full items-center justify-center gap-2 rounded-lg bg-[var(--color-accent)] py-3 font-bold text-white transition-colors hover:bg-[var(--color-accent-hover)] disabled:cursor-not-allowed disabled:opacity-60"
> >
{loading && <Loader2 className="animate-spin" size={20} />} {loading ? <Loader2 className="animate-spin" size={20} /> : <LockKeyhole size={18} />}
</button> </button>
</form> </form>

View File

@@ -1,27 +1,52 @@
'use client'; import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { Suspense, type ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { import {
Archive, Archive,
ChevronRight, ChevronRight,
Clock, Clock,
Loader2, FileText,
HardDrive,
Search, Search,
TrendingUp, TrendingUp,
} from 'lucide-react'; } from 'lucide-react';
import { getPosts } from '@/api/posts'; import { fetchPublicPosts } from '@/api/publicPosts';
import EmptyState from '@/components/ui/EmptyState'; import EmptyState from '@/components/ui/EmptyState';
import StatusBadge from '@/components/ui/StatusBadge'; import StatusBadge from '@/components/ui/StatusBadge';
import Surface from '@/components/ui/Surface'; import Surface from '@/components/ui/Surface';
import WindowSurface from '@/components/ui/WindowSurface'; import WindowSurface from '@/components/ui/WindowSurface';
import { DEFAULT_DESCRIPTION, SITE_NAME } from '@/lib/site';
import { Post, PostListResponse } from '@/types'; import { Post, PostListResponse } from '@/types';
export const dynamic = 'force-dynamic';
export const revalidate = 300;
export const metadata: Metadata = {
title: {
absolute: SITE_NAME,
},
description: DEFAULT_DESCRIPTION,
alternates: {
canonical: '/',
},
openGraph: {
title: SITE_NAME,
description: DEFAULT_DESCRIPTION,
url: '/',
siteName: SITE_NAME,
type: 'website',
},
};
type HomePageProps = {
searchParams?: Promise<Record<string, string | string[] | undefined>>;
};
const isNoticePost = (post: Post) => { const isNoticePost = (post: Post) => {
const categoryName = post.categoryName || ''; const categoryName = post.categoryName || '';
return categoryName === '공지' || categoryName === '怨듭?' || categoryName.toLowerCase() === 'notice'; const normalizedName = categoryName.toLowerCase();
return categoryName === '공지' || normalizedName === 'notice' || normalizedName === 'announcement';
}; };
const formatDate = (value?: string) => { const formatDate = (value?: string) => {
@@ -50,47 +75,53 @@ const getSummary = (content?: string, maxLength = 118) => {
.slice(0, maxLength); .slice(0, maxLength);
}; };
const getTotalElements = (data?: PostListResponse) => { const getTotalElements = (data?: PostListResponse | null) => {
return data?.page?.totalElements ?? data?.totalElements ?? 0; return data?.page?.totalElements ?? data?.totalElements ?? 0;
}; };
const getSearchKeyword = async (searchParams?: HomePageProps['searchParams']) => {
const resolvedSearchParams = searchParams ? await searchParams : {};
const keyword = resolvedSearchParams.keyword;
return Array.isArray(keyword) ? keyword[0] || '' : keyword || '';
};
function SearchResults({ function SearchResults({
keyword, keyword,
data, data,
isLoading,
}: { }: {
keyword: string; keyword: string;
data?: PostListResponse; data?: PostListResponse | null;
isLoading: boolean;
}) { }) {
const searchResults = data?.content || []; const searchResults = data?.content || [];
const searchTotalElements = getTotalElements(data); const searchTotalElements = getTotalElements(data);
return ( return (
<WindowSurface <WindowSurface
title="Search" title="Spotlight"
subtitle={`"${keyword}"`} subtitle={`"${keyword}"`}
bodyClassName="p-5 md:p-6" bodyClassName="p-0"
className="animate-in fade-in slide-in-from-bottom-2 duration-300" className="animate-in fade-in slide-in-from-bottom-2 duration-300"
> >
<div className="mb-6 flex flex-col gap-2 border-b border-[var(--color-line)] pb-5"> <div className="border-b border-[var(--color-line)] bg-[var(--window-titlebar)] px-4 py-4 md:px-6">
<div className="flex items-center gap-2 text-[var(--color-accent)]"> <div className="flex min-w-0 items-center gap-3">
<Search size={22} /> <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-control)]">
<h1 className="text-2xl font-bold tracking-normal text-[var(--color-text)]"> <Search size={20} />
</div>
<div className="min-w-0">
<h1 className="min-w-0 break-words text-2xl font-bold tracking-normal text-[var(--color-text)]">
</h1> </h1>
</div> <p className="break-words text-sm text-[var(--color-text-muted)]">
<p className="text-sm text-[var(--color-text-muted)]">
<span className="font-semibold text-[var(--color-text)]">{keyword}</span> {searchTotalElements.toLocaleString()} <span className="font-semibold text-[var(--color-text)]">{keyword}</span> {searchTotalElements.toLocaleString()}
</p> </p>
</div> </div>
{isLoading ? (
<div className="flex min-h-60 items-center justify-center">
<Loader2 className="animate-spin text-[var(--color-accent)]" size={30} />
</div> </div>
) : searchResults.length > 0 ? ( </div>
<div className="divide-y divide-[var(--color-line)]">
<div className="p-4 md:p-6">
{searchResults.length > 0 ? (
<div className="divide-y divide-[var(--color-line)] rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] px-2">
{searchResults.map((post) => ( {searchResults.map((post) => (
<CompactPostRow key={post.id} post={post} /> <CompactPostRow key={post.id} post={post} />
))} ))}
@@ -98,6 +129,7 @@ function SearchResults({
) : ( ) : (
<EmptyState title="검색 결과가 없습니다." description="다른 키워드로 다시 찾아보세요." /> <EmptyState title="검색 결과가 없습니다." description="다른 키워드로 다시 찾아보세요." />
)} )}
</div>
</WindowSurface> </WindowSurface>
); );
} }
@@ -108,19 +140,19 @@ function NoticeStrip({ notices }: { notices: Post[] }) {
return ( return (
<section className="space-y-2" aria-label="공지"> <section className="space-y-2" aria-label="공지">
{notices.slice(0, 3).map((notice) => ( {notices.slice(0, 3).map((notice) => (
<Link key={notice.id} href={`/posts/${notice.slug}`} className="group block"> <Link key={notice.id} href={`/posts/${notice.slug}`} className="group block min-w-0">
<Surface <Surface
interactive interactive
className="flex items-center justify-between gap-4 border-red-500/10 bg-red-500/[0.045] px-4 py-3 shadow-none" className="flex min-w-0 items-center justify-between gap-3 border-red-500/10 bg-red-500/[0.045] px-4 py-3 shadow-none"
> >
<div className="flex min-w-0 items-center gap-3"> <div className="flex min-w-0 items-center gap-3">
<StatusBadge tone="danger"></StatusBadge> <StatusBadge tone="danger" className="shrink-0"></StatusBadge>
<span className="truncate text-sm font-semibold text-[var(--color-text)]"> <span className="min-w-0 truncate text-sm font-semibold text-[var(--color-text)]">
{notice.title} {notice.title}
</span> </span>
</div> </div>
<div className="flex shrink-0 items-center gap-2 text-xs font-medium text-[var(--color-text-subtle)]"> <div className="flex shrink-0 items-center gap-2 text-xs font-medium text-[var(--color-text-subtle)]">
<time>{formatDate(notice.createdAt)}</time> <time className="hidden sm:inline">{formatDate(notice.createdAt)}</time>
<ChevronRight size={15} className="transition group-hover:translate-x-0.5" /> <ChevronRight size={15} className="transition group-hover:translate-x-0.5" />
</div> </div>
</Surface> </Surface>
@@ -134,42 +166,52 @@ function CompactPostRow({
post, post,
rank, rank,
showViews = false, showViews = false,
featured = false,
}: { }: {
post: Post; post: Post;
rank?: number; rank?: number;
showViews?: boolean; showViews?: boolean;
featured?: boolean;
}) { }) {
const summary = getSummary(post.content, 92); const summary = getSummary(post.content, featured ? 150 : 92);
return ( return (
<Link <Link
href={`/posts/${post.slug}`} href={`/posts/${post.slug}`}
className="group flex items-start justify-between gap-4 rounded-lg px-1 py-4 transition duration-150 hover:bg-black/[0.025] hover:px-3 dark:hover:bg-white/[0.07]" className={clsxSafe(
'group flex min-w-0 items-start justify-between gap-3 rounded-lg px-1 py-4 transition duration-150 hover:bg-[var(--card-bg)] hover:px-3',
featured && 'md:py-5',
)}
> >
{rank !== undefined && ( {rank !== undefined && (
<span className="mt-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--color-accent-soft)] text-xs font-bold tabular-nums text-[var(--color-accent)]"> <span className="mt-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[var(--color-accent-soft)] text-xs font-bold tabular-nums text-[var(--color-accent)]">
{rank} {rank}
</span> </span>
)} )}
{rank === undefined && (
<span className="mt-1 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-control)]">
<FileText size={17} />
</span>
)}
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="mb-1.5 flex items-center gap-2"> <div className="mb-1.5 flex min-w-0 flex-wrap items-center gap-2">
<StatusBadge tone={isNoticePost(post) ? 'danger' : 'neutral'} className="shrink-0"> <StatusBadge tone={isNoticePost(post) ? 'danger' : 'neutral'} className="shrink-0">
{post.categoryName || '미분류'} {post.categoryName || '미분류'}
</StatusBadge> </StatusBadge>
<time className="text-xs text-[var(--color-text-subtle)]"> <time className="shrink-0 text-xs text-[var(--color-text-subtle)]">
{formatDate(post.createdAt)} {formatDate(post.createdAt)}
</time> </time>
{showViews && ( {showViews && (
<span className="text-xs tabular-nums text-[var(--color-text-subtle)]"> <span className="shrink-0 text-xs tabular-nums text-[var(--color-text-subtle)]">
{post.viewCount.toLocaleString()} {post.viewCount.toLocaleString()}
</span> </span>
)} )}
</div> </div>
<h3 className="line-clamp-1 text-base font-semibold text-[var(--color-text)] transition group-hover:text-[var(--color-accent)]"> <h3 className="line-clamp-2 break-words text-base font-semibold text-[var(--color-text)] transition group-hover:text-[var(--color-accent)]">
{post.title} {post.title}
</h3> </h3>
{summary && ( {summary && (
<p className="mt-1 line-clamp-2 text-sm leading-6 text-[var(--color-text-muted)]"> <p className="mt-1 line-clamp-2 break-words text-sm leading-6 text-[var(--color-text-muted)]">
{summary} {summary}
</p> </p>
)} )}
@@ -179,25 +221,26 @@ function CompactPostRow({
); );
} }
function clsxSafe(...classes: Array<string | false | undefined>) {
return classes.filter(Boolean).join(' ');
}
function PostListPanel({ function PostListPanel({
title, title,
icon, icon,
posts, posts,
isPopular = false, isPopular = false,
featured = false,
}: { }: {
title: string; title: string;
icon: ReactNode; icon: ReactNode;
posts: Post[]; posts: Post[];
isPopular?: boolean; isPopular?: boolean;
featured?: boolean;
}) { }) {
return ( return (
<WindowSurface <Surface as="section" strong className="min-w-0 overflow-hidden shadow-none">
as="section" <div className="flex min-h-12 min-w-0 items-center justify-between gap-3 border-b border-[var(--window-titlebar-border)] bg-[var(--window-titlebar)] px-4 py-3 md:px-5">
showTrafficLights={false}
className="shadow-none"
bodyClassName="overflow-hidden"
>
<div className="flex min-h-12 items-center justify-between gap-3 border-b border-[var(--color-line)] bg-white/[0.16] px-5 py-3 dark:bg-white/[0.04]">
<h2 className="flex min-w-0 items-center gap-2 text-sm font-bold text-[var(--color-text)]"> <h2 className="flex min-w-0 items-center gap-2 text-sm font-bold text-[var(--color-text)]">
{icon} {icon}
<span className="truncate">{title}</span> <span className="truncate">{title}</span>
@@ -208,7 +251,7 @@ function PostListPanel({
</Link> </Link>
</div> </div>
<div className="p-5 md:p-6"> <div className="p-4 md:p-6">
{posts.length > 0 ? ( {posts.length > 0 ? (
<div className="divide-y divide-[var(--color-line)]"> <div className="divide-y divide-[var(--color-line)]">
{posts.map((post, index) => ( {posts.map((post, index) => (
@@ -217,6 +260,7 @@ function PostListPanel({
post={post} post={post}
rank={isPopular ? index + 1 : undefined} rank={isPopular ? index + 1 : undefined}
showViews={isPopular} showViews={isPopular}
featured={featured}
/> />
))} ))}
</div> </div>
@@ -224,106 +268,84 @@ function PostListPanel({
<EmptyState title={isPopular ? '인기 글을 집계 중입니다.' : '아직 공개된 글이 없습니다.'} className="min-h-72" /> <EmptyState title={isPopular ? '인기 글을 집계 중입니다.' : '아직 공개된 글이 없습니다.'} className="min-h-72" />
)} )}
</div> </div>
</WindowSurface> </Surface>
); );
} }
function HomeContent() { export default async function Home({ searchParams }: HomePageProps) {
const searchParams = useSearchParams(); const keyword = await getSearchKeyword(searchParams);
const keyword = searchParams.get('keyword') || '';
const { data: noticesData, isLoading: isNoticesLoading } = useQuery({
queryKey: ['posts', 'notices'],
queryFn: () => getPosts({ category: '공지', size: 3, sort: 'createdAt,desc' }),
retry: 0,
});
const { data: latestData, isLoading: isLatestLoading } = useQuery({
queryKey: ['posts', 'latest'],
queryFn: () => getPosts({ size: 8, sort: 'createdAt,desc' }),
retry: 0,
});
const { data: popularData, isLoading: isPopularLoading } = useQuery({
queryKey: ['posts', 'popular'],
queryFn: () => getPosts({ size: 8, sort: 'viewCount,desc' }),
retry: 0,
});
const { data: searchData, isLoading: isSearchLoading } = useQuery({
queryKey: ['posts', 'search', keyword],
queryFn: () => getPosts({ keyword, size: 20 }),
enabled: !!keyword,
retry: 0,
});
const notices = noticesData?.content || [];
const latestList = (latestData?.content || []).filter((post) => !isNoticePost(post)).slice(0, 5);
const popularList = (popularData?.content || []).filter((post) => !isNoticePost(post)).slice(0, 5);
const isHomeLoading = !keyword && (isNoticesLoading || isLatestLoading || isPopularLoading);
if (keyword) { if (keyword) {
const searchData = await fetchPublicPosts({ keyword, size: 20 });
return ( return (
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6"> <main className="mx-auto min-w-0 max-w-[1180px] px-0 py-3 md:py-6">
<SearchResults keyword={keyword} data={searchData} isLoading={isSearchLoading} /> <SearchResults keyword={keyword} data={searchData} />
</main> </main>
); );
} }
if (isHomeLoading) { const [noticesData, latestData, popularData] = await Promise.all([
return ( fetchPublicPosts({ category: '공지', size: 3, sort: 'createdAt,desc' }),
<div className="flex min-h-[60vh] items-center justify-center"> fetchPublicPosts({ size: 10, sort: 'createdAt,desc' }),
<Loader2 className="animate-spin text-[var(--color-accent)]" size={36} /> fetchPublicPosts({ size: 8, sort: 'viewCount,desc' }),
</div> ]);
);
} const notices = noticesData?.content || [];
const latestList = (latestData?.content || []).filter((post) => !isNoticePost(post)).slice(0, 7);
const popularList = (popularData?.content || []).filter((post) => !isNoticePost(post)).slice(0, 5);
return ( return (
<main className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6"> <main className="mx-auto min-w-0 max-w-[1180px] px-0 py-3 md:py-6">
<h1 className="sr-only">WYPark Blog</h1> <h1 className="sr-only">{SITE_NAME}</h1>
<WindowSurface <WindowSurface
title="WYPark" title="WYPark"
subtitle="블로그 라이브러리"
controls={( controls={(
<Link <Link
href="/archive" href="/archive"
className="inline-flex h-8 items-center gap-2 rounded-full bg-[var(--color-text)] px-3 text-xs font-semibold text-[var(--color-page)] shadow-[var(--shadow-control)] transition hover:opacity-90 dark:bg-white dark:text-black" className="inline-flex h-8 min-w-0 items-center gap-2 rounded-full bg-[var(--color-text)] px-3 text-xs font-semibold text-[var(--color-page)] shadow-[var(--shadow-control)] transition hover:opacity-90 dark:bg-white dark:text-black"
> >
<span className="hidden sm:inline"> </span>
<Archive size={14} /> <Archive size={14} />
</Link> </Link>
)} )}
bodyClassName="space-y-6 p-4 md:p-6" bodyClassName="space-y-6 p-4 md:p-6"
> >
<div className="flex min-w-0 flex-col justify-between gap-3 rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] px-4 py-3 md:flex-row md:items-center">
<div className="flex min-w-0 items-center gap-3">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-control)]">
<HardDrive size={20} />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-bold text-[var(--color-text)]"> </p>
<p className="truncate text-xs text-[var(--color-text-subtle)]">
{latestList.length.toLocaleString()} · {popularList.length.toLocaleString()}
</p>
</div>
</div>
<span className="text-xs font-semibold tabular-nums text-[var(--color-text-subtle)]">
{new Intl.DateTimeFormat('ko-KR', { dateStyle: 'medium' }).format(new Date())}
</span>
</div>
<NoticeStrip notices={notices} /> <NoticeStrip notices={notices} />
<section className="grid gap-6 lg:grid-cols-2"> <section className="grid min-w-0 gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(280px,360px)]">
<PostListPanel
title="인기 글"
icon={<TrendingUp size={18} className="text-[var(--color-accent)]" />}
posts={popularList}
isPopular
/>
<PostListPanel <PostListPanel
title="최신 글" title="최신 글"
icon={<Clock size={18} className="text-[var(--color-accent)]" />} icon={<Clock size={18} className="shrink-0 text-[var(--color-accent)]" />}
posts={latestList} posts={latestList}
featured
/>
<PostListPanel
title="인기 글"
icon={<TrendingUp size={18} className="shrink-0 text-[var(--color-accent)]" />}
posts={popularList}
isPopular
/> />
</section> </section>
</WindowSurface> </WindowSurface>
</main> </main>
); );
} }
export default function Home() {
return (
<Suspense
fallback={(
<div className="flex min-h-[60vh] items-center justify-center">
<Loader2 className="animate-spin text-[var(--color-accent)]" size={36} />
</div>
)}
>
<HomeContent />
</Suspense>
);
}

View File

@@ -3,7 +3,7 @@ import ChessPuzzleClient from '@/components/chess/ChessPuzzleClient';
export const metadata: Metadata = { export const metadata: Metadata = {
title: '오늘의 체스 퍼즐 | WYPark Blog', title: '오늘의 체스 퍼즐 | WYPark Blog',
description: '오늘의 한 수 메이트 체스 퍼즐', description: '오늘의 메이트 체스 퍼즐',
}; };
export default function ChessPuzzlePage() { export default function ChessPuzzlePage() {

View File

@@ -1,87 +1,90 @@
import { Metadata } from 'next'; import { Metadata } from 'next';
import PostDetailClient from '@/components/post/PostDetailClient';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { Post } from '@/types'; import { fetchPublicPost } from '@/api/publicPosts';
import PostDetailClient from '@/components/post/PostDetailClient';
import { DEFAULT_DESCRIPTION, getCanonicalUrl, parseApiDate, SITE_NAME, SITE_URL } from '@/lib/site';
type Props = { type Props = {
params: Promise<{ slug: string }>; params: Promise<{ slug: string }>;
}; };
// 🛠️ 서버 사이드 데이터 패칭 함수 (Metadata와 Page 양쪽에서 재사용) const getPostDescription = (content?: string) => {
async function getPostFromServer(slug: string): Promise<Post | null> { const plainText = content
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080'; ?.replace(/```[\s\S]*?```/g, ' ')
.replace(/!\[(.*?)\]\(.*?\)/g, '$1')
.replace(/\[(.*?)\]\(.*?\)/g, '$1')
.replace(/[#*`_~>]/g, '')
.replace(/\s+/g, ' ')
.trim();
if (!plainText) return DEFAULT_DESCRIPTION;
return plainText.length > 150 ? `${plainText.slice(0, 150)}...` : plainText;
};
const getFirstMarkdownImage = (content?: string) => {
const imageMatch = content?.match(/!\[.*?\]\((.*?)\)/);
const imageUrl = imageMatch?.[1]?.split(/\s+/)[0] || '/og-image.png';
try { try {
const res = await fetch(`${BASE_URL}/api/posts/${slug}`, { return new URL(imageUrl, SITE_URL).toString();
// 캐시 설정: 60초마다 갱신 (블로그 특성상 적절) } catch {
// 즉시 반영이 필요하다면 'no-store'로 설정하거나 revalidate: 0 사용 return new URL('/og-image.png', SITE_URL).toString();
next: { revalidate: 60 },
});
if (!res.ok) return null;
const json = await res.json();
return json.data;
} catch (error) {
console.error('Server fetch error:', error);
return null;
}
} }
};
// 🌟 메타데이터 생성 (SEO)
export async function generateMetadata({ params }: Props): Promise<Metadata> { export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params; const { slug } = await params;
const post = await getPostFromServer(slug); const post = await fetchPublicPost(slug);
const canonicalUrl = getCanonicalUrl(`/posts/${encodeURIComponent(post?.slug || slug)}`);
if (!post) { if (!post) {
return { return {
title: '게시글을 찾을 수 없습니다', title: '게시글을 찾을 수 없습니다',
alternates: {
canonical: canonicalUrl,
},
}; };
} }
// 본문 요약 및 이미지 추출 로직 const description = getPostDescription(post.content);
const description = post.content const imageUrl = getFirstMarkdownImage(post.content);
?.replace(/[#*`_~]/g, '') const publishedTime = parseApiDate(post.createdAt).toISOString();
.replace(/\n/g, ' ') const modifiedTime = parseApiDate(post.updatedAt || post.createdAt).toISOString();
.substring(0, 150) + '...';
const imageMatch = post.content?.match(/!\[.*?\]\((.*?)\)/);
const imageUrl = imageMatch ? imageMatch[1] : '/og-image.png';
return { return {
title: post.title, title: post.title,
description: description, description,
alternates: {
canonical: canonicalUrl,
},
openGraph: { openGraph: {
title: post.title, title: post.title,
description: description, description,
url: `https://blog.wypark.me/posts/${slug}`, url: canonicalUrl,
siteName: 'WYPark Blog', siteName: SITE_NAME,
images: [{ url: imageUrl, width: 1200, height: 630 }], images: [{ url: imageUrl, width: 1200, height: 630 }],
type: 'article', type: 'article',
publishedTime: post.createdAt, // created_at 대신 createdAt 사용 주의 (타입 정의 따름) publishedTime,
modifiedTime,
authors: ['WYPark'], authors: ['WYPark'],
}, },
twitter: { twitter: {
card: 'summary_large_image', card: 'summary_large_image',
title: post.title, title: post.title,
description: description, description,
images: [imageUrl], images: [imageUrl],
}, },
}; };
} }
// 🌟 실제 페이지 렌더링 (SSR 적용)
export default async function PostDetailPage({ params }: Props) { export default async function PostDetailPage({ params }: Props) {
const { slug } = await params; const { slug } = await params;
const post = await fetchPublicPost(slug);
// 1. 서버에서 데이터를 미리 가져옵니다.
const post = await getPostFromServer(slug);
// 2. 데이터가 없으면 404 페이지로 보냅니다. (봇에게도 404 신호를 줌)
if (!post) { if (!post) {
notFound(); notFound();
} }
// 3. 가져온 데이터를 클라이언트 컴포넌트에 'initialPost'로 넘겨줍니다.
return <PostDetailClient slug={slug} initialPost={post} />; return <PostDetailClient slug={slug} initialPost={post} />;
} }

View File

@@ -1,16 +1,14 @@
import { MetadataRoute } from 'next'; import { MetadataRoute } from 'next';
import { SITE_URL } from '@/lib/site';
export default function robots(): MetadataRoute.Robots { export default function robots(): MetadataRoute.Robots {
const baseUrl = 'https://blog.wypark.me';
return { return {
rules: { rules: {
userAgent: '*', userAgent: '*',
allow: '/', allow: '/',
// 검색 로봇이 굳이 긁어갈 필요 없는 페이지들은 차단 (글쓰기, 로그인 등)
disallow: ['/write', '/login', '/signup', '/admin'], disallow: ['/write', '/login', '/signup', '/admin'],
}, },
// 여기서 동적으로 생성된 sitemap.xml을 가리킵니다. sitemap: `${SITE_URL}/sitemap.xml`,
sitemap: `${baseUrl}/sitemap.xml`,
}; };
} }

View File

@@ -4,6 +4,7 @@ import { useState } from 'react';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import Link from 'next/link'; import Link from 'next/link';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { MailCheck, UserPlus } from 'lucide-react';
import { signup, verifyEmail } from '@/api/auth'; import { signup, verifyEmail } from '@/api/auth';
import WindowSurface from '@/components/ui/WindowSurface'; import WindowSurface from '@/components/ui/WindowSurface';
import { SignupRequest } from '@/types'; import { SignupRequest } from '@/types';
@@ -74,12 +75,15 @@ export default function SignupPage() {
return ( return (
<div className="flex min-h-[calc(100vh-14rem)] items-center justify-center px-1 py-8"> <div className="flex min-h-[calc(100vh-14rem)] items-center justify-center px-1 py-8">
<WindowSurface <WindowSurface
title="Signup" title="Account Setup"
subtitle={step === 'FORM' ? 'Create account' : registeredEmail} subtitle={step === 'FORM' ? 'Create account' : registeredEmail}
className="w-full max-w-md" className="w-full max-w-md"
bodyClassName="p-8" bodyClassName="p-8"
> >
<div className="mb-8 text-center"> <div className="mb-8 text-center">
<div className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-2xl border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-card)]">
{step === 'FORM' ? <UserPlus size={34} strokeWidth={1.9} /> : <MailCheck size={34} strokeWidth={1.9} />}
</div>
<h1 className="text-2xl font-bold text-[var(--color-text)]"></h1> <h1 className="text-2xl font-bold text-[var(--color-text)]"></h1>
<p className="mt-2 text-sm text-[var(--color-text-muted)]"> <p className="mt-2 text-sm text-[var(--color-text-muted)]">
{step === 'FORM' ? '블로그 OS 계정을 만듭니다.' : '이메일로 전송된 6자리 코드를 입력하세요.'} {step === 'FORM' ? '블로그 OS 계정을 만듭니다.' : '이메일로 전송된 6자리 코드를 입력하세요.'}

View File

@@ -1,60 +1,40 @@
import { MetadataRoute } from 'next'; import { MetadataRoute } from 'next';
import {
fetchPublicPosts,
} from '@/api/publicPosts';
import { parseApiDate, SITE_URL } from '@/lib/site';
interface SitemapPost { export const dynamic = 'force-dynamic';
slug: string; export const revalidate = 300;
updatedAt?: string;
createdAt?: string;
}
export default async function sitemap(): Promise<MetadataRoute.Sitemap> { export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const baseUrl = 'https://blog.wypark.me'; const generatedAt = new Date();
// API 주소 환경변수 사용 (없으면 로컬)
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
// 1. 고정된 정적 페이지들
const routes: MetadataRoute.Sitemap = [ const routes: MetadataRoute.Sitemap = [
{ {
url: baseUrl, url: SITE_URL,
lastModified: new Date(), lastModified: generatedAt,
changeFrequency: 'daily', changeFrequency: 'daily',
priority: 1, priority: 1,
}, },
{ {
url: `${baseUrl}/archive`, url: `${SITE_URL}/archive`,
lastModified: new Date(), lastModified: generatedAt,
changeFrequency: 'daily', changeFrequency: 'daily',
priority: 0.8, priority: 0.8,
}, },
]; ];
try { const postsData = await fetchPublicPosts({ size: 1000, sort: 'createdAt,desc' });
// 2. API에서 게시글 목록 가져오기 const posts = postsData?.content || [];
const response = await fetch(`${apiUrl}/api/posts?size=1000&sort=createdAt,desc`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
next: { revalidate: 3600 }
});
if (!response.ok) { const postRoutes: MetadataRoute.Sitemap = posts
throw new Error('Failed to fetch posts'); .filter((post) => post.slug)
} .map((post) => ({
url: `${SITE_URL}/posts/${encodeURIComponent(post.slug)}`,
const json = await response.json() as { data?: { content?: SitemapPost[] } }; lastModified: parseApiDate(post.updatedAt || post.createdAt, generatedAt),
const posts = json.data?.content || []; changeFrequency: 'weekly',
// 3. 게시글 데이터를 사이트맵 형식으로 변환
const postRoutes = posts.map((post) => ({
// 🛠️ 핵심 수정: slug를 encodeURIComponent로 감싸서 특수문자(&, 한글 등)를 안전하게 처리합니다.
url: `${baseUrl}/posts/${encodeURIComponent(post.slug)}`,
lastModified: new Date(post.updatedAt || post.createdAt || Date.now()),
changeFrequency: 'weekly' as const,
priority: 0.8, priority: 0.8,
})); }));
return [...routes, ...postRoutes]; return [...routes, ...postRoutes];
} catch (error) {
console.error('Sitemap generation error:', error);
return routes;
}
} }

View File

@@ -111,7 +111,7 @@ function CategoryOptions({
{categories.map((category) => ( {categories.map((category) => (
<div key={category.id}> <div key={category.id}>
<label <label
className="flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--color-text-muted)] transition hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10" className="flex cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--color-text-muted)] transition hover:bg-[var(--card-bg)] hover:text-[var(--color-text)]"
style={{ marginLeft: `${depth * 10}px` }} style={{ marginLeft: `${depth * 10}px` }}
> >
<input <input
@@ -167,7 +167,7 @@ function DraftLoadDialog({
<button <button
type="button" type="button"
onClick={onCancel} onClick={onCancel}
className="inline-flex items-center justify-center rounded-full border border-[var(--color-line)] bg-[var(--color-control)] px-4 py-2 text-sm font-semibold text-[var(--color-text-muted)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)]" className="inline-flex items-center justify-center rounded-full border border-[var(--control-border)] bg-[var(--color-control)] px-4 py-2 text-sm font-semibold text-[var(--color-text-muted)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
> >
</button> </button>
@@ -471,7 +471,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
} }
return ( return (
<main className="mx-auto w-full px-0 py-4 md:w-[80vw] md:max-w-[1400px] md:py-6" onPaste={handlePaste}> <main className="w-full min-w-0" onPaste={handlePaste}>
<WindowSurface <WindowSurface
title={isEditMode ? '글 수정' : '새 글 작성'} title={isEditMode ? '글 수정' : '새 글 작성'}
subtitle="Markdown Studio" subtitle="Markdown Studio"
@@ -479,7 +479,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
<button <button
type="button" type="button"
onClick={() => router.push('/admin/posts')} onClick={() => router.push('/admin/posts')}
className="inline-flex h-8 items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-control)] px-3 text-xs font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)]" className="inline-flex h-8 items-center gap-2 rounded-full border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-xs font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
> >
<ArrowLeft size={14} /> <ArrowLeft size={14} />
@@ -502,7 +502,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
<button <button
type="button" type="button"
onClick={handleTempSave} onClick={handleTempSave}
className="inline-flex h-9 items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-control)] px-4 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)]" className="inline-flex h-9 items-center gap-2 rounded-full border border-[var(--control-border)] bg-[var(--color-control)] px-4 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
> >
<FileText size={16} /> <FileText size={16} />
@@ -527,7 +527,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
value={title} value={title}
onChange={(event) => setTitle(event.target.value)} onChange={(event) => setTitle(event.target.value)}
placeholder="제목을 입력하세요" placeholder="제목을 입력하세요"
className="mb-5 w-full rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-4 py-3 text-2xl font-bold tracking-normal text-[var(--color-text)] outline-none transition placeholder:text-[var(--color-text-subtle)] focus:border-[var(--color-accent)] md:text-3xl" className="mb-5 w-full rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-4 py-3 text-2xl font-bold tracking-normal text-[var(--color-text)] outline-none transition placeholder:text-[var(--color-text-subtle)] focus:border-[var(--color-accent)] md:text-3xl"
/> />
<div className="wy-editor-shell" data-color-mode={resolvedTheme}> <div className="wy-editor-shell" data-color-mode={resolvedTheme}>
@@ -558,15 +558,15 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
</h2> </h2>
<div className="mt-4 grid grid-cols-3 gap-2 text-center"> <div className="mt-4 grid grid-cols-3 gap-2 text-center">
<div className="rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] p-3"> <div className="rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] p-3 shadow-[var(--shadow-card)]">
<p className="text-lg font-bold tabular-nums text-[var(--color-text)]">{contentLength.toLocaleString()}</p> <p className="text-lg font-bold tabular-nums text-[var(--color-text)]">{contentLength.toLocaleString()}</p>
<p className="text-[10px] font-semibold text-[var(--color-text-subtle)]"></p> <p className="text-[10px] font-semibold text-[var(--color-text-subtle)]"></p>
</div> </div>
<div className="rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] p-3"> <div className="rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] p-3 shadow-[var(--shadow-card)]">
<p className="text-lg font-bold tabular-nums text-[var(--color-text)]">{wordCount.toLocaleString()}</p> <p className="text-lg font-bold tabular-nums text-[var(--color-text)]">{wordCount.toLocaleString()}</p>
<p className="text-[10px] font-semibold text-[var(--color-text-subtle)]"></p> <p className="text-[10px] font-semibold text-[var(--color-text-subtle)]"></p>
</div> </div>
<div className="rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] p-3"> <div className="rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] p-3 shadow-[var(--shadow-card)]">
<p className="text-lg font-bold tabular-nums text-[var(--color-text)]">{readingMinutes}</p> <p className="text-lg font-bold tabular-nums text-[var(--color-text)]">{readingMinutes}</p>
<p className="text-[10px] font-semibold text-[var(--color-text-subtle)]"></p> <p className="text-[10px] font-semibold text-[var(--color-text-subtle)]"></p>
</div> </div>
@@ -581,7 +581,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
<Folder size={17} /> <Folder size={17} />
</h2> </h2>
<div className="max-h-64 overflow-y-auto rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] p-2"> <div className="max-h-64 overflow-y-auto rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] p-2 shadow-[var(--shadow-card)]">
{categories.length > 0 ? ( {categories.length > 0 ? (
<CategoryOptions categories={categories} selectedId={categoryId} onSelect={setCategoryId} /> <CategoryOptions categories={categories} selectedId={categoryId} onSelect={setCategoryId} />
) : ( ) : (
@@ -602,7 +602,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
value={tags} value={tags}
onChange={(event) => setTags(event.target.value)} onChange={(event) => setTags(event.target.value)}
placeholder="react, nextjs, essay" placeholder="react, nextjs, essay"
className="w-full rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-3 py-2 text-sm text-[var(--color-text)] outline-none transition placeholder:text-[var(--color-text-subtle)] focus:border-[var(--color-accent)]" className="w-full rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 py-2 text-sm text-[var(--color-text)] outline-none transition placeholder:text-[var(--color-text-subtle)] focus:border-[var(--color-accent)]"
/> />
<p className="mt-2 text-xs text-[var(--color-text-subtle)]"> .</p> <p className="mt-2 text-xs text-[var(--color-text-subtle)]"> .</p>
</Surface> </Surface>
@@ -613,7 +613,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
</h2> </h2>
<label <label
className={`flex min-h-28 w-full cursor-pointer flex-col items-center justify-center rounded-lg border border-dashed border-[var(--color-line)] bg-[var(--color-control)] p-4 text-center transition hover:border-[var(--color-accent)] hover:bg-[var(--window-bg-strong)] ${isUploading ? 'cursor-wait opacity-60' : ''}`} className={`flex min-h-28 w-full cursor-pointer flex-col items-center justify-center rounded-lg border border-dashed border-[var(--card-border)] bg-[var(--card-bg)] p-4 text-center shadow-[var(--shadow-card)] transition hover:border-[var(--color-accent)] hover:bg-[var(--card-bg-strong)] ${isUploading ? 'cursor-wait opacity-60' : ''}`}
> >
<UploadCloud className="mb-2 h-7 w-7 text-[var(--color-text-subtle)]" /> <UploadCloud className="mb-2 h-7 w-7 text-[var(--color-text-subtle)]" />
<span className="text-sm font-semibold text-[var(--color-text)]"> <span className="text-sm font-semibold text-[var(--color-text)]">
@@ -641,7 +641,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
<button <button
type="button" type="button"
onClick={() => setShowDraftList((previous) => !previous)} onClick={() => setShowDraftList((previous) => !previous)}
className="rounded-full border border-[var(--color-line)] bg-[var(--color-control)] px-2.5 py-1 text-xs font-bold text-[var(--color-text-muted)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)]" className="rounded-full border border-[var(--control-border)] bg-[var(--color-control)] px-2.5 py-1 text-xs font-bold text-[var(--color-text-muted)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
> >
{drafts.length}/10 {drafts.length}/10
</button> </button>
@@ -656,7 +656,7 @@ export default function AdminPostEditor({ editSlug }: AdminPostEditorProps) {
) : ( ) : (
<ul className="space-y-1"> <ul className="space-y-1">
{drafts.map((draft) => ( {drafts.map((draft) => (
<li key={draft.id} className="group rounded-lg px-3 py-2 transition hover:bg-black/[0.04] dark:hover:bg-white/10"> <li key={draft.id} className="group rounded-lg px-3 py-2 transition hover:bg-[var(--card-bg)]">
<div className="flex items-start justify-between gap-2"> <div className="flex items-start justify-between gap-2">
<button type="button" onClick={() => handleLoadDraft(draft)} className="min-w-0 flex-1 text-left"> <button type="button" onClick={() => handleLoadDraft(draft)} className="min-w-0 flex-1 text-left">
<p className="line-clamp-1 text-sm font-semibold text-[var(--color-text)]">{draft.title}</p> <p className="line-clamp-1 text-sm font-semibold text-[var(--color-text)]">{draft.title}</p>

View File

@@ -57,10 +57,10 @@ export default function AdminRouteShell({ children }: { children: React.ReactNod
} }
return ( return (
<div className="mx-auto w-full space-y-6 px-0 py-4 md:w-[80vw] md:max-w-[1400px] md:py-6"> <div className="mx-auto w-full max-w-[1400px] space-y-6 px-0 py-4 md:py-6">
<WindowSurface title="Admin Console" subtitle="Operations toolbar" bodyClassName="p-2"> <WindowSurface title="System Settings" subtitle="Admin Console" bodyClassName="p-2">
<nav <nav
className="flex gap-2 overflow-x-auto rounded-lg bg-[var(--color-control)] p-1 backdrop-blur-xl" className="flex gap-2 overflow-x-auto rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] p-1 shadow-[var(--shadow-card)] backdrop-blur-[18px]"
aria-label="관리자 메뉴" aria-label="관리자 메뉴"
> >
{navItems.map((item) => { {navItems.map((item) => {
@@ -74,8 +74,8 @@ export default function AdminRouteShell({ children }: { children: React.ReactNod
className={clsx( className={clsx(
'inline-flex h-9 shrink-0 items-center gap-2 rounded-lg px-4 text-sm font-semibold transition', 'inline-flex h-9 shrink-0 items-center gap-2 rounded-lg px-4 text-sm font-semibold transition',
isActive isActive
? 'bg-[var(--window-bg-strong)] text-[var(--color-text)] shadow-sm' ? 'bg-[var(--card-bg-strong)] text-[var(--color-text)] shadow-sm'
: 'text-[var(--color-text-muted)] hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10', : 'text-[var(--color-text-muted)] hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]',
)} )}
> >
<Icon size={16} /> <Icon size={16} />

View File

@@ -50,7 +50,7 @@ export default function AdminDashboardActionCenter({
<Link <Link
key={item.label} key={item.label}
href={item.href} href={item.href}
className="flex items-center justify-between gap-4 rounded-lg px-3 py-3 transition hover:bg-black/[0.03] dark:hover:bg-white/10" className="flex items-center justify-between gap-4 rounded-lg px-3 py-3 transition hover:bg-[var(--card-bg)]"
> >
<span className="flex items-center gap-3 text-sm font-semibold text-[var(--color-text-muted)]"> <span className="flex items-center gap-3 text-sm font-semibold text-[var(--color-text-muted)]">
<Icon size={16} /> <Icon size={16} />

View File

@@ -34,9 +34,9 @@ export default function AdminDashboardCategoryHealth({
</div> </div>
{categoryStats.length > 0 ? ( {categoryStats.length > 0 ? (
<div className="overflow-x-auto rounded-lg border border-[var(--color-line)]"> <div className="overflow-x-auto rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] shadow-[var(--shadow-card)]">
<div className="min-w-[680px]"> <div className="min-w-[680px]">
<div className="grid grid-cols-[1.2fr_0.6fr_0.7fr_0.9fr_auto] gap-3 bg-black/[0.03] px-4 py-3 text-xs font-bold text-[var(--color-text-subtle)] dark:bg-white/10"> <div className="grid grid-cols-[1.2fr_0.6fr_0.7fr_0.9fr_auto] gap-3 bg-[var(--window-titlebar)] px-4 py-3 text-xs font-bold text-[var(--color-text-subtle)]">
<span></span> <span></span>
<span></span> <span></span>
<span> </span> <span> </span>
@@ -47,7 +47,7 @@ export default function AdminDashboardCategoryHealth({
<Link <Link
key={category.id} key={category.id}
href={`/category/${category.name}`} href={`/category/${category.name}`}
className="grid grid-cols-[1.2fr_0.6fr_0.7fr_0.9fr_auto] gap-3 border-t border-[var(--color-line)] px-4 py-3 text-sm transition hover:bg-black/[0.03] dark:hover:bg-white/10" className="grid grid-cols-[1.2fr_0.6fr_0.7fr_0.9fr_auto] gap-3 border-t border-[var(--card-border)] px-4 py-3 text-sm transition hover:bg-[var(--card-bg-strong)]"
> >
<span className="truncate font-semibold text-[var(--color-text)]">{category.name}</span> <span className="truncate font-semibold text-[var(--color-text)]">{category.name}</span>
<span className="text-[var(--color-text-muted)]">{category.postCount.toLocaleString()}</span> <span className="text-[var(--color-text-muted)]">{category.postCount.toLocaleString()}</span>

View File

@@ -16,7 +16,7 @@ function PostStatRow({ post, isFallback }: { post: DashboardPostStat; isFallback
return ( return (
<Link <Link
href={`/posts/${post.slug}`} href={`/posts/${post.slug}`}
className="group flex items-start justify-between gap-4 rounded-lg px-3 py-3 transition hover:bg-black/[0.03] dark:hover:bg-white/10" className="group flex items-start justify-between gap-4 rounded-lg px-3 py-3 transition hover:bg-[var(--card-bg)]"
> >
<div className="min-w-0"> <div className="min-w-0">
<div className="mb-1 flex items-center gap-2"> <div className="mb-1 flex items-center gap-2">

View File

@@ -34,6 +34,7 @@ export default function AdminDashboardTrafficChart({
isFallback, isFallback,
}: AdminDashboardTrafficChartProps) { }: AdminDashboardTrafficChartProps) {
const maxViews = Math.max(...points.map((point) => point.views), 1); const maxViews = Math.max(...points.map((point) => point.views), 1);
const hasTraffic = points.some((point) => point.views > 0);
return ( return (
<Surface as="section" className="p-5"> <Surface as="section" className="p-5">
@@ -44,7 +45,9 @@ export default function AdminDashboardTrafficChart({
<h2 className="text-lg font-bold text-[var(--color-text)]"> </h2> <h2 className="text-lg font-bold text-[var(--color-text)]"> </h2>
</div> </div>
<p className="mt-1 text-sm text-[var(--color-text-muted)]"> <p className="mt-1 text-sm text-[var(--color-text-muted)]">
. {isFallback
? '대시보드 집계 전에는 게시글 누적 조회수로 임시 흐름을 표시합니다.'
: '최근 기간별 조회수 흐름을 확인합니다.'}
</p> </p>
</div> </div>
<SegmentedControl <SegmentedControl
@@ -56,24 +59,37 @@ export default function AdminDashboardTrafficChart({
</div> </div>
{points.length > 0 ? ( {points.length > 0 ? (
<div className="flex h-64 items-end gap-1.5 overflow-hidden rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-3 py-4"> <>
<div className="h-64 overflow-x-auto rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-3 py-4">
<div className="flex h-full min-w-full items-stretch gap-1.5">
{points.map((point) => { {points.map((point) => {
const height = Math.max((point.views / maxViews) * 100, 4); const height = Math.max((point.views / maxViews) * 100, 4);
return ( return (
<div key={point.date} className="flex min-w-2 flex-1 flex-col items-center gap-2"> <div key={point.date} className="flex min-w-2 flex-1 flex-col items-center gap-2">
<div className="flex min-h-0 w-full flex-1 items-end">
<div <div
className="w-full rounded-t bg-[var(--color-accent)]/70 transition hover:bg-[var(--color-accent)]" className="w-full rounded-t bg-[var(--color-accent)]/70 transition hover:bg-[var(--color-accent)]"
style={{ height: `${height}%` }} style={{ height: `${height}%` }}
title={`${formatDay(point.date)} 조회 ${point.views.toLocaleString()}`} title={`${formatDay(point.date)} 조회 ${point.views.toLocaleString()}`}
/> />
<span className="hidden text-[10px] font-medium text-[var(--color-text-subtle)] sm:block"> </div>
<span className="hidden h-4 text-[10px] font-medium text-[var(--color-text-subtle)] sm:block">
{formatDay(point.date)} {formatDay(point.date)}
</span> </span>
</div> </div>
); );
})} })}
</div> </div>
</div>
{isFallback && (
<p className="mt-3 text-xs font-medium text-[var(--color-text-subtle)]">
{hasTraffic
? '임시 그래프는 글 발행일과 누적 조회수를 기준으로 계산됩니다.'
: '집계 API가 연결되면 실제 일별 조회수로 대체됩니다.'}
</p>
)}
</>
) : ( ) : (
<EmptyState <EmptyState
title="통계 API 연결 전" title="통계 API 연결 전"

View File

@@ -0,0 +1,347 @@
'use client';
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
import { Chess as ChessGame, type Color, type PieceSymbol, type Square } from 'chess.js';
import { clsx } from 'clsx';
import { ChessColor } from '@/types';
export type MoveSquares = {
from: Square;
to: Square;
};
type BoardPiece = {
square: Square;
color: Color;
type: PieceSymbol;
};
type VisualPiece = BoardPiece & {
id: string;
};
interface ChessBoardProps {
fen: string;
orientation?: ChessColor;
selectedSquare?: Square | null;
legalTargets?: Set<Square>;
lastMoveSquares?: MoveSquares | null;
disabled?: boolean;
isDraggableSquare?: (square: Square) => boolean;
onSquareClick?: (square: Square) => void;
onSquareDrop?: (from: Square, to: Square) => void;
}
const FILES = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] as const;
const WHITE_RANKS = [8, 7, 6, 5, 4, 3, 2, 1] as const;
const BLACK_RANKS = [1, 2, 3, 4, 5, 6, 7, 8] as const;
export const BOARD_SQUARES = WHITE_RANKS.flatMap((rank) =>
FILES.map((file) => `${file}${rank}` as Square),
);
const PIECE_SYMBOLS: Record<Color, Record<PieceSymbol, string>> = {
w: {
k: '♔',
q: '♕',
r: '♖',
b: '♗',
n: '♘',
p: '♙',
},
b: {
k: '♚',
q: '♛',
r: '♜',
b: '♝',
n: '♞',
p: '♟',
},
};
const PIECE_NAMES: Record<PieceSymbol, string> = {
k: '킹',
q: '퀸',
r: '룩',
b: '비숍',
n: '나이트',
p: '폰',
};
const colorLabel = (color: Color) => (color === 'w' ? '백' : '흑');
const createGame = (fen: string) => {
try {
return new ChessGame(fen);
} catch {
return new ChessGame();
}
};
const getBoardSquares = (orientation: ChessColor) => {
const ranks = orientation === 'black' ? BLACK_RANKS : WHITE_RANKS;
const files = orientation === 'black' ? [...FILES].reverse() : FILES;
return ranks.flatMap((rank) => files.map((file) => `${file}${rank}` as Square));
};
const getPieces = (game: ChessGame): BoardPiece[] =>
BOARD_SQUARES.flatMap((square) => {
const piece = game.get(square);
if (!piece) return [];
return [{ square, color: piece.color, type: piece.type }];
});
const getSquareLabel = (square: Square, piece?: { color: Color; type: PieceSymbol }) => {
if (!piece) return `${square} 빈 칸`;
return `${square} ${colorLabel(piece.color)} ${PIECE_NAMES[piece.type]}`;
};
const isLightSquare = (square: Square) => {
const fileIndex = FILES.indexOf(square[0] as (typeof FILES)[number]);
const rank = Number(square[1]);
return (fileIndex + rank) % 2 === 0;
};
const getSquarePosition = (square: Square, orientation: ChessColor): CSSProperties => {
const fileIndex = FILES.indexOf(square[0] as (typeof FILES)[number]);
const rank = Number(square[1]);
const x = orientation === 'black' ? 7 - fileIndex : fileIndex;
const y = orientation === 'black' ? rank - 1 : 8 - rank;
return {
transform: `translate(${x * 100}%, ${y * 100}%)`,
};
};
const samePiece = (a: BoardPiece, b: BoardPiece) => a.color === b.color && a.type === b.type;
const canRepresentMove = (fromPiece: VisualPiece, toPiece: BoardPiece) =>
fromPiece.color === toPiece.color && (fromPiece.type === toPiece.type || fromPiece.type === 'p');
const createPieceId = (piece: BoardPiece, index: number) =>
`${piece.color}-${piece.type}-${piece.square}-${index}`;
const createVisualPieces = (pieces: BoardPiece[]) => pieces.map((piece, index) => ({ ...piece, id: createPieceId(piece, index) }));
const reconcileVisualPieces = (
previousPieces: VisualPiece[],
nextPieces: BoardPiece[],
lastMoveSquares?: MoveSquares | null,
) => {
if (!lastMoveSquares) return createVisualPieces(nextPieces);
const nextBySquare = new Map(nextPieces.map((piece) => [piece.square, piece]));
const movedPieceTarget = nextBySquare.get(lastMoveSquares.to);
if (!movedPieceTarget) return createVisualPieces(nextPieces);
const usedVisualIds = new Set<string>();
const usedSquares = new Set<Square>();
const reconciled: VisualPiece[] = [];
const movingPiece =
previousPieces.find(
(piece) => piece.square === lastMoveSquares.from && canRepresentMove(piece, movedPieceTarget),
) ?? previousPieces.find((piece) => piece.square === lastMoveSquares.from);
if (movingPiece) {
reconciled.push({ ...movingPiece, ...movedPieceTarget });
usedVisualIds.add(movingPiece.id);
usedSquares.add(movedPieceTarget.square);
}
previousPieces.forEach((visualPiece) => {
if (usedVisualIds.has(visualPiece.id)) return;
const nextPiece = nextBySquare.get(visualPiece.square);
if (!nextPiece || usedSquares.has(nextPiece.square) || !samePiece(visualPiece, nextPiece)) return;
reconciled.push({ ...visualPiece, ...nextPiece });
usedVisualIds.add(visualPiece.id);
usedSquares.add(nextPiece.square);
});
nextPieces.forEach((nextPiece, index) => {
if (usedSquares.has(nextPiece.square)) return;
reconciled.push({ ...nextPiece, id: createPieceId(nextPiece, previousPieces.length + index) });
});
return reconciled;
};
export const getMoveSquares = (move?: string | null): MoveSquares | null => {
if (!move || move.length < 4) return null;
return {
from: move.slice(0, 2) as Square,
to: move.slice(2, 4) as Square,
};
};
export const toChessJsColor = (color: ChessColor): Color => (color === 'white' ? 'w' : 'b');
export const getTurnLabel = (color: ChessColor) => (color === 'white' ? '백' : '흑');
export default function ChessBoard({
fen,
orientation = 'white',
selectedSquare,
legalTargets,
lastMoveSquares,
disabled = false,
isDraggableSquare,
onSquareClick,
onSquareDrop,
}: ChessBoardProps) {
const game = useMemo(() => createGame(fen), [fen]);
const boardSquares = useMemo(() => getBoardSquares(orientation), [orientation]);
const firstFile = orientation === 'black' ? 'h' : 'a';
const lastRank = orientation === 'black' ? '8' : '1';
const [visualPieces, setVisualPieces] = useState(() => createVisualPieces(getPieces(game)));
const previousFenRef = useRef(fen);
useEffect(() => {
const nextPieces = getPieces(game);
setVisualPieces((previousPieces) => {
if (previousFenRef.current === fen) return previousPieces;
previousFenRef.current = fen;
return reconcileVisualPieces(previousPieces, nextPieces, lastMoveSquares);
});
}, [fen, game, lastMoveSquares]);
return (
<div className="relative aspect-square w-full rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] p-1 shadow-[var(--shadow-control)] backdrop-blur-[18px]">
<div className="relative h-full w-full overflow-hidden rounded-md border border-white/60 bg-[var(--color-surface-strong)] shadow-[0_1px_0_rgb(255_255_255_/_0.46)_inset] dark:border-white/10">
<div className="grid h-full w-full grid-cols-[repeat(8,minmax(0,1fr))] grid-rows-[repeat(8,minmax(0,1fr))]">
{boardSquares.map((square) => {
const piece = game.get(square);
const isLight = isLightSquare(square);
const isSelected = selectedSquare === square;
const isTarget = legalTargets?.has(square) ?? false;
const isLastMoveSquare = lastMoveSquares?.from === square || lastMoveSquares?.to === square;
const canDrag = !disabled && Boolean(piece) && (isDraggableSquare?.(square) ?? true);
const file = square[0];
const rank = square[1];
return (
<button
key={square}
type="button"
onClick={() => onSquareClick?.(square)}
draggable={canDrag}
onDragStart={(event) => {
if (!canDrag) {
event.preventDefault();
return;
}
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData('text/plain', square);
}}
onDragOver={(event) => {
if (!disabled && onSquareDrop) {
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
}
}}
onDrop={(event) => {
if (disabled || !onSquareDrop) return;
event.preventDefault();
const from = event.dataTransfer.getData('text/plain') as Square;
if (!from || from === square) return;
onSquareDrop(from, square);
}}
className={clsx(
'relative min-h-0 min-w-0 overflow-hidden transition-[filter,box-shadow] duration-150',
isLight ? 'bg-[#edf2f5] dark:bg-[#c8d0d6]' : 'bg-[#7fa18b] dark:bg-[#415d52]',
canDrag && 'cursor-grab active:cursor-grabbing',
!disabled && 'hover:brightness-[1.04] focus-visible:z-20',
disabled && 'cursor-not-allowed',
)}
aria-label={getSquareLabel(square, piece)}
aria-pressed={isSelected}
>
{isLastMoveSquare && (
<span className="absolute inset-1 rounded bg-[var(--color-accent-soft)] shadow-[0_0_0_1px_rgb(255_255_255_/_0.34)_inset]" />
)}
{isSelected && (
<span className="absolute inset-1 rounded border-2 border-[var(--color-accent)] bg-[var(--color-accent-soft)] shadow-[0_0_0_2px_rgb(255_255_255_/_0.28)_inset]" />
)}
{file === firstFile && (
<span
className={clsx(
'absolute left-1 top-1 text-[9px] font-bold leading-none sm:left-1.5 sm:top-1.5 sm:text-[10px]',
isLight ? 'text-[#7a9a86]' : 'text-white/80',
)}
>
{rank}
</span>
)}
{rank === lastRank && (
<span
className={clsx(
'absolute bottom-1 right-1 text-[9px] font-bold leading-none sm:bottom-1.5 sm:right-1.5 sm:text-[10px]',
isLight ? 'text-[#7a9a86]' : 'text-white/80',
)}
>
{file}
</span>
)}
{isTarget && (
<span
className={clsx(
'absolute z-10 rounded-full transition',
piece
? 'inset-[13%] border-[2px] border-[var(--color-accent)]/70 shadow-[0_0_0_1px_rgb(255_255_255_/_0.28)_inset]'
: 'left-1/2 top-1/2 h-[22%] w-[22%] -translate-x-1/2 -translate-y-1/2 bg-[var(--color-accent)]/42 shadow-[0_1px_3px_rgb(0_0_0_/_0.18)]',
)}
/>
)}
</button>
);
})}
</div>
<div className="pointer-events-none absolute inset-0">
{visualPieces.map((piece) => {
const canDrag = !disabled && (isDraggableSquare?.(piece.square) ?? true);
const isSelected = selectedSquare === piece.square;
const isLastMovePiece = lastMoveSquares?.to === piece.square;
return (
<span
key={piece.id}
className="absolute left-0 top-0 flex h-[12.5%] w-[12.5%] items-center justify-center transition-transform duration-[420ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none"
style={getSquarePosition(piece.square, orientation)}
aria-hidden="true"
>
<span
className={clsx(
'flex h-full w-full select-none items-center justify-center font-serif text-[2.5rem] font-bold leading-none transition-[transform,filter] duration-200 sm:text-[3rem] md:text-[3.6rem]',
canDrag && 'cursor-grab active:cursor-grabbing',
isSelected && 'scale-110 -translate-y-0.5 brightness-110',
isLastMovePiece && 'scale-[1.04]',
piece.color === 'w'
? 'text-[#fffdf7] [text-shadow:0_1px_2px_rgb(0_0_0_/_0.48),0_0_1px_rgb(0_0_0_/_0.72),0_5px_9px_rgb(15_23_42_/_0.2)]'
: 'text-[#151922] [text-shadow:0_1px_0_rgb(255_255_255_/_0.72),0_0_1px_rgb(255_255_255_/_0.82),0_5px_9px_rgb(15_23_42_/_0.2)]',
)}
>
{PIECE_SYMBOLS[piece.color][piece.type]}
</span>
</span>
);
})}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,535 @@
'use client';
import { useMemo, useState, type ReactNode } from 'react';
import Link from 'next/link';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Chess as ChessGame, type Move, type Square } from 'chess.js';
import { clsx } from 'clsx';
import {
AlertCircle,
ChevronLeft,
Clipboard,
Flag,
History,
Home,
Loader2,
PlusCircle,
RotateCcw,
Swords,
Undo2,
} from 'lucide-react';
import toast from 'react-hot-toast';
import { getChessGame, postChessMove, resignChessGame, undoChessMove } from '@/api/chess';
import ChessBoard, { getMoveSquares, getTurnLabel, toChessJsColor, type MoveSquares } from '@/components/chess/ChessBoard';
import { getChessErrorMessage, getChessOutcomeLabel, isAuthError, outcomeBadgeTones } from '@/components/chess/chessUi';
import StatusBadge from '@/components/ui/StatusBadge';
import WindowSurface from '@/components/ui/WindowSurface';
import { useAuthStore } from '@/store/authStore';
import { ChessColor, ChessGameResponse } from '@/types';
interface ChessGamePlayClientProps {
gameId: string;
}
const INITIAL_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
const createGame = (fen: string) => {
try {
return new ChessGame(fen);
} catch {
return null;
}
};
const getPreferredMove = (moves: Move[], to: Square) => {
const candidates = moves.filter((move) => move.to === to);
return candidates.find((move) => move.promotion === 'q') ?? candidates[0] ?? null;
};
const toUciMove = (move: Move) => `${move.from}${move.to}${move.promotion ?? ''}`;
const hasPlayerMoved = (moves: string[], playerColor: ChessColor) => {
return moves.some((_, index) => {
const side = index % 2 === 0 ? 'white' : 'black';
return side === playerColor;
});
};
function ChessPageFrame({ children }: { children: ReactNode }) {
return (
<main className="mx-auto flex w-full min-w-0 max-w-[1180px] flex-col gap-5 px-0 py-3 md:py-6">
{children}
</main>
);
}
function LoadingState({ message = '대국을 불러오는 중입니다.' }: { message?: string }) {
return (
<ChessPageFrame>
<WindowSurface title="Maia Chess" showTrafficLights={false} bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center">
<Loader2 className="mb-3 animate-spin text-[var(--color-accent)]" size={30} />
<p className="text-sm font-semibold text-[var(--color-text)]">{message}</p>
</WindowSurface>
</ChessPageFrame>
);
}
function LoginRequired() {
return (
<ChessPageFrame>
<WindowSurface title="Maia Chess" showTrafficLights={false} bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center">
<AlertCircle className="mb-3 text-amber-500" size={30} />
<h1 className="break-words text-2xl font-bold tracking-normal text-[var(--color-text)]"> .</h1>
<p className="mt-2 max-w-md break-words text-sm leading-6 text-[var(--color-text-muted)]">
Maia .
</p>
<Link
href="/login?redirect=/chess"
className="mt-6 inline-flex h-10 items-center gap-2 rounded-lg bg-[var(--color-accent)] px-4 text-sm font-semibold text-white transition hover:bg-[var(--color-accent-hover)]"
>
</Link>
</WindowSurface>
</ChessPageFrame>
);
}
function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {
return (
<ChessPageFrame>
<WindowSurface title="Maia Chess" showTrafficLights={false} bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center">
<AlertCircle className="mb-3 text-red-500" size={30} />
<h1 className="break-words text-2xl font-bold tracking-normal text-[var(--color-text)]"> .</h1>
<p className="mt-2 max-w-md break-words text-sm leading-6 text-[var(--color-text-muted)]">{message}</p>
<button
type="button"
onClick={onRetry}
className="mt-6 inline-flex h-10 items-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-4 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<RotateCcw size={16} />
</button>
</WindowSurface>
</ChessPageFrame>
);
}
function GameInfoPanel({
game,
isPlayerTurn,
pending,
canUndo,
canResign,
onCopyPgn,
onUndo,
onResign,
}: {
game: ChessGameResponse;
isPlayerTurn: boolean;
pending: boolean;
canUndo: boolean;
canResign: boolean;
onCopyPgn: () => void;
onUndo: () => void;
onResign: () => void;
}) {
const gameEnded = game.status !== 'IN_PROGRESS';
return (
<WindowSurface title="Game Info" showTrafficLights={false} as="aside" bodyClassName="p-4 md:p-5">
<div className="mb-4 flex min-w-0 flex-wrap items-center gap-2">
<StatusBadge tone={outcomeBadgeTones[game.outcome]}>{getChessOutcomeLabel(game.outcome, game.status)}</StatusBadge>
{game.result && <StatusBadge tone="neutral">{game.result}</StatusBadge>}
</div>
<dl className="grid grid-cols-2 gap-3 text-sm">
<div className="min-w-0 rounded-lg bg-black/[0.025] px-3 py-2 dark:bg-white/[0.06]">
<dt className="text-xs text-[var(--color-text-subtle)]"></dt>
<dd className="mt-0.5 truncate font-semibold text-[var(--color-text)]">{game.rating}</dd>
</div>
<div className="min-w-0 rounded-lg bg-black/[0.025] px-3 py-2 dark:bg-white/[0.06]">
<dt className="text-xs text-[var(--color-text-subtle)]"></dt>
<dd className="mt-0.5 truncate font-semibold text-[var(--color-text)]">Maia {game.model}</dd>
</div>
<div className="min-w-0 rounded-lg bg-black/[0.025] px-3 py-2 dark:bg-white/[0.06]">
<dt className="text-xs text-[var(--color-text-subtle)]"> </dt>
<dd className="mt-0.5 truncate font-semibold text-[var(--color-text)]">{getTurnLabel(game.playerColor)}</dd>
</div>
<div className="min-w-0 rounded-lg bg-black/[0.025] px-3 py-2 dark:bg-white/[0.06]">
<dt className="text-xs text-[var(--color-text-subtle)]"> </dt>
<dd className="mt-0.5 truncate font-semibold text-[var(--color-text)]">{getTurnLabel(game.turn)}</dd>
</div>
</dl>
<div
className={clsx(
'mt-4 rounded-lg border px-3 py-3 text-sm font-semibold leading-6',
gameEnded && 'border-[var(--color-line)] bg-black/[0.025] text-[var(--color-text-muted)] dark:bg-white/[0.06]',
!gameEnded && isPlayerTurn && !pending && 'border-emerald-500/20 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',
!gameEnded && (!isPlayerTurn || pending) && 'border-[var(--color-line)] bg-black/[0.025] text-[var(--color-text-muted)] dark:bg-white/[0.06]',
)}
>
{gameEnded && '종료된 대국입니다.'}
{!gameEnded && pending && '요청을 처리하는 중입니다.'}
{!gameEnded && !pending && isPlayerTurn && '내 차례입니다. 말을 움직이세요.'}
{!gameEnded && !pending && !isPlayerTurn && 'Maia 차례입니다.'}
</div>
<div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-3 xl:grid-cols-1">
{game.status === 'IN_PROGRESS' && (
<>
<button
type="button"
onClick={onUndo}
disabled={!canUndo}
className="inline-flex h-10 min-w-0 items-center justify-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)] disabled:cursor-not-allowed disabled:opacity-50"
>
<Undo2 size={16} />
</button>
<button
type="button"
onClick={onResign}
disabled={!canResign}
className="inline-flex h-10 min-w-0 items-center justify-center gap-2 rounded-lg border border-red-500/20 bg-red-500/10 px-3 text-sm font-semibold text-red-700 shadow-[var(--shadow-control)] transition hover:bg-red-500/15 disabled:cursor-not-allowed disabled:opacity-50 dark:text-red-300"
>
<Flag size={16} />
</button>
</>
)}
<Link
href="/chess"
className="inline-flex h-10 min-w-0 items-center justify-center gap-2 rounded-lg bg-[var(--color-accent)] px-3 text-sm font-semibold text-white shadow-[var(--shadow-control)] transition hover:bg-[var(--color-accent-hover)]"
>
<PlusCircle size={16} />
</Link>
</div>
<div className="mt-4 rounded-lg border border-[var(--color-line)] bg-black/[0.025] px-3 py-3 dark:bg-white/[0.06]">
<p className="text-xs font-semibold text-[var(--color-text-subtle)]"> Maia </p>
<p className="mt-1 break-words font-mono text-sm font-semibold text-[var(--color-text)]">
{game.maiaMove || '아직 없음'}
</p>
</div>
<div className="mt-5">
<div className="mb-2 flex min-w-0 items-center justify-between gap-3">
<p className="text-sm font-bold text-[var(--color-text)]">PGN</p>
<button
type="button"
onClick={onCopyPgn}
className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-xs font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<Clipboard size={14} />
</button>
</div>
<pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] p-3 text-xs leading-5 text-[var(--color-text-muted)]">
{game.pgn || 'PGN이 아직 없습니다.'}
</pre>
</div>
</WindowSurface>
);
}
export default function ChessGamePlayClient({ gameId }: ChessGamePlayClientProps) {
const queryClient = useQueryClient();
const { isLoggedIn, _hasHydrated } = useAuthStore();
const [selectedSquare, setSelectedSquare] = useState<Square | null>(null);
const [optimisticFen, setOptimisticFen] = useState<string | null>(null);
const [optimisticMoveSquares, setOptimisticMoveSquares] = useState<MoveSquares | null>(null);
const gameQueryKey = useMemo(() => ['chess-game', gameId] as const, [gameId]);
const gameQuery = useQuery({
queryKey: gameQueryKey,
queryFn: () => getChessGame(gameId),
enabled: _hasHydrated && isLoggedIn,
retry: 0,
});
const syncUpdatedGame = async (updatedGame: ChessGameResponse) => {
queryClient.setQueryData(gameQueryKey, updatedGame);
setOptimisticFen(null);
setOptimisticMoveSquares(null);
setSelectedSquare(null);
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['chess-games'] }),
queryClient.invalidateQueries({ queryKey: ['chess-game-stats'] }),
]);
};
const moveMutation = useMutation({
mutationFn: (move: string) => postChessMove(gameId, { move }),
onSuccess: async (updatedGame) => {
await syncUpdatedGame(updatedGame);
},
onError: (error) => {
setOptimisticFen(null);
setOptimisticMoveSquares(null);
setSelectedSquare(null);
toast.error(getChessErrorMessage(error, '봇 응답을 가져오지 못했습니다. 잠시 후 다시 시도해주세요.'));
void gameQuery.refetch();
},
});
const undoMutation = useMutation({
mutationFn: () => undoChessMove(gameId),
onSuccess: async (updatedGame) => {
await syncUpdatedGame(updatedGame);
toast.success('무르기를 적용했습니다.');
},
onError: (error) => {
setOptimisticFen(null);
setOptimisticMoveSquares(null);
setSelectedSquare(null);
toast.error(getChessErrorMessage(error, '무르기를 처리하지 못했습니다.'));
void gameQuery.refetch();
},
});
const resignMutation = useMutation({
mutationFn: () => resignChessGame(gameId),
onSuccess: async (updatedGame) => {
await syncUpdatedGame(updatedGame);
toast.success('기권 처리되었습니다.');
},
onError: (error) => {
setOptimisticFen(null);
setOptimisticMoveSquares(null);
setSelectedSquare(null);
toast.error(getChessErrorMessage(error, '기권을 처리하지 못했습니다.'));
void gameQuery.refetch();
},
});
const game = gameQuery.data;
const isPending = moveMutation.isPending || undoMutation.isPending || resignMutation.isPending;
const currentFen = optimisticFen ?? game?.fen ?? INITIAL_FEN;
const localGame = useMemo(() => createGame(currentFen), [currentFen]);
const playerColor = game ? toChessJsColor(game.playerColor) : null;
const canInteract =
Boolean(game && localGame && playerColor) &&
game?.status === 'IN_PROGRESS' &&
game.turn === game.playerColor &&
!isPending;
const legalMoves = useMemo<Move[]>(() => {
if (!localGame || !selectedSquare || !canInteract) return [];
return localGame.moves({ square: selectedSquare, verbose: true });
}, [canInteract, localGame, selectedSquare]);
const legalTargets = useMemo(() => new Set(legalMoves.map((move) => move.to)), [legalMoves]);
const serverLastMoveSquares = useMemo(() => getMoveSquares(game?.maiaMove ?? game?.moves.at(-1)), [game?.maiaMove, game?.moves]);
const lastMoveSquares = optimisticMoveSquares ?? serverLastMoveSquares;
const isOwnTurnPiece = (square: Square) => {
if (!localGame || !playerColor || !canInteract) return false;
const piece = localGame.get(square);
return piece?.color === playerColor && piece.color === localGame.turn();
};
const attemptMove = (from: Square, to: Square) => {
if (!game || !localGame || !canInteract || !isOwnTurnPiece(from)) return;
const movesFromSquare = localGame.moves({ square: from, verbose: true });
const candidate = getPreferredMove(movesFromSquare, to);
if (!candidate) {
setSelectedSquare(null);
toast.error('그 칸으로는 이동할 수 없습니다.');
return;
}
try {
const nextGame = new ChessGame(currentFen);
nextGame.move({
from,
to,
promotion: candidate.promotion,
});
setOptimisticFen(nextGame.fen());
setOptimisticMoveSquares({ from, to });
setSelectedSquare(null);
moveMutation.mutate(toUciMove(candidate));
} catch {
setOptimisticMoveSquares(null);
toast.error('합법적인 수가 아닙니다.');
}
};
const handleSquareClick = (square: Square) => {
if (!localGame || !canInteract) return;
const piece = localGame.get(square);
const isSelectablePiece = piece?.color === playerColor && piece.color === localGame.turn();
if (!selectedSquare) {
if (isSelectablePiece) setSelectedSquare(square);
return;
}
if (selectedSquare === square) {
setSelectedSquare(null);
return;
}
if (legalTargets.has(square)) {
attemptMove(selectedSquare, square);
return;
}
if (isSelectablePiece) {
setSelectedSquare(square);
return;
}
setSelectedSquare(null);
};
const copyPgn = () => {
if (!game?.pgn) {
toast.error('복사할 PGN이 없습니다.');
return;
}
void navigator.clipboard.writeText(game.pgn)
.then(() => toast.success('PGN을 복사했습니다.'))
.catch(() => toast.error('PGN 복사에 실패했습니다.'));
};
const canResign = Boolean(game && game.status === 'IN_PROGRESS' && !isPending);
const canUndo = Boolean(game && game.status === 'IN_PROGRESS' && !isPending && hasPlayerMoved(game.moves, game.playerColor));
const pendingLabel = resignMutation.isPending
? '기권 처리 중'
: undoMutation.isPending
? '무르기 처리 중'
: moveMutation.isPending
? 'Maia 생각 중'
: '';
const handleUndo = () => {
if (!canUndo) return;
undoMutation.mutate();
};
const handleResign = () => {
if (!canResign) return;
if (!window.confirm('정말 기권하시겠습니까? 이 대국은 패배로 종료됩니다.')) return;
resignMutation.mutate();
};
if (!_hasHydrated) return <LoadingState message="로그인 상태를 확인하는 중입니다." />;
if (!isLoggedIn) return <LoginRequired />;
if (gameQuery.isLoading) return <LoadingState />;
if (gameQuery.isError) {
if (isAuthError(gameQuery.error)) return <LoginRequired />;
return (
<ErrorState
message={getChessErrorMessage(gameQuery.error, '대국 상세를 불러오지 못했습니다.')}
onRetry={() => void gameQuery.refetch()}
/>
);
}
if (!game) {
return (
<ErrorState
message="대국 정보를 찾을 수 없습니다."
onRetry={() => void gameQuery.refetch()}
/>
);
}
const isPlayerTurn = game.status === 'IN_PROGRESS' && game.turn === game.playerColor;
return (
<ChessPageFrame>
<section className="flex min-w-0 flex-col gap-3 border-b border-[var(--color-line)] pb-5">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2 text-[var(--color-accent)]">
<Swords size={24} className="shrink-0" />
<h1 className="min-w-0 break-words text-2xl font-bold tracking-normal text-[var(--color-text)] md:text-3xl">
Maia
</h1>
</div>
<div className="flex shrink-0 flex-wrap items-center gap-2">
<Link
href="/chess"
className="inline-flex h-9 items-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<Home size={16} />
</Link>
<Link
href="/chess/history"
className="inline-flex h-9 items-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<History size={16} />
</Link>
</div>
</div>
<Link
href="/chess"
className="inline-flex w-fit items-center gap-1.5 text-sm font-semibold text-[var(--color-text-subtle)] transition hover:text-[var(--color-accent)]"
>
<ChevronLeft size={15} />
</Link>
</section>
<section className="grid min-w-0 items-start justify-center gap-5 xl:grid-cols-[minmax(0,30rem)_22rem]">
<WindowSurface
title="Board"
subtitle={isPending ? 'Updating' : isPlayerTurn ? 'Your move' : 'Synced'}
showTrafficLights={false}
bodyClassName="p-2 md:p-3"
>
<div className="relative mx-auto max-w-full" style={{ width: 'min(100%, clamp(19rem, min(52vw, calc(100svh - 22.5rem)), 30rem))' }}>
<ChessBoard
fen={currentFen}
orientation={game.playerColor}
selectedSquare={selectedSquare}
legalTargets={legalTargets}
lastMoveSquares={lastMoveSquares}
disabled={!canInteract}
isDraggableSquare={isOwnTurnPiece}
onSquareClick={handleSquareClick}
onSquareDrop={attemptMove}
/>
{isPending && (
<div className="pointer-events-none absolute bottom-3 left-1/2 z-30 -translate-x-1/2">
<div className="flex items-center gap-2 rounded-full border border-white/25 bg-black/62 px-4 py-2 text-sm font-semibold text-white shadow-[0_12px_28px_rgb(0_0_0_/_0.28)] backdrop-blur-md">
<Loader2 className="animate-spin" size={16} />
{pendingLabel || '처리 중'}
</div>
</div>
)}
</div>
</WindowSurface>
<GameInfoPanel
game={game}
isPlayerTurn={isPlayerTurn}
pending={isPending}
canUndo={canUndo}
canResign={canResign}
onCopyPgn={copyPgn}
onUndo={handleUndo}
onResign={handleResign}
/>
</section>
</ChessPageFrame>
);
}

View File

@@ -0,0 +1,212 @@
'use client';
import { useMemo, useState, type ReactNode } from 'react';
import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { AlertCircle, Bot, ChevronRight, Home, Loader2, RotateCcw, Swords } from 'lucide-react';
import { getChessGames } from '@/api/chess';
import { getTurnLabel } from '@/components/chess/ChessBoard';
import {
formatChessDateTime,
getChessErrorMessage,
getChessOutcomeLabel,
isAuthError,
outcomeBadgeTones,
type OutcomeFilter,
} from '@/components/chess/chessUi';
import SegmentedControl, { SegmentedControlOption } from '@/components/ui/SegmentedControl';
import StatusBadge from '@/components/ui/StatusBadge';
import WindowSurface from '@/components/ui/WindowSurface';
import { useAuthStore } from '@/store/authStore';
import { ChessGameSummaryResponse } from '@/types';
const FILTER_OPTIONS: readonly SegmentedControlOption<OutcomeFilter>[] = [
{ label: '전체', value: 'ALL' },
{ label: '진행중', value: 'IN_PROGRESS' },
{ label: '승', value: 'WIN' },
{ label: '패', value: 'LOSS' },
{ label: '무', value: 'DRAW' },
];
function ChessPageFrame({ children }: { children: ReactNode }) {
return (
<main className="mx-auto flex w-full min-w-0 max-w-[1160px] flex-col gap-5 px-0 py-3 md:py-6">
{children}
</main>
);
}
function LoadingState({ message = '대국 기록을 불러오는 중입니다.' }: { message?: string }) {
return (
<ChessPageFrame>
<WindowSurface title="Game History" showTrafficLights={false} bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center">
<Loader2 className="mb-3 animate-spin text-[var(--color-accent)]" size={30} />
<p className="text-sm font-semibold text-[var(--color-text)]">{message}</p>
</WindowSurface>
</ChessPageFrame>
);
}
function LoginRequired() {
return (
<ChessPageFrame>
<WindowSurface title="Game History" showTrafficLights={false} bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center">
<AlertCircle className="mb-3 text-amber-500" size={30} />
<h1 className="break-words text-2xl font-bold tracking-normal text-[var(--color-text)]"> .</h1>
<p className="mt-2 max-w-md break-words text-sm leading-6 text-[var(--color-text-muted)]">
.
</p>
<Link
href="/login?redirect=/chess/history"
className="mt-6 inline-flex h-10 items-center gap-2 rounded-lg bg-[var(--color-accent)] px-4 text-sm font-semibold text-white transition hover:bg-[var(--color-accent-hover)]"
>
</Link>
</WindowSurface>
</ChessPageFrame>
);
}
function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {
return (
<ChessPageFrame>
<WindowSurface title="Game History" showTrafficLights={false} bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center">
<AlertCircle className="mb-3 text-red-500" size={30} />
<h1 className="break-words text-2xl font-bold tracking-normal text-[var(--color-text)]"> .</h1>
<p className="mt-2 max-w-md break-words text-sm leading-6 text-[var(--color-text-muted)]">{message}</p>
<button
type="button"
onClick={onRetry}
className="mt-6 inline-flex h-10 items-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-4 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<RotateCcw size={16} />
</button>
</WindowSurface>
</ChessPageFrame>
);
}
function HistoryRow({ game }: { game: ChessGameSummaryResponse }) {
return (
<Link
href={`/chess/play/${game.gameId}`}
className="group grid min-w-0 gap-3 rounded-lg px-3 py-4 transition hover:bg-[var(--card-bg)] md:grid-cols-[minmax(0,1fr)_8rem_8rem_7rem_1.25rem] md:items-center"
>
<div className="min-w-0">
<div className="mb-1.5 flex min-w-0 flex-wrap items-center gap-2">
<StatusBadge tone={outcomeBadgeTones[game.outcome]}>{getChessOutcomeLabel(game.outcome, game.status)}</StatusBadge>
{game.result && <StatusBadge tone="neutral">{game.result}</StatusBadge>}
</div>
<p className="truncate text-sm font-bold text-[var(--color-text)]">
Maia {game.model} · {game.rating}
</p>
<p className="mt-0.5 truncate text-xs text-[var(--color-text-subtle)]">
{formatChessDateTime(game.updatedAt)}
</p>
</div>
<div className="min-w-0 text-sm md:text-right">
<p className="text-xs text-[var(--color-text-subtle)] md:hidden"> </p>
<p className="font-semibold text-[var(--color-text-muted)]">{getTurnLabel(game.playerColor)}</p>
</div>
<div className="min-w-0 text-sm md:text-right">
<p className="text-xs text-[var(--color-text-subtle)] md:hidden"></p>
<p className="font-semibold tabular-nums text-[var(--color-text-muted)]">{game.movesCount.toLocaleString()}</p>
</div>
<div className="min-w-0 text-sm md:text-right">
<p className="text-xs text-[var(--color-text-subtle)] md:hidden"></p>
<p className="truncate font-semibold text-[var(--color-text-muted)]">{formatChessDateTime(game.createdAt)}</p>
</div>
<ChevronRight size={17} className="hidden text-[var(--color-text-subtle)] transition group-hover:translate-x-0.5 group-hover:text-[var(--color-accent)] md:block" />
</Link>
);
}
export default function ChessHistoryClient() {
const { isLoggedIn, _hasHydrated } = useAuthStore();
const [filter, setFilter] = useState<OutcomeFilter>('ALL');
const gamesQuery = useQuery({
queryKey: ['chess-games', { page: 0, size: 100, sort: 'updatedAt,desc' }],
queryFn: () => getChessGames({ page: 0, size: 100, sort: 'updatedAt,desc' }),
enabled: _hasHydrated && isLoggedIn,
retry: 0,
});
const games = useMemo(() => gamesQuery.data?.content ?? [], [gamesQuery.data?.content]);
const filteredGames = useMemo(() => {
if (filter === 'ALL') return games;
return games.filter((game) => game.outcome === filter);
}, [filter, games]);
if (!_hasHydrated) return <LoadingState message="로그인 상태를 확인하는 중입니다." />;
if (!isLoggedIn) return <LoginRequired />;
if (gamesQuery.isLoading) return <LoadingState />;
if (gamesQuery.isError) {
if (isAuthError(gamesQuery.error)) return <LoginRequired />;
return (
<ErrorState
message={getChessErrorMessage(gamesQuery.error, '대국 기록을 불러오지 못했습니다.')}
onRetry={() => void gamesQuery.refetch()}
/>
);
}
return (
<ChessPageFrame>
<section className="flex min-w-0 flex-col gap-3 border-b border-[var(--color-line)] pb-5">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2 text-[var(--color-accent)]">
<Swords size={24} className="shrink-0" />
<h1 className="min-w-0 break-words text-2xl font-bold tracking-normal text-[var(--color-text)] md:text-3xl">
</h1>
</div>
<Link
href="/chess"
className="inline-flex h-9 items-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<Home size={16} />
</Link>
</div>
<p className="max-w-2xl break-words text-sm leading-6 text-[var(--color-text-muted)]">
Maia . PGN을 .
</p>
</section>
<WindowSurface
title="History"
subtitle={`${filteredGames.length.toLocaleString()} / ${games.length.toLocaleString()} games`}
showTrafficLights={false}
controls={(
<SegmentedControl
ariaLabel="대국 결과 필터"
options={FILTER_OPTIONS}
value={filter}
onChange={setFilter}
className="max-w-[calc(100vw-3rem)] overflow-x-auto"
/>
)}
bodyClassName="p-3 md:p-4"
>
{filteredGames.length > 0 ? (
<div className="divide-y divide-[var(--color-line)]">
{filteredGames.map((game) => (
<HistoryRow key={game.gameId} game={game} />
))}
</div>
) : (
<div className="flex min-h-72 flex-col items-center justify-center text-center">
<Bot className="mb-3 text-[var(--color-accent)]" size={30} />
<p className="text-sm font-semibold text-[var(--color-text)]"> .</p>
<p className="mt-1 text-xs text-[var(--color-text-subtle)]"> .</p>
</div>
)}
</WindowSurface>
</ChessPageFrame>
);
}

View File

@@ -0,0 +1,362 @@
'use client';
import { type FormEvent, type ReactNode, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
Bot,
ChevronRight,
Clock3,
History,
Loader2,
LockKeyhole,
Puzzle,
Swords,
Trophy,
} from 'lucide-react';
import toast from 'react-hot-toast';
import { createChessGame, getChessGames, getChessGameStats } from '@/api/chess';
import { getTurnLabel } from '@/components/chess/ChessBoard';
import { formatChessDateTime, getChessErrorMessage, getChessOutcomeLabel, outcomeBadgeTones, outcomeLabels } from '@/components/chess/chessUi';
import MetricCard from '@/components/ui/MetricCard';
import SegmentedControl, { SegmentedControlOption } from '@/components/ui/SegmentedControl';
import StatusBadge from '@/components/ui/StatusBadge';
import WindowSurface from '@/components/ui/WindowSurface';
import { useAuthStore } from '@/store/authStore';
import { ChessColor, ChessGameCreateRequest, MaiaModel } from '@/types';
type ChessFormState = Required<Pick<ChessGameCreateRequest, 'rating' | 'playerColor' | 'model' | 'temperature' | 'topP'>>;
const COLOR_OPTIONS: readonly SegmentedControlOption<ChessColor>[] = [
{ label: '백', value: 'white' },
{ label: '흑', value: 'black' },
];
const MODEL_OPTIONS: readonly SegmentedControlOption<MaiaModel>[] = [
{ label: '3m', value: '3m' },
{ label: '5m', value: '5m' },
{ label: '23m', value: '23m' },
{ label: '79m', value: '79m' },
];
const DEFAULT_FORM: ChessFormState = {
rating: 1500,
playerColor: 'white',
model: '5m',
temperature: 0.8,
topP: 0.95,
};
const clampRating = (value: number) => Math.min(2600, Math.max(600, value));
function ChessPageFrame({ children }: { children: ReactNode }) {
return (
<main className="mx-auto flex w-full min-w-0 max-w-[1160px] flex-col gap-5 px-0 py-3 md:py-6">
{children}
</main>
);
}
function LoadingGate() {
return (
<ChessPageFrame>
<WindowSurface title="Maia Chess" showTrafficLights={false} bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center">
<Loader2 className="mb-3 animate-spin text-[var(--color-accent)]" size={30} />
<p className="text-sm font-semibold text-[var(--color-text)]"> .</p>
</WindowSurface>
</ChessPageFrame>
);
}
function LoginRequired() {
return (
<ChessPageFrame>
<WindowSurface title="Maia Chess" showTrafficLights={false} bodyClassName="p-6 md:p-8">
<div className="flex min-h-80 flex-col items-center justify-center text-center">
<div className="mb-4 flex h-16 w-16 items-center justify-center rounded-lg border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-control)]">
<LockKeyhole size={30} />
</div>
<h1 className="break-words text-2xl font-bold tracking-normal text-[var(--color-text)]"> .</h1>
<p className="mt-2 max-w-md break-words text-sm leading-6 text-[var(--color-text-muted)]">
Maia , , PGN은 .
</p>
<div className="mt-6 flex flex-wrap items-center justify-center gap-2">
<Link
href="/login?redirect=/chess"
className="inline-flex h-10 items-center gap-2 rounded-lg bg-[var(--color-accent)] px-4 text-sm font-semibold text-white transition hover:bg-[var(--color-accent-hover)]"
>
<LockKeyhole size={16} />
</Link>
<Link
href="/play/chess"
className="inline-flex h-10 items-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-4 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<Puzzle size={16} />
</Link>
</div>
</div>
</WindowSurface>
</ChessPageFrame>
);
}
function GameSummaryRow({
game,
}: {
game: {
gameId: string;
rating: number;
playerColor: ChessColor;
model: string;
outcome: keyof typeof outcomeLabels;
status: string;
movesCount: number;
updatedAt: string;
};
}) {
return (
<Link
href={`/chess/play/${game.gameId}`}
className="group flex min-w-0 items-center justify-between gap-3 rounded-lg px-2 py-3 transition hover:bg-[var(--card-bg)]"
>
<div className="min-w-0">
<div className="mb-1.5 flex min-w-0 flex-wrap items-center gap-2">
<StatusBadge tone={outcomeBadgeTones[game.outcome]}>{getChessOutcomeLabel(game.outcome, game.status)}</StatusBadge>
<span className="text-xs font-semibold text-[var(--color-text-subtle)]">
Maia {game.model} · {game.rating}
</span>
</div>
<p className="truncate text-sm font-semibold text-[var(--color-text)]">
{getTurnLabel(game.playerColor)} · {game.movesCount.toLocaleString()}
</p>
<p className="mt-0.5 truncate text-xs text-[var(--color-text-subtle)]">{formatChessDateTime(game.updatedAt)}</p>
</div>
<ChevronRight size={17} className="shrink-0 text-[var(--color-text-subtle)] transition group-hover:translate-x-0.5 group-hover:text-[var(--color-accent)]" />
</Link>
);
}
export default function ChessHomeClient() {
const router = useRouter();
const queryClient = useQueryClient();
const { isLoggedIn, _hasHydrated } = useAuthStore();
const [form, setForm] = useState<ChessFormState>(DEFAULT_FORM);
const statsQuery = useQuery({
queryKey: ['chess-game-stats'],
queryFn: getChessGameStats,
enabled: _hasHydrated && isLoggedIn,
retry: 0,
});
const gamesQuery = useQuery({
queryKey: ['chess-games', { page: 0, size: 6, sort: 'updatedAt,desc' }],
queryFn: () => getChessGames({ page: 0, size: 6, sort: 'updatedAt,desc' }),
enabled: _hasHydrated && isLoggedIn,
retry: 0,
});
const createMutation = useMutation({
mutationFn: (payload: ChessGameCreateRequest) => createChessGame(payload),
onSuccess: async (game) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['chess-games'] }),
queryClient.invalidateQueries({ queryKey: ['chess-game-stats'] }),
]);
router.push(`/chess/play/${game.gameId}`);
},
onError: (error) => {
toast.error(getChessErrorMessage(error, '대국을 생성하지 못했습니다.'));
},
});
const recentGames = gamesQuery.data?.content ?? [];
const stats = statsQuery.data;
const isLoadingData = statsQuery.isLoading || gamesQuery.isLoading;
const hasDataError = statsQuery.isError || gamesQuery.isError;
const dataErrorMessage = useMemo(() => {
if (statsQuery.error) return getChessErrorMessage(statsQuery.error, '통계를 불러오지 못했습니다.');
if (gamesQuery.error) return getChessErrorMessage(gamesQuery.error, '대국 기록을 불러오지 못했습니다.');
return '';
}, [gamesQuery.error, statsQuery.error]);
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
createMutation.mutate(form);
};
if (!_hasHydrated) return <LoadingGate />;
if (!isLoggedIn) return <LoginRequired />;
return (
<ChessPageFrame>
<section className="flex min-w-0 flex-col gap-2 border-b border-[var(--color-line)] pb-5">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2 text-[var(--color-accent)]">
<Swords size={24} className="shrink-0" />
<h1 className="min-w-0 break-words text-2xl font-bold tracking-normal text-[var(--color-text)] md:text-3xl">
Maia
</h1>
</div>
<div className="flex shrink-0 flex-wrap items-center gap-2">
<Link
href="/chess/history"
className="inline-flex h-9 items-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<History size={16} />
</Link>
<Link
href="/play/chess"
className="inline-flex h-9 items-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]"
>
<Puzzle size={16} />
</Link>
</div>
</div>
<p className="max-w-2xl break-words text-sm leading-6 text-[var(--color-text-muted)]">
Maia3 . FEN으로 .
</p>
</section>
<section className="grid min-w-0 gap-3 sm:grid-cols-2 xl:grid-cols-5">
<MetricCard label="전체" value={stats?.total ?? (isLoadingData ? null : 0)} icon={<Trophy size={18} />} />
<MetricCard label="진행중" value={stats?.inProgress ?? (isLoadingData ? null : 0)} icon={<Clock3 size={18} />} />
<MetricCard label="승" value={stats?.wins ?? (isLoadingData ? null : 0)} />
<MetricCard label="패" value={stats?.losses ?? (isLoadingData ? null : 0)} />
<MetricCard label="무" value={stats?.draws ?? (isLoadingData ? null : 0)} />
</section>
{hasDataError && (
<div className="rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm font-semibold text-red-700 dark:text-red-300">
{dataErrorMessage}
</div>
)}
<section className="grid min-w-0 items-start gap-5 lg:grid-cols-[minmax(0,1fr)_22rem]">
<WindowSurface title="New Game" showTrafficLights={false} bodyClassName="p-4 md:p-5">
<form onSubmit={handleSubmit} className="space-y-5">
<div>
<div className="mb-2 flex items-center justify-between gap-3">
<label htmlFor="chess-rating" className="text-sm font-semibold text-[var(--color-text)]">
</label>
<span className="rounded-full bg-[var(--color-accent-soft)] px-3 py-1 text-sm font-bold tabular-nums text-[var(--color-accent)]">
{form.rating}
</span>
</div>
<input
id="chess-rating"
type="range"
min={600}
max={2600}
step={50}
value={form.rating}
onChange={(event) => setForm((previous) => ({ ...previous, rating: clampRating(Number(event.target.value)) }))}
className="w-full accent-[var(--color-accent)]"
/>
<input
type="number"
min={600}
max={2600}
step={50}
value={form.rating}
onChange={(event) => setForm((previous) => ({ ...previous, rating: clampRating(Number(event.target.value) || DEFAULT_FORM.rating) }))}
className="mt-3 h-10 w-full rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text)] outline-none transition focus:border-[var(--color-accent)]"
/>
</div>
<div className="grid min-w-0 gap-4 md:grid-cols-2">
<div className="min-w-0">
<p className="mb-2 text-sm font-semibold text-[var(--color-text)]"> </p>
<SegmentedControl
ariaLabel="내 색상"
options={COLOR_OPTIONS}
value={form.playerColor}
onChange={(playerColor) => setForm((previous) => ({ ...previous, playerColor }))}
className="w-full justify-center"
/>
</div>
<div className="min-w-0">
<p className="mb-2 text-sm font-semibold text-[var(--color-text)]"></p>
<SegmentedControl
ariaLabel="Maia 모델"
options={MODEL_OPTIONS}
value={form.model}
onChange={(model) => setForm((previous) => ({ ...previous, model }))}
className="w-full justify-center"
/>
</div>
</div>
<details className="rounded-lg border border-[var(--color-line)] bg-black/[0.025] px-4 py-3 dark:bg-white/[0.06]">
<summary className="cursor-pointer text-sm font-semibold text-[var(--color-text-muted)]">
</summary>
<div className="mt-4 grid gap-4 md:grid-cols-2">
<label className="min-w-0 text-sm font-semibold text-[var(--color-text)]">
Temperature
<input
type="number"
min={0}
max={2}
step={0.05}
value={form.temperature}
onChange={(event) => setForm((previous) => ({ ...previous, temperature: Number(event.target.value) }))}
className="mt-2 h-10 w-full rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-3 text-sm text-[var(--color-text)] outline-none transition focus:border-[var(--color-accent)]"
/>
</label>
<label className="min-w-0 text-sm font-semibold text-[var(--color-text)]">
Top P
<input
type="number"
min={0}
max={1}
step={0.01}
value={form.topP}
onChange={(event) => setForm((previous) => ({ ...previous, topP: Number(event.target.value) }))}
className="mt-2 h-10 w-full rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-3 text-sm text-[var(--color-text)] outline-none transition focus:border-[var(--color-accent)]"
/>
</label>
</div>
</details>
<button
type="submit"
disabled={createMutation.isPending}
className="inline-flex h-11 w-full items-center justify-center gap-2 rounded-lg bg-[var(--color-accent)] px-4 text-sm font-bold text-white transition hover:bg-[var(--color-accent-hover)] disabled:cursor-not-allowed disabled:opacity-60"
>
{createMutation.isPending ? <Loader2 className="animate-spin" size={18} /> : <Bot size={18} />}
</button>
</form>
</WindowSurface>
<WindowSurface title="Recent Games" showTrafficLights={false} as="aside" bodyClassName="p-3 md:p-4">
{gamesQuery.isLoading ? (
<div className="flex min-h-56 flex-col items-center justify-center text-center">
<Loader2 className="mb-3 animate-spin text-[var(--color-accent)]" size={26} />
<p className="text-sm font-semibold text-[var(--color-text)]"> .</p>
</div>
) : recentGames.length > 0 ? (
<div className="divide-y divide-[var(--color-line)]">
{recentGames.map((game) => (
<GameSummaryRow key={game.gameId} game={game} />
))}
</div>
) : (
<div className="flex min-h-56 flex-col items-center justify-center text-center">
<Bot className="mb-3 text-[var(--color-accent)]" size={28} />
<p className="text-sm font-semibold text-[var(--color-text)]"> .</p>
<p className="mt-1 text-xs text-[var(--color-text-subtle)]"> Maia .</p>
</div>
)}
</WindowSurface>
</section>
</ChessPageFrame>
);
}

View File

@@ -1,8 +1,9 @@
'use client'; 'use client';
import type { CSSProperties, ReactNode } from 'react';
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { Chess as ChessGame, type Color, type Move, type PieceSymbol, type Square } from 'chess.js'; import { Chess as ChessGame, type Color, type Move, type Square } from 'chess.js';
import { clsx } from 'clsx'; import { clsx } from 'clsx';
import { import {
AlertCircle, AlertCircle,
@@ -14,42 +15,15 @@ import {
Target, Target,
} from 'lucide-react'; } from 'lucide-react';
import { getTodayChessPuzzle } from '@/api/chess'; import { getTodayChessPuzzle } from '@/api/chess';
import ChessBoard, { BOARD_SQUARES, type MoveSquares } from '@/components/chess/ChessBoard';
import WindowSurface from '@/components/ui/WindowSurface'; import WindowSurface from '@/components/ui/WindowSurface';
import { type ChessPuzzle } from '@/types'; import { type ChessPuzzle } from '@/types';
type FeedbackTone = 'neutral' | 'success' | 'error'; type FeedbackTone = 'neutral' | 'success' | 'error';
const TIMEZONE = 'Asia/Seoul'; const TIMEZONE = 'Asia/Seoul';
const FILES = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] as const; const BOARD_SIZE_STYLE: CSSProperties = {
const RANKS = [8, 7, 6, 5, 4, 3, 2, 1] as const; width: 'min(100%, clamp(19rem, min(52vw, calc(100svh - 22.5rem)), 30rem))',
const BOARD_SQUARES = RANKS.flatMap((rank) => FILES.map((file) => `${file}${rank}` as Square));
const PIECE_SYMBOLS: Record<Color, Record<PieceSymbol, string>> = {
w: {
k: '♔',
q: '♕',
r: '♖',
b: '♗',
n: '♘',
p: '♙',
},
b: {
k: '♚',
q: '♛',
r: '♜',
b: '♝',
n: '♞',
p: '♟',
},
};
const PIECE_NAMES: Record<PieceSymbol, string> = {
k: '킹',
q: '퀸',
r: '룩',
b: '비숍',
n: '나이트',
p: '폰',
}; };
const turnLabel = (color: Color) => (color === 'w' ? '백' : '흑'); const turnLabel = (color: Color) => (color === 'w' ? '백' : '흑');
@@ -59,14 +33,14 @@ const getReadyFeedback = (puzzle: ChessPuzzle): { tone: FeedbackTone; message: s
return { return {
tone: 'neutral', tone: 'neutral',
message: `${turnLabel(game.turn())} 차례 · 체크메이트 한 수`, message: `${turnLabel(game.turn())} 차례. 체크메이트를 찾으세요.`,
}; };
}; };
const getSquareLabel = (square: Square, piece?: { color: Color; type: PieceSymbol }) => { const getPreferredMove = (moves: Move[], to: Square) => {
if (!piece) return `${square} 빈 칸`; const candidates = moves.filter((move) => move.to === to);
return `${square} ${turnLabel(piece.color)} ${PIECE_NAMES[piece.type]}`; return candidates.find((move) => move.promotion === 'q') ?? candidates[0] ?? null;
}; };
const formatDate = (value: string) => { const formatDate = (value: string) => {
@@ -85,57 +59,76 @@ const formatDate = (value: string) => {
function PageHeader() { function PageHeader() {
return ( return (
<section className="flex flex-col gap-2 border-b border-[var(--color-line)] pb-6"> <section className="flex min-w-0 flex-col gap-2 border-b border-[var(--color-line)] pb-5">
<div className="flex items-center gap-2 text-[var(--color-accent)]"> <div className="flex min-w-0 items-center gap-2 text-[var(--color-accent)]">
<Target size={23} /> <Target size={23} className="shrink-0" />
<h1 className="text-2xl font-bold tracking-normal text-[var(--color-text)] md:text-3xl"> <h1 className="min-w-0 break-words text-2xl font-bold tracking-normal text-[var(--color-text)] md:text-3xl">
</h1> </h1>
</div> </div>
<p className="max-w-2xl text-sm leading-6 text-[var(--color-text-muted)]"> <p className="max-w-2xl break-words text-sm leading-6 text-[var(--color-text-muted)]">
. .
</p> </p>
</section> </section>
); );
} }
function ChessPageFrame({ children }: { children: ReactNode }) {
return (
<main className="mx-auto flex w-full min-w-0 max-w-[1160px] flex-col gap-5 px-0 py-3 md:py-6">
{children}
</main>
);
}
function BoardWindow({ children }: { children: ReactNode }) {
return (
<WindowSurface title="Board" showTrafficLights={false} bodyClassName="p-2 md:p-3">
<div className="mx-auto max-w-full" style={BOARD_SIZE_STYLE}>
{children}
</div>
</WindowSurface>
);
}
function LoadingState() { function LoadingState() {
return ( return (
<main className="mx-auto flex w-full flex-col gap-6 px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6"> <ChessPageFrame>
<PageHeader /> <PageHeader />
<section className="grid items-start gap-5 lg:grid-cols-[minmax(0,1fr)_21rem]"> <section className="grid min-w-0 items-start justify-center gap-5 lg:grid-cols-[minmax(0,30rem)_20rem]">
<WindowSurface title="Board" bodyClassName="p-3 md:p-5"> <BoardWindow>
<div className="mx-auto grid aspect-square w-full max-w-[min(78vh,680px)] grid-cols-8 overflow-hidden rounded-lg border border-[var(--color-line)]"> <div className="grid aspect-square w-full grid-cols-8 overflow-hidden rounded-lg border border-[var(--color-line)]">
{BOARD_SQUARES.map((square, index) => ( {BOARD_SQUARES.map((square, index) => (
<div <div
key={square} key={square}
className={clsx( className={clsx(
'aspect-square animate-pulse', 'aspect-square animate-pulse',
(index + Math.floor(index / 8)) % 2 === 0 ? 'bg-black/[0.06]' : 'bg-black/[0.12]', (index + Math.floor(index / 8)) % 2 === 0
'dark:bg-white/[0.08]', ? 'bg-[#edf2f5] dark:bg-[#c8d0d6]'
: 'bg-[#7fa18b] dark:bg-[#415d52]',
)} )}
/> />
))} ))}
</div> </div>
</WindowSurface> </BoardWindow>
<WindowSurface title="Puzzle" as="aside" bodyClassName="flex min-h-72 flex-col items-center justify-center p-5 text-center"> <WindowSurface title="Puzzle" showTrafficLights={false} as="aside" bodyClassName="flex min-h-72 flex-col items-center justify-center p-5 text-center">
<Loader2 className="mb-3 animate-spin text-[var(--color-accent)]" size={28} /> <Loader2 className="mb-3 animate-spin text-[var(--color-accent)]" size={28} />
<p className="text-sm font-semibold text-[var(--color-text)]"> .</p> <p className="text-sm font-semibold text-[var(--color-text)]"> .</p>
</WindowSurface> </WindowSurface>
</section> </section>
</main> </ChessPageFrame>
); );
} }
function ErrorState({ onRetry }: { onRetry: () => void }) { function ErrorState({ onRetry }: { onRetry: () => void }) {
return ( return (
<main className="mx-auto flex w-full flex-col gap-6 px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6"> <ChessPageFrame>
<PageHeader /> <PageHeader />
<WindowSurface title="Puzzle" bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center"> <WindowSurface title="Puzzle" showTrafficLights={false} bodyClassName="flex min-h-80 flex-col items-center justify-center p-8 text-center">
<AlertCircle className="mb-3 text-red-500" size={30} /> <AlertCircle className="mb-3 text-red-500" size={30} />
<h2 className="text-lg font-bold text-[var(--color-text)]"> .</h2> <h2 className="break-words text-lg font-bold text-[var(--color-text)]"> .</h2>
<p className="mt-2 max-w-md text-sm leading-6 text-[var(--color-text-muted)]"> <p className="mt-2 max-w-md break-words text-sm leading-6 text-[var(--color-text-muted)]">
API가 . API가 .
</p> </p>
<button <button
type="button" type="button"
@@ -146,7 +139,7 @@ function ErrorState({ onRetry }: { onRetry: () => void }) {
</button> </button>
</WindowSurface> </WindowSurface>
</main> </ChessPageFrame>
); );
} }
@@ -154,7 +147,7 @@ function ChessPuzzleBoard({ puzzle }: { puzzle: ChessPuzzle }) {
const [currentFen, setCurrentFen] = useState(puzzle.fen); const [currentFen, setCurrentFen] = useState(puzzle.fen);
const [selectedSquare, setSelectedSquare] = useState<Square | null>(null); const [selectedSquare, setSelectedSquare] = useState<Square | null>(null);
const [solved, setSolved] = useState(false); const [solved, setSolved] = useState(false);
const [lastMoveSquares, setLastMoveSquares] = useState<{ from: Square; to: Square } | null>(null); const [lastMoveSquares, setLastMoveSquares] = useState<MoveSquares | null>(null);
const [feedback, setFeedback] = useState(getReadyFeedback(puzzle)); const [feedback, setFeedback] = useState(getReadyFeedback(puzzle));
const game = useMemo(() => new ChessGame(currentFen), [currentFen]); const game = useMemo(() => new ChessGame(currentFen), [currentFen]);
@@ -184,8 +177,19 @@ function ChessPuzzleBoard({ puzzle }: { puzzle: ChessPuzzle }) {
}); });
}; };
const isDraggablePuzzleSquare = (square: Square) => {
if (solved) return false;
const piece = game.get(square);
return piece?.color === game.turn();
};
const tryMove = (from: Square, to: Square) => { const tryMove = (from: Square, to: Square) => {
const candidate = legalMoves.find((move) => move.to === to); if (solved || !isDraggablePuzzleSquare(from)) return;
const movesFromSquare = game.moves({ square: from, verbose: true });
const candidate = getPreferredMove(movesFromSquare, to);
if (!candidate) { if (!candidate) {
setFeedback({ setFeedback({
@@ -212,7 +216,7 @@ function ChessPuzzleBoard({ puzzle }: { puzzle: ChessPuzzle }) {
setLastMoveSquares(null); setLastMoveSquares(null);
setFeedback({ setFeedback({
tone: 'error', tone: 'error',
message: `${move.san} 아직 메이트가 아닙니다.`, message: `${move.san} 아직 메이트가 아닙니다.`,
}); });
} catch { } catch {
setFeedback({ setFeedback({
@@ -263,101 +267,40 @@ function ChessPuzzleBoard({ puzzle }: { puzzle: ChessPuzzle }) {
}; };
return ( return (
<main className="mx-auto flex w-full flex-col gap-6 px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6"> <ChessPageFrame>
<PageHeader /> <PageHeader />
<section className="grid items-start gap-5 lg:grid-cols-[minmax(0,1fr)_21rem]"> <section className="grid min-w-0 items-start justify-center gap-5 lg:grid-cols-[minmax(0,30rem)_20rem]">
<WindowSurface title="Board" bodyClassName="p-3 md:p-5"> <BoardWindow>
<div className="mx-auto grid aspect-square w-full max-w-[min(78vh,680px)] grid-cols-8 overflow-hidden rounded-lg border border-[var(--color-line)] shadow-[var(--shadow-control)]"> <ChessBoard
{BOARD_SQUARES.map((square, index) => { fen={currentFen}
const piece = game.get(square); selectedSquare={selectedSquare}
const file = square[0]; legalTargets={legalTargets}
const rank = square[1]; lastMoveSquares={lastMoveSquares}
const fileIndex = index % 8; disabled={solved}
const rankIndex = Math.floor(index / 8); isDraggableSquare={isDraggablePuzzleSquare}
const isLight = (fileIndex + rankIndex) % 2 === 0; onSquareClick={handleSquareClick}
const isSelected = selectedSquare === square; onSquareDrop={tryMove}
const isTarget = legalTargets.has(square);
const isLastMoveSquare = lastMoveSquares?.from === square || lastMoveSquares?.to === square;
return (
<button
key={square}
type="button"
onClick={() => handleSquareClick(square)}
className={clsx(
'relative flex aspect-square items-center justify-center overflow-hidden text-[clamp(1.75rem,8vw,4.8rem)] leading-none transition',
isLight ? 'bg-[#eef0e6]' : 'bg-[#5f8d68]',
isSelected && 'z-10 ring-4 ring-[var(--color-accent)] ring-inset',
isLastMoveSquare && 'bg-[var(--color-accent-soft)]',
!solved && 'hover:brightness-105 focus-visible:z-20',
)}
aria-label={getSquareLabel(square, piece)}
aria-pressed={isSelected}
>
{file === 'a' && (
<span
className={clsx(
'absolute left-1.5 top-1 text-[10px] font-bold leading-none',
isLight ? 'text-[#5f8d68]' : 'text-[#eef0e6]',
)}
>
{rank}
</span>
)}
{rank === '1' && (
<span
className={clsx(
'absolute bottom-1 right-1.5 text-[10px] font-bold leading-none',
isLight ? 'text-[#5f8d68]' : 'text-[#eef0e6]',
)}
>
{file}
</span>
)}
{isTarget && (
<span
className={clsx(
'absolute h-4 w-4 rounded-full',
piece ? 'h-full w-full rounded-none ring-4 ring-black/20 ring-inset' : 'bg-black/20',
)}
/> />
)} </BoardWindow>
{piece && (
<span
className={clsx(
'relative z-10 select-none',
piece.color === 'w'
? 'text-[#fbfbfb] [text-shadow:0_1px_2px_rgb(0_0_0_/_0.55)]'
: 'text-[#202124] [text-shadow:0_1px_1px_rgb(255_255_255_/_0.22)]',
)}
>
{PIECE_SYMBOLS[piece.color][piece.type]}
</span>
)}
</button>
);
})}
</div>
</WindowSurface>
<WindowSurface title="Puzzle" as="aside" bodyClassName="p-5"> <WindowSurface title="Puzzle" showTrafficLights={false} as="aside" bodyClassName="p-4 md:p-5">
<div className="mb-4 flex items-start justify-between gap-3"> <div className="mb-4 flex min-w-0 items-start justify-between gap-3">
<div> <div className="min-w-0">
<p className="text-xs font-semibold uppercase text-[var(--color-text-subtle)]"> <p className="text-xs font-semibold uppercase tracking-normal text-[var(--color-text-subtle)]">
{formatDate(puzzle.date)} {formatDate(puzzle.date)}
</p> </p>
<h2 className="mt-1 text-xl font-bold tracking-normal text-[var(--color-text)]"> <h2 className="mt-1 break-words text-xl font-bold tracking-normal text-[var(--color-text)]">
{puzzle.title} {puzzle.title}
</h2> </h2>
<p className="mt-1 text-sm text-[var(--color-text-muted)]">{puzzle.theme}</p> <p className="mt-1 break-words text-sm text-[var(--color-text-muted)]">{puzzle.theme}</p>
</div> </div>
{solved && <CheckCircle2 size={24} className="shrink-0 text-emerald-500" />} {solved && <CheckCircle2 size={24} className="shrink-0 text-emerald-500" />}
</div> </div>
<div <div
className={clsx( className={clsx(
'mb-4 rounded-lg border px-3 py-3 text-sm font-semibold leading-6', 'mb-4 break-words rounded-lg border px-3 py-3 text-sm font-semibold leading-6',
feedback.tone === 'success' && 'border-emerald-500/25 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300', feedback.tone === 'success' && 'border-emerald-500/25 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',
feedback.tone === 'error' && 'border-red-500/25 bg-red-500/10 text-red-700 dark:text-red-300', feedback.tone === 'error' && 'border-red-500/25 bg-red-500/10 text-red-700 dark:text-red-300',
feedback.tone === 'neutral' && 'border-[var(--color-line)] bg-black/[0.025] text-[var(--color-text-muted)] dark:bg-white/[0.06]', feedback.tone === 'neutral' && 'border-[var(--color-line)] bg-black/[0.025] text-[var(--color-text-muted)] dark:bg-white/[0.06]',
@@ -367,13 +310,13 @@ function ChessPuzzleBoard({ puzzle }: { puzzle: ChessPuzzle }) {
</div> </div>
<dl className="grid grid-cols-2 gap-3 text-sm"> <dl className="grid grid-cols-2 gap-3 text-sm">
<div className="rounded-lg bg-black/[0.025] px-3 py-2 dark:bg-white/[0.06]"> <div className="min-w-0 rounded-lg bg-black/[0.025] px-3 py-2 dark:bg-white/[0.06]">
<dt className="text-xs text-[var(--color-text-subtle)]"></dt> <dt className="text-xs text-[var(--color-text-subtle)]"></dt>
<dd className="mt-0.5 font-semibold text-[var(--color-text)]">{puzzle.rating}</dd> <dd className="mt-0.5 truncate font-semibold text-[var(--color-text)]">{puzzle.rating}</dd>
</div> </div>
<div className="rounded-lg bg-black/[0.025] px-3 py-2 dark:bg-white/[0.06]"> <div className="min-w-0 rounded-lg bg-black/[0.025] px-3 py-2 dark:bg-white/[0.06]">
<dt className="text-xs text-[var(--color-text-subtle)]"></dt> <dt className="text-xs text-[var(--color-text-subtle)]"></dt>
<dd className="mt-0.5 font-semibold text-[var(--color-text)]"> <dd className="mt-0.5 truncate font-semibold text-[var(--color-text)]">
{solved ? puzzle.answer : '숨김'} {solved ? puzzle.answer : '숨김'}
</dd> </dd>
</div> </div>
@@ -404,14 +347,14 @@ function ChessPuzzleBoard({ puzzle }: { puzzle: ChessPuzzle }) {
href={puzzle.sourceUrl} href={puzzle.sourceUrl}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="mt-4 inline-flex items-center gap-1.5 text-xs font-semibold text-[var(--color-text-subtle)] transition hover:text-[var(--color-accent)]" className="mt-4 inline-flex max-w-full items-center gap-1.5 break-words text-xs font-semibold text-[var(--color-text-subtle)] transition hover:text-[var(--color-accent)]"
> >
Lichess <span className="truncate">Lichess </span>
<ExternalLink size={13} /> <ExternalLink size={13} className="shrink-0" />
</a> </a>
</WindowSurface> </WindowSurface>
</section> </section>
</main> </ChessPageFrame>
); );
} }

View File

@@ -0,0 +1,60 @@
import axios from 'axios';
import { ChessOutcome } from '@/types';
export type OutcomeFilter = 'ALL' | 'IN_PROGRESS' | 'WIN' | 'LOSS' | 'DRAW';
export const outcomeLabels: Record<ChessOutcome, string> = {
IN_PROGRESS: '진행중',
WIN: '승',
LOSS: '패',
DRAW: '무',
UNKNOWN: '미정',
};
export const outcomeBadgeTones: Record<ChessOutcome, 'neutral' | 'info' | 'success' | 'warning' | 'danger'> = {
IN_PROGRESS: 'info',
WIN: 'success',
LOSS: 'danger',
DRAW: 'warning',
UNKNOWN: 'neutral',
};
export const getChessOutcomeLabel = (outcome: ChessOutcome, status?: string) => {
if (status === 'RESIGNED' && outcome === 'LOSS') return '기권패';
return outcomeLabels[outcome];
};
export const formatChessDateTime = (value?: string) => {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat('ko-KR', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(date);
};
export const getChessErrorMessage = (error: unknown, fallback = '요청을 처리하지 못했습니다.') => {
if (axios.isAxiosError(error)) {
if (error.response?.status === 401 || error.response?.status === 403) {
return '로그인이 필요합니다.';
}
const message = error.response?.data?.message;
if (typeof message === 'string' && message.trim()) return message;
}
if (error instanceof Error && error.message) return error.message;
return fallback;
};
export const isAuthError = (error: unknown) => {
return axios.isAxiosError(error) && (error.response?.status === 401 || error.response?.status === 403);
};

View File

@@ -163,7 +163,7 @@ export default function CommentItem({ comment, postSlug, depth = 0 }: CommentIte
</button> </button>
<button <button
onClick={() => { setIsDeleting(false); setGuestPassword(''); }} onClick={() => { setIsDeleting(false); setGuestPassword(''); }}
className="rounded-full p-1 text-[var(--color-text-subtle)] hover:bg-black/[0.06] dark:hover:bg-white/10" className="rounded-full p-1 text-[var(--color-text-subtle)] hover:bg-[var(--card-bg)]"
> >
<X size={14} /> <X size={14} />
</button> </button>

View File

@@ -1,63 +1,342 @@
'use client'; 'use client';
import { type CSSProperties, type FocusEvent, useCallback, useEffect, useRef, useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation'; import { usePathname, useRouter } from 'next/navigation';
import { clsx } from 'clsx'; import { clsx } from 'clsx';
import { Archive, Crown, Home, LogIn, LogOut, PenLine, Settings, UserPlus } from 'lucide-react'; import type { LucideIcon } from 'lucide-react';
import {
Archive,
Crown,
Home,
LogIn,
LogOut,
Menu,
MoreHorizontal,
PenLine,
Pin,
PinOff,
Settings,
UserPlus,
} from 'lucide-react';
import ThemeToggle from '@/components/theme/ThemeToggle';
import { useAuthStore } from '@/store/authStore'; import { useAuthStore } from '@/store/authStore';
interface DesktopDockProps { interface DesktopDockProps {
isSidebarCollapsed: boolean; onOpenMobileMenu: () => void;
} }
type DockItem = { type DockAction = {
key: string; key: string;
href?: string; href?: string;
label: string; label: string;
icon: typeof Home; icon: LucideIcon;
isActive?: (pathname: string) => boolean; isActive?: (pathname: string) => boolean;
onClick?: () => void; onClick?: () => void;
}; };
export default function DesktopDock({ isSidebarCollapsed }: DesktopDockProps) { const isActivePath = (target: string) => (pathname: string) => {
if (target === '/') return pathname === '/';
return pathname.startsWith(target);
};
const DOCK_LEAVE_DELAY_MS = 120;
const DOCK_COLLAPSE_MS = 560;
const DOCK_PINNED_STORAGE_KEY = 'dock-pinned-v2';
type DockToneStyle = CSSProperties & {
'--dock-item-bg': string;
'--dock-item-bg-hover': string;
'--dock-item-bg-active': string;
'--dock-item-border': string;
'--dock-item-border-hover': string;
'--dock-item-fg': string;
'--dock-item-fg-strong': string;
'--dock-item-ring': string;
};
const createDockTone = (
bg: string,
hover: string,
active: string,
border: string,
borderHover: string,
fg: string,
fgStrong: string,
ring: string,
): DockToneStyle => ({
'--dock-item-bg': bg,
'--dock-item-bg-hover': hover,
'--dock-item-bg-active': active,
'--dock-item-border': border,
'--dock-item-border-hover': borderHover,
'--dock-item-fg': fg,
'--dock-item-fg-strong': fgStrong,
'--dock-item-ring': ring,
});
const dockGlassTone = createDockTone(
'rgba(255, 255, 255, 0.24)',
'rgba(255, 255, 255, 0.36)',
'rgba(255, 255, 255, 0.46)',
'rgba(255, 255, 255, 0.2)',
'rgba(255, 255, 255, 0.34)',
'var(--color-text-muted)',
'var(--color-text)',
'rgba(255, 255, 255, 0.34)',
);
const homeDockTone = createDockTone(
'rgba(255, 255, 255, 0.58)',
'rgba(255, 255, 255, 0.68)',
'rgba(255, 255, 255, 0.76)',
'rgba(255, 255, 255, 0.28)',
'rgba(255, 255, 255, 0.46)',
'var(--color-text-muted)',
'var(--color-text)',
'rgba(255, 255, 255, 0.42)',
);
const dockToneStyles: Record<string, DockToneStyle> = {
home: homeDockTone,
archive: createDockTone('rgba(222, 216, 255, 0.54)', 'rgba(222, 216, 255, 0.64)', 'rgba(222, 216, 255, 0.72)', 'rgba(255, 255, 255, 0.26)', 'rgba(151, 132, 214, 0.34)', '#6f668f', '#514274', 'rgba(151, 132, 214, 0.2)'),
chess: createDockTone('rgba(255, 229, 162, 0.54)', 'rgba(255, 229, 162, 0.64)', 'rgba(255, 229, 162, 0.72)', 'rgba(255, 255, 255, 0.28)', 'rgba(184, 134, 42, 0.34)', '#7b6d4a', '#665125', 'rgba(184, 134, 42, 0.2)'),
admin: createDockTone('rgba(192, 226, 255, 0.54)', 'rgba(192, 226, 255, 0.64)', 'rgba(192, 226, 255, 0.72)', 'rgba(255, 255, 255, 0.27)', 'rgba(81, 145, 195, 0.34)', '#627f96', '#3f6686', 'rgba(81, 145, 195, 0.2)'),
write: createDockTone('rgba(255, 209, 184, 0.54)', 'rgba(255, 209, 184, 0.64)', 'rgba(255, 209, 184, 0.72)', 'rgba(255, 255, 255, 0.28)', 'rgba(187, 106, 70, 0.34)', '#8c705f', '#724d38', 'rgba(187, 106, 70, 0.2)'),
login: createDockTone('rgba(190, 236, 238, 0.54)', 'rgba(190, 236, 238, 0.64)', 'rgba(190, 236, 238, 0.72)', 'rgba(255, 255, 255, 0.27)', 'rgba(68, 150, 158, 0.34)', '#63898c', '#446d72', 'rgba(68, 150, 158, 0.2)'),
signup: createDockTone('rgba(237, 207, 250, 0.54)', 'rgba(237, 207, 250, 0.64)', 'rgba(237, 207, 250, 0.72)', 'rgba(255, 255, 255, 0.27)', 'rgba(153, 91, 176, 0.34)', '#846c8e', '#684a78', 'rgba(153, 91, 176, 0.2)'),
logout: createDockTone('rgba(255, 207, 216, 0.54)', 'rgba(255, 207, 216, 0.64)', 'rgba(255, 207, 216, 0.72)', 'rgba(255, 255, 255, 0.28)', 'rgba(188, 84, 99, 0.34)', '#8f6970', '#714850', 'rgba(188, 84, 99, 0.2)'),
pin: createDockTone('rgba(255, 219, 170, 0.56)', 'rgba(255, 219, 170, 0.66)', 'rgba(255, 219, 170, 0.74)', 'rgba(255, 255, 255, 0.28)', 'rgba(184, 118, 44, 0.36)', '#8a704e', '#6b4f2d', 'rgba(184, 118, 44, 0.22)'),
menu: createDockTone('rgba(213, 234, 203, 0.54)', 'rgba(213, 234, 203, 0.64)', 'rgba(213, 234, 203, 0.72)', 'rgba(255, 255, 255, 0.27)', 'rgba(98, 143, 80, 0.34)', '#6f8366', '#526f44', 'rgba(98, 143, 80, 0.2)'),
more: createDockTone('rgba(210, 228, 255, 0.54)', 'rgba(210, 228, 255, 0.64)', 'rgba(210, 228, 255, 0.72)', 'rgba(255, 255, 255, 0.27)', 'rgba(86, 126, 183, 0.34)', '#6d7f98', '#4f688d', 'rgba(86, 126, 183, 0.2)'),
default: dockGlassTone,
};
const getDockToneStyle = (key: string) => dockToneStyles[key] ?? dockToneStyles.default;
export default function DesktopDock({ onOpenMobileMenu }: DesktopDockProps) {
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter(); const router = useRouter();
const { isLoggedIn, role, logout, _hasHydrated } = useAuthStore(); const { isLoggedIn, role, logout, _hasHydrated } = useAuthStore();
const [isPinned, setIsPinned] = useState(true);
const [isMoreOpen, setIsMoreOpen] = useState(false);
const [isDockHovered, setIsDockHovered] = useState(false);
const [isDockFocused, setIsDockFocused] = useState(false);
const [isDockClosing, setIsDockClosing] = useState(false);
const isPinnedRef = useRef(isPinned);
const dockZoneRef = useRef<HTMLDivElement>(null);
const dockLeaveTimerRef = useRef<number | null>(null);
const dockCollapseTimerRef = useRef<number | null>(null);
const pinToggleStartedByPointerRef = useRef(false);
const isAdmin = _hasHydrated && isLoggedIn && role?.includes('ADMIN'); const isAdmin = _hasHydrated && isLoggedIn && role?.includes('ADMIN');
const isDockOpen = isPinned || isDockHovered || isDockFocused;
const isDockRangeExpanded = isDockOpen || isDockClosing;
const clearDockTimers = useCallback(() => {
if (dockLeaveTimerRef.current !== null) {
window.clearTimeout(dockLeaveTimerRef.current);
dockLeaveTimerRef.current = null;
}
if (dockCollapseTimerRef.current !== null) {
window.clearTimeout(dockCollapseTimerRef.current);
dockCollapseTimerRef.current = null;
}
}, []);
const expandDock = () => {
clearDockTimers();
setIsDockClosing(false);
setIsDockHovered(true);
};
const startDockCollapse = useCallback(() => {
clearDockTimers();
setIsDockHovered(false);
setIsDockClosing(true);
dockCollapseTimerRef.current = window.setTimeout(() => {
setIsDockClosing(false);
dockCollapseTimerRef.current = null;
}, DOCK_COLLAPSE_MS);
}, [clearDockTimers]);
const scheduleDockCollapse = () => {
if (isPinned || isDockFocused) return;
clearDockTimers();
dockLeaveTimerRef.current = window.setTimeout(() => {
startDockCollapse();
}, DOCK_LEAVE_DELAY_MS);
};
const blurFocusedDockItem = useCallback(() => {
if (
document.activeElement instanceof HTMLElement &&
dockZoneRef.current?.contains(document.activeElement)
) {
document.activeElement.blur();
}
}, []);
const releaseUnpinnedDockAfterNavigation = useCallback(() => {
if (isPinnedRef.current) return;
const isPointerInsideDock = dockZoneRef.current?.matches(':hover') ?? false;
blurFocusedDockItem();
setIsDockFocused(false);
if (isPointerInsideDock) {
clearDockTimers();
setIsDockClosing(false);
setIsDockHovered(true);
return;
}
startDockCollapse();
}, [blurFocusedDockItem, clearDockTimers, startDockCollapse]);
useEffect(() => {
isPinnedRef.current = isPinned;
}, [isPinned]);
useEffect(() => {
const frameId = window.requestAnimationFrame(() => {
const savedValue = window.localStorage.getItem(DOCK_PINNED_STORAGE_KEY);
const nextValue = savedValue === null ? true : savedValue === 'true';
isPinnedRef.current = nextValue;
setIsPinned(nextValue);
});
return () => window.cancelAnimationFrame(frameId);
}, []);
useEffect(() => {
const frameId = window.requestAnimationFrame(() => {
setIsMoreOpen(false);
releaseUnpinnedDockAfterNavigation();
});
return () => window.cancelAnimationFrame(frameId);
}, [pathname, releaseUnpinnedDockAfterNavigation]);
useEffect(() => {
return () => clearDockTimers();
}, [clearDockTimers]);
const handlePinnedChange = () => {
const nextValue = !isPinned;
const startedByPointer = pinToggleStartedByPointerRef.current;
const isPointerInsideDock = dockZoneRef.current?.matches(':hover') ?? false;
pinToggleStartedByPointerRef.current = false;
window.localStorage.setItem(DOCK_PINNED_STORAGE_KEY, String(nextValue));
clearDockTimers();
isPinnedRef.current = nextValue;
setIsPinned(nextValue);
if (nextValue) {
setIsDockClosing(false);
setIsDockHovered(false);
return;
}
if (startedByPointer) {
setIsDockFocused(false);
blurFocusedDockItem();
}
if (isPointerInsideDock) {
setIsDockClosing(false);
setIsDockHovered(true);
return;
}
if (!isDockFocused || startedByPointer) {
startDockCollapse();
return;
}
setIsDockHovered(false);
setIsDockClosing(false);
};
const handleDockZoneFocus = () => {
clearDockTimers();
setIsDockClosing(false);
setIsDockFocused(true);
};
const handleDockHandleFocus = () => {
handleDockZoneFocus();
window.requestAnimationFrame(() => {
dockZoneRef.current
?.querySelector<HTMLElement>('[data-dock-panel="true"] a, [data-dock-panel="true"] button')
?.focus();
});
};
const handleDockBlur = (event: FocusEvent<HTMLDivElement>) => {
const nextTarget = event.relatedTarget;
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
if (!nextTarget) {
window.setTimeout(() => {
if (dockZoneRef.current?.contains(document.activeElement)) return;
setIsDockFocused(false);
if (!isPinned && !isDockHovered) {
startDockCollapse();
}
}, 80);
return;
}
setIsDockFocused(false);
if (!isPinned && !isDockHovered) {
startDockCollapse();
}
};
const handleLogout = () => { const handleLogout = () => {
if (confirm('로그아웃 하시겠습니까?')) { if (confirm('로그아웃 하시겠습니까?')) {
logout(); logout();
setIsMoreOpen(false);
router.push('/'); router.push('/');
} }
}; };
const items: DockItem[] = [ const baseItems: DockAction[] = [
{ {
key: 'home', key: 'home',
href: '/', href: '/',
label: '홈', label: '홈',
icon: Home, icon: Home,
isActive: (currentPath) => currentPath === '/', isActive: isActivePath('/'),
}, },
{ {
key: 'archive', key: 'archive',
href: '/archive', href: '/archive',
label: '아카이브', label: '아카이브',
icon: Archive, icon: Archive,
isActive: (currentPath) => currentPath.startsWith('/archive'), isActive: isActivePath('/archive'),
}, },
{ {
key: 'chess', key: 'chess',
href: '/play/chess', href: '/chess',
label: '체스', label: '체스',
icon: Crown, icon: Crown,
isActive: (currentPath) => currentPath.startsWith('/play/chess'), isActive: (currentPath) => currentPath.startsWith('/chess') || currentPath.startsWith('/play/chess'),
}, },
]; ];
const authItems: DockAction[] = [];
if (_hasHydrated && isAdmin) { if (_hasHydrated && isAdmin) {
items.push( authItems.push(
{ {
key: 'admin', key: 'admin',
href: '/admin', href: '/admin',
@@ -70,7 +349,7 @@ export default function DesktopDock({ isSidebarCollapsed }: DesktopDockProps) {
href: '/admin/posts/new', href: '/admin/posts/new',
label: '글쓰기', label: '글쓰기',
icon: PenLine, icon: PenLine,
isActive: (currentPath) => currentPath.startsWith('/admin/posts/new'), isActive: isActivePath('/admin/posts/new'),
}, },
{ {
key: 'logout', key: 'logout',
@@ -80,47 +359,50 @@ export default function DesktopDock({ isSidebarCollapsed }: DesktopDockProps) {
}, },
); );
} else if (_hasHydrated && isLoggedIn) { } else if (_hasHydrated && isLoggedIn) {
items.push({ authItems.push({
key: 'logout', key: 'logout',
label: '로그아웃', label: '로그아웃',
icon: LogOut, icon: LogOut,
onClick: handleLogout, onClick: handleLogout,
}); });
} else if (_hasHydrated) { } else if (_hasHydrated) {
items.push( authItems.push(
{ {
key: 'login', key: 'login',
href: '/login', href: '/login',
label: '로그인', label: '로그인',
icon: LogIn, icon: LogIn,
isActive: (currentPath) => currentPath.startsWith('/login'), isActive: isActivePath('/login'),
}, },
{ {
key: 'signup', key: 'signup',
href: '/signup', href: '/signup',
label: '회원가입', label: '회원가입',
icon: UserPlus, icon: UserPlus,
isActive: (currentPath) => currentPath.startsWith('/signup'), isActive: isActivePath('/signup'),
}, },
); );
} }
const renderItem = (item: DockItem) => { const desktopItems = [...baseItems, ...authItems];
const renderDesktopItem = (item: DockAction) => {
const Icon = item.icon; const Icon = item.icon;
const active = item.isActive?.(pathname) ?? false; const active = item.isActive?.(pathname) ?? false;
const toneStyle = getDockToneStyle(item.key);
const itemClass = clsx( const itemClass = clsx(
'group relative flex h-10 w-10 items-center justify-center rounded-lg border border-white/20 bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition duration-150 hover:-translate-y-1 hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)] focus-visible:-translate-y-1 sm:h-12 sm:w-12', 'group/item relative flex h-12 w-12 items-center justify-center rounded-lg border border-[var(--dock-item-border)] bg-[var(--dock-item-bg)] text-[var(--dock-item-fg)] shadow-[var(--shadow-control)] backdrop-blur-[18px] transition duration-150 hover:-translate-y-1 hover:border-[var(--dock-item-border-hover)] hover:bg-[var(--dock-item-bg-hover)] hover:text-[var(--dock-item-fg-strong)] focus-visible:-translate-y-1',
active && 'bg-[var(--window-bg-strong)] text-[var(--color-accent)] ring-1 ring-[var(--color-accent-soft)]', active && 'border-[var(--dock-item-border-hover)] bg-[var(--dock-item-bg-active)] text-[var(--dock-item-fg-strong)] ring-1 ring-[var(--dock-item-ring)]',
); );
const content = ( const content = (
<> <>
<Icon size={20} strokeWidth={2.1} /> <Icon size={20} strokeWidth={2.1} />
<span className="pointer-events-none absolute -top-9 hidden whitespace-nowrap rounded-full border border-[var(--color-line)] bg-[var(--window-bg-strong)] px-2.5 py-1 text-xs font-semibold text-[var(--color-text)] opacity-0 shadow-[var(--shadow-control)] backdrop-blur-xl transition group-hover:opacity-100 sm:block"> <span className="pointer-events-none absolute -top-9 whitespace-nowrap rounded-full border border-[var(--card-border)] bg-[var(--card-bg-strong)] px-2.5 py-1 text-xs font-semibold text-[var(--color-text)] opacity-0 shadow-[var(--shadow-control)] backdrop-blur-[18px] transition group-hover/item:opacity-100">
{item.label} {item.label}
</span> </span>
{active && ( {active && (
<span className="absolute -bottom-1 h-1 w-1 rounded-full bg-[var(--color-accent)]" /> <span className="absolute -bottom-1 h-1 w-1 rounded-full bg-[var(--dock-item-fg-strong)]" />
)} )}
</> </>
); );
@@ -134,6 +416,8 @@ export default function DesktopDock({ isSidebarCollapsed }: DesktopDockProps) {
aria-label={item.label} aria-label={item.label}
aria-current={active ? 'page' : undefined} aria-current={active ? 'page' : undefined}
className={itemClass} className={itemClass}
style={toneStyle}
onClick={releaseUnpinnedDockAfterNavigation}
> >
{content} {content}
</Link> </Link>
@@ -148,6 +432,55 @@ export default function DesktopDock({ isSidebarCollapsed }: DesktopDockProps) {
aria-label={item.label} aria-label={item.label}
onClick={item.onClick} onClick={item.onClick}
className={itemClass} className={itemClass}
style={toneStyle}
>
{content}
</button>
);
};
const renderMobileItem = (item: DockAction, activeOverride?: boolean) => {
const Icon = item.icon;
const active = activeOverride ?? item.isActive?.(pathname) ?? false;
const toneStyle = getDockToneStyle(item.key);
const itemClass = clsx(
'flex h-12 min-w-0 flex-1 flex-col items-center justify-center gap-0.5 rounded-lg border border-[var(--dock-item-border)] bg-[var(--dock-item-bg)] px-1 text-[10px] font-semibold leading-none text-[var(--dock-item-fg)] shadow-[var(--shadow-control)] backdrop-blur-[18px] transition-colors',
'hover:border-[var(--dock-item-border-hover)] hover:bg-[var(--dock-item-bg-hover)] hover:text-[var(--dock-item-fg-strong)] focus-visible:bg-[var(--dock-item-bg-active)]',
active && 'border-[var(--dock-item-border-hover)] bg-[var(--dock-item-bg-active)] text-[var(--dock-item-fg-strong)] ring-1 ring-[var(--dock-item-ring)]',
);
const content = (
<>
<Icon size={18} strokeWidth={2.1} />
<span className="max-w-full truncate">{item.label}</span>
</>
);
if (item.href) {
return (
<Link
key={item.key}
href={item.href}
title={item.label}
aria-label={item.label}
aria-current={active ? 'page' : undefined}
className={itemClass}
style={toneStyle}
onClick={() => setIsMoreOpen(false)}
>
{content}
</Link>
);
}
return (
<button
key={item.key}
type="button"
title={item.label}
aria-label={item.label}
onClick={item.onClick}
className={itemClass}
style={toneStyle}
> >
{content} {content}
</button> </button>
@@ -155,16 +488,156 @@ export default function DesktopDock({ isSidebarCollapsed }: DesktopDockProps) {
}; };
return ( return (
<>
<nav <nav
aria-label="빠른 실행 Dock" aria-label="빠른 실행 Dock"
className={clsx( className={clsx(
'fixed bottom-3 left-1/2 z-40 -translate-x-1/2 transition-[left] duration-300 ease-out md:bottom-5', 'fixed bottom-1 left-1/2 z-50 hidden -translate-x-1/2 md:block',
isSidebarCollapsed ? 'md:left-[calc(50%+2.5rem)]' : 'md:left-[calc(50%+9rem)]',
)} )}
> >
<div className="flex max-w-[calc(100vw-1rem)] items-end gap-1.5 overflow-x-auto rounded-lg border border-[var(--window-border)] bg-[var(--dock-bg)] px-2 py-2 shadow-[var(--shadow-window)] backdrop-blur-2xl sm:gap-2"> <div
{items.map(renderItem)} ref={dockZoneRef}
onMouseEnter={expandDock}
onMouseLeave={scheduleDockCollapse}
onFocus={handleDockZoneFocus}
onBlur={handleDockBlur}
className={clsx(
'relative flex items-end justify-center transition-[width,height,padding] duration-[560ms] ease-[cubic-bezier(0.22,1,0.36,1)]',
isDockRangeExpanded
? 'h-32 w-[min(calc(100vw-2rem),56rem)] px-8 pb-7 pt-12'
: 'h-14 w-16 px-0 pb-0 pt-0',
)}
>
<button
type="button"
aria-label="Dock 열기"
tabIndex={isDockRangeExpanded ? -1 : 0}
onMouseEnter={expandDock}
onFocus={handleDockHandleFocus}
className={clsx(
'absolute bottom-0 left-1/2 z-10 flex h-10 w-12 -translate-x-1/2 items-start justify-center rounded-t-lg border border-b-0 border-[var(--dock-item-border-hover)] bg-[var(--dock-item-bg-active)] pt-1.5 text-[var(--dock-item-fg-strong)] shadow-[var(--shadow-control)] backdrop-blur-[22px]',
'transition-[transform,opacity,width,height] duration-[560ms] ease-[cubic-bezier(0.22,1,0.36,1)] hover:bg-[var(--dock-item-bg-hover)] focus-visible:bg-[var(--dock-item-bg-hover)]',
isDockRangeExpanded
? 'pointer-events-none translate-y-5 scale-75 opacity-0'
: 'pointer-events-auto translate-y-0 scale-100 opacity-100 hover:h-10 hover:w-14',
)}
style={getDockToneStyle('more')}
>
<MoreHorizontal size={18} strokeWidth={2.3} />
</button>
<div
data-dock-panel="true"
className={clsx(
'flex max-w-[calc(100vw-2rem)] origin-bottom items-end gap-2 overflow-visible rounded-xl border border-[var(--dock-border)] bg-[var(--dock-bg)] px-2 py-2 shadow-[var(--shadow-dock)] backdrop-blur-[30px]',
'transition-[transform,opacity,filter] duration-[560ms] ease-[cubic-bezier(0.22,1,0.36,1)]',
isDockOpen
? 'pointer-events-auto translate-y-0 scale-x-100 scale-y-100 opacity-100 blur-0'
: clsx(
'translate-y-8 scale-x-[0.16] scale-y-[0.22] opacity-0 blur-sm',
isDockClosing ? 'pointer-events-auto' : 'pointer-events-none',
),
)}
>
{desktopItems.map(renderDesktopItem)}
<button
type="button"
title={isPinned ? 'Dock 고정 해제' : 'Dock 고정'}
aria-label={isPinned ? 'Dock 고정 해제' : 'Dock 고정'}
aria-pressed={isPinned}
onPointerDown={() => {
pinToggleStartedByPointerRef.current = true;
}}
onClick={handlePinnedChange}
className={clsx(
'group/item relative ml-1 flex h-12 w-12 items-center justify-center rounded-lg border border-[var(--dock-item-border-hover)] bg-[var(--dock-item-bg-active)] text-[var(--dock-item-fg-strong)] shadow-[var(--shadow-control)] ring-1 ring-[var(--dock-item-ring)] backdrop-blur-[18px] transition duration-150 hover:-translate-y-1 hover:bg-[var(--dock-item-bg-hover)]',
isPinned && 'shadow-[var(--shadow-dock)]',
)}
style={getDockToneStyle('pin')}
>
{isPinned ? <PinOff size={19} /> : <Pin size={19} />}
<span className="pointer-events-none absolute -top-9 whitespace-nowrap rounded-full border border-[var(--card-border)] bg-[var(--card-bg-strong)] px-2.5 py-1 text-xs font-semibold text-[var(--color-text)] opacity-0 shadow-[var(--shadow-control)] backdrop-blur-[18px] transition group-hover/item:opacity-100">
{isPinned ? '고정 해제' : '고정'}
</span>
</button>
</div>
</div> </div>
</nav> </nav>
{isMoreOpen && (
<div className="fixed inset-x-2 bottom-[4.75rem] z-50 md:hidden">
<div className="mx-auto max-w-md rounded-lg border border-[var(--dock-border)] bg-[var(--dock-bg)] p-3 shadow-[var(--shadow-dock)] backdrop-blur-[30px]">
<div className="mb-3 flex items-center justify-between gap-3">
<span className="text-xs font-bold uppercase tracking-normal text-[var(--color-text-subtle)]">
</span>
<ThemeToggle />
</div>
<div className="grid grid-cols-2 gap-2">
{authItems.map((item) => {
const Icon = item.icon;
const active = item.isActive?.(pathname) ?? false;
const toneStyle = getDockToneStyle(item.key);
const className = clsx(
'inline-flex h-10 min-w-0 items-center justify-center gap-2 rounded-lg border border-[var(--dock-item-border)] bg-[var(--dock-item-bg)] px-3 text-sm font-semibold text-[var(--dock-item-fg)] shadow-[var(--shadow-control)] backdrop-blur-[18px] transition-colors hover:border-[var(--dock-item-border-hover)] hover:bg-[var(--dock-item-bg-hover)] hover:text-[var(--dock-item-fg-strong)]',
active && 'border-[var(--dock-item-border-hover)] bg-[var(--dock-item-bg-active)] text-[var(--dock-item-fg-strong)] ring-1 ring-[var(--dock-item-ring)]',
);
if (item.href) {
return (
<Link
key={item.key}
href={item.href}
className={className}
style={toneStyle}
onClick={() => setIsMoreOpen(false)}
>
<Icon size={16} />
<span className="truncate">{item.label}</span>
</Link>
);
}
return (
<button
key={item.key}
type="button"
className={className}
style={toneStyle}
onClick={item.onClick}
>
<Icon size={16} />
<span className="truncate">{item.label}</span>
</button>
);
})}
</div>
</div>
</div>
)}
<nav aria-label="모바일 Dock" className="fixed inset-x-2 bottom-2 z-40 md:hidden">
<div className="mx-auto flex max-w-md items-center gap-1 rounded-lg border border-[var(--dock-border)] bg-[var(--dock-bg)] p-1.5 pb-[calc(0.375rem+env(safe-area-inset-bottom))] shadow-[var(--shadow-dock)] backdrop-blur-[30px]">
{renderMobileItem(baseItems[0])}
{renderMobileItem(baseItems[1])}
{renderMobileItem({
key: 'menu',
label: '메뉴',
icon: Menu,
onClick: () => {
setIsMoreOpen(false);
onOpenMobileMenu();
},
})}
{renderMobileItem(baseItems[2])}
{renderMobileItem({
key: 'more',
label: '더보기',
icon: MoreHorizontal,
onClick: () => setIsMoreOpen((previous) => !previous),
}, isMoreOpen)}
</div>
</nav>
</>
); );
} }

View File

@@ -1,16 +1,13 @@
'use client'; 'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { clsx } from 'clsx'; import { BatteryMedium, ChevronRight, Command, Monitor, Search, Wifi } from 'lucide-react';
import { getProfile } from '@/api/profile'; import { getProfile } from '@/api/profile';
import ThemeToggle from '@/components/theme/ThemeToggle'; import ThemeToggle from '@/components/theme/ThemeToggle';
interface DesktopMenuBarProps {
isSidebarCollapsed: boolean;
}
const defaultProfile = { const defaultProfile = {
githubUrl: 'https://github.com', githubUrl: 'https://github.com',
email: 'user@example.com', email: 'user@example.com',
@@ -24,22 +21,36 @@ const getCategoryTitle = (pathname: string) => {
const getAppTitle = (pathname: string) => { const getAppTitle = (pathname: string) => {
if (pathname.startsWith('/admin/posts/new')) return 'Write'; if (pathname.startsWith('/admin/posts/new')) return 'Write';
if (pathname.startsWith('/admin/posts')) return 'Posts'; if (pathname.startsWith('/admin/posts')) return 'Post Manager';
if (pathname.startsWith('/admin/comments')) return 'Comments'; if (pathname.startsWith('/admin/comments')) return 'Comment Center';
if (pathname.startsWith('/admin/categories')) return 'Categories'; if (pathname.startsWith('/admin/categories')) return 'Category Studio';
if (pathname.startsWith('/admin/profile')) return 'Profile'; if (pathname.startsWith('/admin/profile')) return 'Profile Panel';
if (pathname.startsWith('/admin')) return 'Dashboard'; if (pathname.startsWith('/admin')) return 'Admin Console';
if (pathname.startsWith('/archive')) return 'Archive'; if (pathname.startsWith('/archive')) return 'Archive';
if (pathname.startsWith('/category')) return getCategoryTitle(pathname); if (pathname.startsWith('/category')) return getCategoryTitle(pathname);
if (pathname.startsWith('/posts')) return 'Reader'; if (pathname.startsWith('/posts')) return 'Reader';
if (pathname.startsWith('/chess')) return 'Maia Chess';
if (pathname.startsWith('/play/chess')) return 'Chess'; if (pathname.startsWith('/play/chess')) return 'Chess';
if (pathname.startsWith('/login')) return 'Login'; if (pathname.startsWith('/login')) return 'Login';
if (pathname.startsWith('/signup')) return 'Signup'; if (pathname.startsWith('/signup')) return 'Signup';
return '홈'; return '홈';
}; };
export default function DesktopMenuBar({ isSidebarCollapsed }: DesktopMenuBarProps) { const formatMenuTime = (date: Date | null) => {
if (!date) return '';
return new Intl.DateTimeFormat('ko-KR', {
month: 'short',
day: 'numeric',
weekday: 'short',
hour: '2-digit',
minute: '2-digit',
}).format(date);
};
export default function DesktopMenuBar() {
const pathname = usePathname(); const pathname = usePathname();
const [now, setNow] = useState<Date | null>(null);
const { data: profile } = useQuery({ const { data: profile } = useQuery({
queryKey: ['profile'], queryKey: ['profile'],
@@ -47,38 +58,64 @@ export default function DesktopMenuBar({ isSidebarCollapsed }: DesktopMenuBarPro
retry: 0, retry: 0,
}); });
useEffect(() => {
const updateTime = () => setNow(new Date());
const frameId = window.requestAnimationFrame(updateTime);
const timerId = window.setInterval(updateTime, 60_000);
return () => {
window.cancelAnimationFrame(frameId);
window.clearInterval(timerId);
};
}, []);
const githubUrl = profile?.githubUrl || defaultProfile.githubUrl; const githubUrl = profile?.githubUrl || defaultProfile.githubUrl;
const email = profile?.email || defaultProfile.email; const email = profile?.email || defaultProfile.email;
const menuLinkClass = 'text-xs font-semibold text-[var(--color-text-subtle)] transition hover:text-[var(--color-text)]'; const menuLinkClass = 'hidden rounded px-2 py-1 text-xs font-semibold text-[var(--color-text-muted)] transition hover:bg-[var(--card-bg)] hover:text-[var(--color-text)] xl:inline-flex';
const systemIconClass = 'text-[var(--color-text-muted)]';
return ( return (
<div <div
className={clsx( className="fixed inset-x-0 top-0 z-[70] hidden h-10 border-b border-[var(--menubar-border)] bg-[var(--menubar-bg)] px-3 shadow-[var(--shadow-menubar)] backdrop-blur-[28px] md:block"
'fixed left-16 right-3 top-3 z-40 transition-[left] duration-300 ease-out md:right-6', role="menubar"
isSidebarCollapsed ? 'md:left-24' : 'md:left-[19rem]', aria-label="시스템 메뉴 막대"
)}
> >
<div className="flex h-11 items-center justify-between gap-3 rounded-lg border border-[var(--window-border)] bg-[var(--menubar-bg)] px-3 shadow-[var(--shadow-control)] backdrop-blur-2xl"> <div className="flex h-full min-w-0 items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-3"> <div className="flex min-w-0 items-center gap-1">
<Link href="/" className="shrink-0 text-sm font-bold text-[var(--color-text)]"> <Link
href="/"
className="mr-1 inline-flex h-7 shrink-0 items-center gap-1.5 rounded px-2 text-sm font-bold text-[var(--color-text)] transition hover:bg-[var(--card-bg)]"
>
<Command size={15} strokeWidth={2.4} />
WYPark WYPark
</Link> </Link>
<span className="hidden h-4 w-px bg-[var(--color-line)] sm:block" />
<span className="truncate text-sm font-semibold text-[var(--color-text-muted)]"> <div className="hidden min-w-0 items-center gap-1.5 rounded px-2 py-1 text-xs font-semibold text-[var(--color-text-subtle)] sm:flex">
{getAppTitle(pathname)} <Monitor size={14} />
</span> <span className="truncate text-[var(--color-text-muted)]">{getAppTitle(pathname)}</span>
<div className="hidden items-center gap-3 md:flex"> <ChevronRight size={13} />
<span className="truncate">{profile?.name || 'WYPark'}</span>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<a href={githubUrl} target="_blank" rel="noreferrer" className={menuLinkClass}> <a href={githubUrl} target="_blank" rel="noreferrer" className={menuLinkClass}>
GitHub GitHub
</a> </a>
<a href={`mailto:${email}`} className={menuLinkClass}> <a href={`mailto:${email}`} className={menuLinkClass}>
Email Email
</a> </a>
</div> <Search size={15} className={systemIconClass} />
</div> <Wifi size={15} className={systemIconClass} />
<BatteryMedium size={17} className={systemIconClass} />
<span className="hidden min-w-[8.5rem] text-right text-xs font-semibold tabular-nums text-[var(--color-text-muted)] lg:block">
{formatMenuTime(now)}
</span>
<div className="scale-[0.88]">
<ThemeToggle /> <ThemeToggle />
</div> </div>
</div> </div>
</div>
</div>
); );
} }

View File

@@ -2,13 +2,16 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import { usePathname } from 'next/navigation';
import { clsx } from 'clsx'; import { clsx } from 'clsx';
import DesktopDock from '@/components/layout/DesktopDock'; import DesktopDock from '@/components/layout/DesktopDock';
import DesktopMenuBar from '@/components/layout/DesktopMenuBar'; import DesktopMenuBar from '@/components/layout/DesktopMenuBar';
import Sidebar from '@/components/layout/Sidebar'; import Sidebar from '@/components/layout/Sidebar';
export default function DesktopShell({ children }: { children: ReactNode }) { export default function DesktopShell({ children }: { children: ReactNode }) {
const pathname = usePathname();
const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false); const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);
useEffect(() => { useEffect(() => {
const savedValue = window.localStorage.getItem('sidebar-collapsed'); const savedValue = window.localStorage.getItem('sidebar-collapsed');
@@ -21,29 +24,49 @@ export default function DesktopShell({ children }: { children: ReactNode }) {
return () => window.cancelAnimationFrame(frameId); return () => window.cancelAnimationFrame(frameId);
}, []); }, []);
useEffect(() => {
const frameId = window.requestAnimationFrame(() => {
setIsMobileSidebarOpen(false);
});
return () => window.cancelAnimationFrame(frameId);
}, [pathname]);
const handleSidebarCollapsedChange = (nextValue: boolean) => { const handleSidebarCollapsedChange = (nextValue: boolean) => {
setIsSidebarCollapsed(nextValue); setIsSidebarCollapsed(nextValue);
window.localStorage.setItem('sidebar-collapsed', String(nextValue)); window.localStorage.setItem('sidebar-collapsed', String(nextValue));
}; };
const isReaderRoute = pathname.startsWith('/posts/');
const isChessRoute = pathname.startsWith('/chess') || pathname.startsWith('/play/chess');
return ( return (
<div className="min-h-screen"> <div className="desktop-shell min-h-screen overflow-x-clip">
<Sidebar <Sidebar
isDesktopCollapsed={isSidebarCollapsed} isDesktopCollapsed={isSidebarCollapsed}
isMobileOpen={isMobileSidebarOpen}
onDesktopCollapsedChange={handleSidebarCollapsedChange} onDesktopCollapsedChange={handleSidebarCollapsedChange}
onMobileOpenChange={setIsMobileSidebarOpen}
/>
<DesktopMenuBar />
<DesktopDock
onOpenMobileMenu={() => setIsMobileSidebarOpen(true)}
/> />
<DesktopMenuBar isSidebarCollapsed={isSidebarCollapsed} />
<DesktopDock isSidebarCollapsed={isSidebarCollapsed} />
<main <main
className={clsx( className={clsx(
'relative w-full flex-1 transition-[margin,width] duration-300 ease-out', 'relative z-10 min-w-0 max-w-full flex-1 overflow-x-clip transition-[margin,width] duration-300 ease-out',
isSidebarCollapsed isSidebarCollapsed
? 'md:ml-20 md:w-[calc(100%-5rem)]' ? 'md:ml-[7rem] md:w-[calc(100%-7rem)]'
: 'md:ml-72 md:w-[calc(100%-18rem)]', : 'md:ml-[20rem] md:w-[calc(100%-20rem)]',
)}
>
<div
className={clsx(
'mx-auto min-w-0 max-w-full px-3 pt-14 md:px-6 md:pt-16 lg:px-8',
isChessRoute ? 'pb-44 md:pb-40' : isReaderRoute ? 'pb-44 md:pb-36' : 'pb-36 md:pb-32',
)} )}
> >
<div className="mx-auto w-full px-4 pb-28 pt-20 md:px-6 md:pb-32 md:pt-24 lg:px-8">
{children} {children}
</div> </div>
</main> </main>

View File

@@ -10,13 +10,9 @@ import {
ChevronRight, ChevronRight,
ChevronsLeft, ChevronsLeft,
ChevronsRight, ChevronsRight,
Crown,
FileQuestion, FileQuestion,
Folder, Folder,
FolderOpen, FolderOpen,
Home,
Menu,
X,
} from 'lucide-react'; } from 'lucide-react';
import { getCategories } from '@/api/category'; import { getCategories } from '@/api/category';
import { getProfile } from '@/api/profile'; import { getProfile } from '@/api/profile';
@@ -25,7 +21,9 @@ import { Category, Profile } from '@/types';
interface SidebarProps { interface SidebarProps {
isDesktopCollapsed: boolean; isDesktopCollapsed: boolean;
isMobileOpen: boolean;
onDesktopCollapsedChange: (nextValue: boolean) => void; onDesktopCollapsedChange: (nextValue: boolean) => void;
onMobileOpenChange: (nextValue: boolean) => void;
} }
interface CategoryItemProps { interface CategoryItemProps {
@@ -74,7 +72,7 @@ function CategoryItem({ category, depth, onNavigate, pathname }: CategoryItemPro
'flex items-center justify-between rounded-lg px-3 py-2 text-sm transition-all', 'flex items-center justify-between rounded-lg px-3 py-2 text-sm transition-all',
isActive isActive
? 'bg-[var(--color-accent-soft)] font-semibold text-[var(--color-accent)] shadow-sm' ? 'bg-[var(--color-accent-soft)] font-semibold text-[var(--color-accent)] shadow-sm'
: 'text-[var(--color-text-muted)] hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10', : 'text-[var(--color-text-muted)] hover:bg-[var(--card-bg)] hover:text-[var(--color-text)]',
)} )}
style={{ marginLeft: `${depth * 8}px` }} style={{ marginLeft: `${depth * 8}px` }}
> >
@@ -95,7 +93,7 @@ function CategoryItem({ category, depth, onNavigate, pathname }: CategoryItemPro
event.stopPropagation(); event.stopPropagation();
setIsExpanded((previous) => !previous); setIsExpanded((previous) => !previous);
}} }}
className="ml-1 rounded-full p-1 transition-colors hover:bg-black/[0.06] dark:hover:bg-white/10" className="ml-1 rounded-full p-1 transition-colors hover:bg-[var(--card-bg)]"
aria-label={isChildrenVisible ? `${category.name} 접기` : `${category.name} 펼치기`} aria-label={isChildrenVisible ? `${category.name} 접기` : `${category.name} 펼치기`}
> >
<ChevronRight <ChevronRight
@@ -125,10 +123,10 @@ function CategoryItem({ category, depth, onNavigate, pathname }: CategoryItemPro
function SidebarContent({ function SidebarContent({
isDesktopCollapsed, isDesktopCollapsed,
isMobileOpen,
onDesktopCollapsedChange, onDesktopCollapsedChange,
onMobileOpenChange,
}: SidebarProps) { }: SidebarProps) {
const [isOpen, setIsOpen] = useState(false);
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
@@ -150,7 +148,7 @@ function SidebarContent({
const displayProfile = profile ? { ...defaultProfile, ...profile } : defaultProfile; const displayProfile = profile ? { ...defaultProfile, ...profile } : defaultProfile;
const decodedPathname = decodeURIComponent(pathname); const decodedPathname = decodeURIComponent(pathname);
const closeSidebar = () => setIsOpen(false); const closeSidebar = () => onMobileOpenChange(false);
const handleSearch = (newKeyword: string) => { const handleSearch = (newKeyword: string) => {
const trimmedKeyword = newKeyword.trim(); const trimmedKeyword = newKeyword.trim();
@@ -168,47 +166,52 @@ function SidebarContent({
return ( return (
<> <>
<button
type="button"
onClick={() => setIsOpen((previous) => !previous)}
className="fixed left-4 top-4 z-50 rounded-full border border-[var(--color-line)] bg-[var(--color-control)] p-2 shadow-[var(--shadow-control)] backdrop-blur-xl transition-colors hover:bg-[var(--color-surface-strong)] md:hidden"
aria-label={isOpen ? '사이드바 닫기' : '사이드바 열기'}
>
{isOpen ? <X size={20} /> : <Menu size={20} />}
</button>
<button <button
type="button" type="button"
aria-label="사이드바 닫기" aria-label="사이드바 닫기"
onClick={closeSidebar} onClick={closeSidebar}
className={clsx( className={clsx(
'fixed inset-0 z-30 bg-black/35 backdrop-blur-sm transition-opacity md:hidden', 'fixed inset-0 z-50 bg-black/35 backdrop-blur-sm transition-opacity md:hidden',
isOpen ? 'opacity-100' : 'pointer-events-none opacity-0', isMobileOpen ? 'opacity-100' : 'pointer-events-none opacity-0',
)} )}
/> />
<aside <aside
className={clsx( className={clsx(
'fixed left-0 top-0 z-40 flex h-screen w-72 flex-col overflow-hidden border-r border-[var(--window-border)] bg-[var(--sidebar-bg)] shadow-[var(--shadow-panel)] backdrop-blur-2xl transition-[transform,width] duration-300 ease-out md:translate-x-0', 'fixed left-0 top-0 z-[60] flex h-screen w-72 max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden border-r border-[var(--sidebar-border)] bg-[var(--sidebar-bg)] shadow-[var(--shadow-sidebar)] backdrop-blur-[30px] transition-[transform,width] duration-300 ease-out md:left-4 md:top-14 md:z-40 md:h-[calc(100vh-9rem)] md:max-w-none md:translate-x-0 md:rounded-lg md:border',
isDesktopCollapsed ? 'md:w-20' : 'md:w-72', isDesktopCollapsed ? 'md:w-[4.5rem]' : 'md:w-72',
isOpen ? 'translate-x-0' : '-translate-x-full', isMobileOpen ? 'translate-x-0' : '-translate-x-full',
)} )}
> >
<div className={clsx('relative shrink-0 text-center', isDesktopCollapsed ? 'px-6 pb-5 pt-8 md:px-3 md:pb-4 md:pt-5' : 'px-6 pb-5 pt-8')}> <div className="flex h-12 shrink-0 items-center justify-between gap-3 border-b border-[var(--window-titlebar-border)] bg-[var(--window-titlebar)] px-4">
<div className={clsx('min-w-0', isDesktopCollapsed && 'md:hidden')}>
<p className="truncate text-sm font-bold text-[var(--color-text)]"></p>
<p className="truncate text-[11px] font-medium text-[var(--color-text-subtle)]"> </p>
</div>
<button <button
type="button" type="button"
onClick={() => onDesktopCollapsedChange(!isDesktopCollapsed)} onClick={() => onDesktopCollapsedChange(!isDesktopCollapsed)}
className="absolute right-3 top-3 hidden h-8 w-8 items-center justify-center rounded-full border border-[var(--color-line)] bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)] md:flex" className="hidden h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)] md:flex"
aria-label={isDesktopCollapsed ? '사이드바 펼치기' : '사이드바 접기'} aria-label={isDesktopCollapsed ? '사이드바 펼치기' : '사이드바 접기'}
> >
{isDesktopCollapsed ? <ChevronsRight size={16} /> : <ChevronsLeft size={16} />} {isDesktopCollapsed ? <ChevronsRight size={16} /> : <ChevronsLeft size={16} />}
</button> </button>
</div>
<Link href="/" onClick={closeSidebar} className="block transition-opacity hover:opacity-85"> <div className={clsx('relative shrink-0', isDesktopCollapsed ? 'px-5 pb-4 pt-5 md:px-3 md:pb-3 md:pt-4' : 'px-5 pb-4 pt-5')}>
<Link
href="/"
onClick={closeSidebar}
className={clsx(
'flex min-w-0 items-center gap-3 rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] p-3 transition hover:bg-[var(--card-bg-strong)]',
isDesktopCollapsed && 'md:justify-center md:border-transparent md:bg-transparent md:p-0 md:hover:bg-transparent',
)}
>
<div <div
className={clsx( className={clsx(
'relative mx-auto overflow-hidden rounded-2xl bg-black/[0.04] shadow-inner ring-1 ring-[var(--color-line)] transition-all dark:bg-white/10', 'relative shrink-0 overflow-hidden rounded-lg bg-black/[0.04] shadow-inner ring-1 ring-[var(--color-line)] transition-all dark:bg-white/10',
isDesktopCollapsed ? 'mb-4 h-20 w-20 md:mb-0 md:mt-8 md:h-12 md:w-12' : 'mb-4 h-20 w-20', isDesktopCollapsed ? 'h-12 w-12' : 'h-12 w-12',
)} )}
> >
{isProfileLoading ? ( {isProfileLoading ? (
@@ -226,16 +229,16 @@ function SidebarContent({
)} )}
</div> </div>
<div className={clsx(isDesktopCollapsed && 'md:hidden')}> <div className={clsx('min-w-0 text-left', isDesktopCollapsed && 'md:hidden')}>
{isProfileLoading ? ( {isProfileLoading ? (
<div className="flex flex-col items-center space-y-2"> <div className="space-y-2">
<div className="h-6 w-24 animate-pulse rounded bg-black/[0.06] dark:bg-white/10" /> <div className="h-6 w-24 animate-pulse rounded bg-black/[0.06] dark:bg-white/10" />
<div className="h-4 w-32 animate-pulse rounded bg-black/[0.04] dark:bg-white/10" /> <div className="h-4 w-32 animate-pulse rounded bg-black/[0.04] dark:bg-white/10" />
</div> </div>
) : ( ) : (
<> <>
<h2 className="text-lg font-bold tracking-normal text-[var(--color-text)]">{displayProfile.name}</h2> <h2 className="truncate text-sm font-bold tracking-normal text-[var(--color-text)]">{displayProfile.name}</h2>
<p className="mt-1 whitespace-pre-line text-sm leading-relaxed text-[var(--color-text-muted)]">{displayProfile.bio}</p> <p className="mt-0.5 line-clamp-2 whitespace-pre-line text-xs leading-5 text-[var(--color-text-muted)]">{displayProfile.bio}</p>
</> </>
)} )}
</div> </div>
@@ -288,7 +291,7 @@ function SidebarContent({
'flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-all', 'flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-all',
pathname === '/category/uncategorized' pathname === '/category/uncategorized'
? 'bg-[var(--color-accent-soft)] font-semibold text-[var(--color-accent)]' ? 'bg-[var(--color-accent-soft)] font-semibold text-[var(--color-accent)]'
: 'text-[var(--color-text-muted)] hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10', : 'text-[var(--color-text-muted)] hover:bg-[var(--card-bg)] hover:text-[var(--color-text)]',
)} )}
> >
<FileQuestion size={16} /> <FileQuestion size={16} />
@@ -298,42 +301,9 @@ function SidebarContent({
</div> </div>
</div> </div>
<div className="-mx-2 mt-3 shrink-0 border-t border-[var(--color-line)] px-2 pt-3">
<div className="mb-2 flex h-8 items-center px-3">
<p className="text-xs font-semibold uppercase tracking-normal text-[var(--color-text-subtle)]"></p>
</div>
<Link
href="/play/chess"
onClick={closeSidebar}
className={clsx(
'flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-all',
pathname === '/play/chess'
? 'bg-[var(--color-accent-soft)] font-semibold text-[var(--color-accent)]'
: 'text-[var(--color-text-muted)] hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10',
)}
>
<Crown size={16} />
<span></span>
</Link>
</div>
</div> </div>
<div className={clsx('hidden flex-1 flex-col items-center gap-2 overflow-y-auto px-0 pb-4 pt-2 md:flex', !isDesktopCollapsed && 'md:hidden')}> <div className={clsx('hidden flex-1 flex-col items-center gap-2 overflow-y-auto px-0 pb-4 pt-2 md:flex', !isDesktopCollapsed && 'md:hidden')}>
<Link
href="/"
title="홈"
aria-label="홈"
className={clsx(
'flex h-11 w-11 items-center justify-center rounded-xl border border-[var(--color-line)] bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)]',
pathname === '/' && 'bg-[var(--window-bg-strong)] text-[var(--color-accent)]',
)}
>
<Home size={18} />
</Link>
<div className="my-1 h-px w-9 bg-[var(--color-line)]" />
{compactCategoryItems.map((category) => { {compactCategoryItems.map((category) => {
const isActive = decodedPathname === `/category/${category.name}`; const isActive = decodedPathname === `/category/${category.name}`;
@@ -344,8 +314,8 @@ function SidebarContent({
title={category.name} title={category.name}
aria-label={category.name} aria-label={category.name}
className={clsx( className={clsx(
'flex h-11 w-11 items-center justify-center rounded-xl border border-[var(--color-line)] bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)]', 'flex h-11 w-11 items-center justify-center rounded-xl border border-[var(--control-border)] bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]',
isActive && 'bg-[var(--window-bg-strong)] text-[var(--color-accent)]', isActive && 'bg-[var(--card-bg-strong)] text-[var(--color-accent)]',
)} )}
> >
<Folder size={18} /> <Folder size={18} />
@@ -358,26 +328,12 @@ function SidebarContent({
title="미분류" title="미분류"
aria-label="미분류" aria-label="미분류"
className={clsx( className={clsx(
'flex h-11 w-11 items-center justify-center rounded-xl border border-[var(--color-line)] bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)]', 'flex h-11 w-11 items-center justify-center rounded-xl border border-[var(--control-border)] bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]',
pathname === '/category/uncategorized' && 'bg-[var(--window-bg-strong)] text-[var(--color-accent)]', pathname === '/category/uncategorized' && 'bg-[var(--card-bg-strong)] text-[var(--color-accent)]',
)} )}
> >
<FileQuestion size={18} /> <FileQuestion size={18} />
</Link> </Link>
<div className="my-1 h-px w-9 bg-[var(--color-line)]" />
<Link
href="/play/chess"
title="체스"
aria-label="체스"
className={clsx(
'flex h-11 w-11 items-center justify-center rounded-xl border border-[var(--color-line)] bg-[var(--color-control)] text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition hover:bg-[var(--window-bg-strong)] hover:text-[var(--color-text)]',
pathname === '/play/chess' && 'bg-[var(--window-bg-strong)] text-[var(--color-accent)]',
)}
>
<Crown size={18} />
</Link>
</div> </div>
</nav> </nav>
@@ -402,7 +358,7 @@ export default function Sidebar(props: SidebarProps) {
fallback={( fallback={(
<div <div
className={clsx( className={clsx(
'h-screen border-r border-[var(--window-border)] bg-[var(--sidebar-bg)]', 'h-screen border-r border-[var(--sidebar-border)] bg-[var(--sidebar-bg)]',
props.isDesktopCollapsed ? 'w-20' : 'w-72', props.isDesktopCollapsed ? 'w-20' : 'w-72',
)} )}
/> />

View File

@@ -49,7 +49,7 @@ export default function TopHeader() {
}; };
const quietActionClass = const quietActionClass =
'flex h-9 shrink-0 items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] backdrop-blur-2xl transition-colors hover:bg-[var(--color-surface-strong)] hover:text-[var(--color-text)]'; 'flex h-9 shrink-0 items-center gap-2 rounded-full border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] backdrop-blur-[18px] transition-colors hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)]';
return ( return (
<div <div
@@ -65,7 +65,7 @@ export default function TopHeader() {
].join(' ')} ].join(' ')}
aria-hidden={!isMenuOpen} aria-hidden={!isMenuOpen}
> >
<div className="flex min-w-max items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-surface)]/85 p-1.5 shadow-[var(--shadow-control)] backdrop-blur-2xl"> <div className="flex min-w-max items-center gap-2 rounded-full border border-[var(--control-border)] bg-[var(--card-bg)] p-1.5 shadow-[var(--shadow-control)] backdrop-blur-[18px]">
<ThemeToggle /> <ThemeToggle />
{_hasHydrated && ( {_hasHydrated && (
@@ -96,7 +96,7 @@ export default function TopHeader() {
<button <button
type="button" type="button"
onClick={handleLogout} onClick={handleLogout}
className="flex h-9 shrink-0 items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-control)] px-3 text-sm font-medium text-[var(--color-text-muted)] shadow-[var(--shadow-control)] backdrop-blur-2xl transition-colors hover:bg-[var(--color-surface-strong)] hover:text-red-500" className="flex h-9 shrink-0 items-center gap-2 rounded-full border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-medium text-[var(--color-text-muted)] shadow-[var(--shadow-control)] backdrop-blur-[18px] transition-colors hover:bg-[var(--card-bg-strong)] hover:text-red-500"
> >
<LogOut size={16} /> <LogOut size={16} />
<span className="hidden sm:inline"></span> <span className="hidden sm:inline"></span>
@@ -116,7 +116,7 @@ export default function TopHeader() {
<Link <Link
href="/signup" href="/signup"
onClick={closeMenu} onClick={closeMenu}
className="flex h-9 shrink-0 items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text)] shadow-[var(--shadow-control)] backdrop-blur-2xl transition-all hover:bg-[var(--color-surface-strong)]" className="flex h-9 shrink-0 items-center gap-2 rounded-full border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text)] shadow-[var(--shadow-control)] backdrop-blur-[18px] transition-all hover:bg-[var(--card-bg-strong)]"
> >
<UserPlus size={16} /> <UserPlus size={16} />
<span className="hidden sm:inline"></span> <span className="hidden sm:inline"></span>
@@ -132,7 +132,7 @@ export default function TopHeader() {
aria-label={isMenuOpen ? '상단 메뉴 닫기' : '상단 메뉴 열기'} aria-label={isMenuOpen ? '상단 메뉴 닫기' : '상단 메뉴 열기'}
aria-expanded={isMenuOpen} aria-expanded={isMenuOpen}
onClick={() => setIsMenuOpen((previous) => !previous)} onClick={() => setIsMenuOpen((previous) => !previous)}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-[var(--color-line)] bg-[var(--color-control)] text-[var(--color-text)] shadow-[var(--shadow-control)] backdrop-blur-2xl transition-colors hover:bg-[var(--color-surface-strong)]" className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-[var(--control-border)] bg-[var(--color-control)] text-[var(--color-text)] shadow-[var(--shadow-control)] backdrop-blur-[18px] transition-colors hover:bg-[var(--card-bg-strong)]"
> >
{isMenuOpen ? <X size={18} /> : <Menu size={18} />} {isMenuOpen ? <X size={18} /> : <Menu size={18} />}
</button> </button>

View File

@@ -0,0 +1,253 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { clsx } from 'clsx';
import { Calendar, ChevronRight, FileText, Rows3, SlidersHorizontal } from 'lucide-react';
import EmptyState from '@/components/ui/EmptyState';
import StatusBadge from '@/components/ui/StatusBadge';
import Surface from '@/components/ui/Surface';
import { Post } from '@/types';
type ArchiveExplorerProps = {
posts: Post[];
};
type Density = 'comfortable' | 'compact';
const ALL = 'all';
const getPostDate = (post: Post) => {
const date = new Date(post.createdAt);
return Number.isNaN(date.getTime()) ? null : date;
};
const getMonthKey = (date: Date) => {
return (date.getMonth() + 1).toString().padStart(2, '0');
};
const formatDate = (value: string) => {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '';
return new Intl.DateTimeFormat('ko-KR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(date);
};
const sortNewestFirst = (posts: Post[]) => {
return [...posts].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
};
export default function ArchiveExplorer({ posts }: ArchiveExplorerProps) {
const [selectedYear, setSelectedYear] = useState(ALL);
const [selectedMonth, setSelectedMonth] = useState(ALL);
const [selectedCategory, setSelectedCategory] = useState(ALL);
const [density, setDensity] = useState<Density>('compact');
const years = useMemo(() => {
return Array.from(new Set(posts.map(getPostDate).filter(Boolean).map((date) => date!.getFullYear().toString())))
.sort((a, b) => Number(b) - Number(a));
}, [posts]);
const monthOptions = useMemo(() => {
return Array.from(new Set(posts
.map((post) => {
const date = getPostDate(post);
if (!date) return null;
if (selectedYear !== ALL && date.getFullYear().toString() !== selectedYear) return null;
return getMonthKey(date);
})
.filter(Boolean) as string[]))
.sort((a, b) => Number(b) - Number(a));
}, [posts, selectedYear]);
const categories = useMemo(() => {
return Array.from(new Set(posts.map((post) => post.categoryName || '미분류'))).sort((a, b) => a.localeCompare(b, 'ko-KR'));
}, [posts]);
useEffect(() => {
if (selectedMonth !== ALL && !monthOptions.includes(selectedMonth)) {
setSelectedMonth(ALL);
}
}, [monthOptions, selectedMonth]);
const filteredPosts = useMemo(() => {
return sortNewestFirst(posts.filter((post) => {
const date = getPostDate(post);
if (!date) return false;
const year = date.getFullYear().toString();
const month = getMonthKey(date);
const category = post.categoryName || '미분류';
return (
(selectedYear === ALL || year === selectedYear)
&& (selectedMonth === ALL || month === selectedMonth)
&& (selectedCategory === ALL || category === selectedCategory)
);
}));
}, [posts, selectedCategory, selectedMonth, selectedYear]);
const groupedPosts = useMemo(() => {
const groups: Record<string, Record<string, Post[]>> = {};
filteredPosts.forEach((post) => {
const date = getPostDate(post);
if (!date) return;
const year = date.getFullYear().toString();
const month = getMonthKey(date);
groups[year] ??= {};
groups[year][month] ??= [];
groups[year][month].push(post);
});
return groups;
}, [filteredPosts]);
const sortedYears = Object.keys(groupedPosts).sort((a, b) => Number(b) - Number(a));
const isCompact = density === 'compact';
return (
<div className="min-w-0 space-y-7">
<Surface className="p-3 shadow-none md:p-4">
<div className="grid min-w-0 gap-3 md:grid-cols-[repeat(3,minmax(0,1fr))_auto]">
<label className="min-w-0 text-xs font-bold uppercase tracking-normal text-[var(--color-text-subtle)]">
<select
value={selectedYear}
onChange={(event) => setSelectedYear(event.target.value)}
className="mt-1 h-10 w-full rounded-lg border px-3 text-sm font-semibold normal-case"
>
<option value={ALL}> </option>
{years.map((year) => (
<option key={year} value={year}>{year}</option>
))}
</select>
</label>
<label className="min-w-0 text-xs font-bold uppercase tracking-normal text-[var(--color-text-subtle)]">
<select
value={selectedMonth}
onChange={(event) => setSelectedMonth(event.target.value)}
className="mt-1 h-10 w-full rounded-lg border px-3 text-sm font-semibold normal-case"
>
<option value={ALL}> </option>
{monthOptions.map((month) => (
<option key={month} value={month}>{Number(month)}</option>
))}
</select>
</label>
<label className="min-w-0 text-xs font-bold uppercase tracking-normal text-[var(--color-text-subtle)]">
<select
value={selectedCategory}
onChange={(event) => setSelectedCategory(event.target.value)}
className="mt-1 h-10 w-full rounded-lg border px-3 text-sm font-semibold normal-case"
>
<option value={ALL}> </option>
{categories.map((category) => (
<option key={category} value={category}>{category}</option>
))}
</select>
</label>
<div className="flex items-end">
<button
type="button"
aria-pressed={isCompact}
onClick={() => setDensity((previous) => (previous === 'compact' ? 'comfortable' : 'compact'))}
className={clsx(
'inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-3 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] transition-colors hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-text)] md:w-auto',
isCompact && 'text-[var(--color-accent)]',
)}
>
{isCompact ? <Rows3 size={16} /> : <SlidersHorizontal size={16} />}
<span>{isCompact ? 'Compact' : 'Comfort'}</span>
</button>
</div>
</div>
</Surface>
<div className="flex min-w-0 items-center justify-between gap-3 border-b border-[var(--color-line)] pb-4">
<p className="min-w-0 break-words text-sm font-semibold text-[var(--color-text-muted)]">
<span className="text-[var(--color-accent)]">{filteredPosts.length.toLocaleString()}</span>
</p>
</div>
{sortedYears.length > 0 ? (
<div className={clsx('relative', isCompact ? 'space-y-8' : 'space-y-12')}>
<div className="absolute bottom-4 left-4 top-4 hidden w-px bg-[var(--color-line)] md:block" />
{sortedYears.map((year) => {
const months = groupedPosts[year];
const sortedMonths = Object.keys(months).sort((a, b) => Number(b) - Number(a));
return (
<div key={year} className="relative min-w-0">
<div className={clsx('flex items-center gap-4', isCompact ? 'mb-4' : 'mb-6')}>
<div className="z-10 hidden h-9 w-9 items-center justify-center rounded-full border-4 border-[var(--window-bg-strong)] bg-[var(--color-accent-soft)] shadow-[var(--shadow-control)] md:flex">
<div className="h-2.5 w-2.5 rounded-full bg-[var(--color-accent)]" />
</div>
<h2 className="text-2xl font-bold text-[var(--color-text)]">{year}</h2>
</div>
<div className={clsx(isCompact ? 'space-y-5 md:pl-12' : 'space-y-8 md:pl-12')}>
{sortedMonths.map((month) => {
const monthPosts = months[month];
return (
<div key={month} className="min-w-0">
<h3 className={clsx('flex items-center gap-2 font-bold text-[var(--color-text-muted)]', isCompact ? 'mb-2 text-base' : 'mb-4 text-lg')}>
<Calendar size={18} className="shrink-0 text-[var(--color-text-subtle)]" />
{Number(month)}
<StatusBadge tone="neutral">{monthPosts.length}</StatusBadge>
</h3>
<div className={clsx('grid min-w-0', isCompact ? 'gap-2' : 'gap-3')}>
{monthPosts.map((post) => (
<Link
key={post.id}
href={`/posts/${post.slug}`}
className="group/item block min-w-0"
>
<Surface interactive className={clsx('flex min-w-0 items-center justify-between gap-3 shadow-none', isCompact ? 'p-3' : 'p-4')}>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-control)]">
<FileText size={17} />
</span>
<div className="min-w-0 flex-1">
<h4 className="line-clamp-2 break-words text-sm font-semibold text-[var(--color-text)] transition-colors group-hover/item:text-[var(--color-accent)] md:text-base">
{post.title}
</h4>
<div className="mt-1.5 flex min-w-0 flex-wrap items-center gap-2 text-xs text-[var(--color-text-subtle)]">
<StatusBadge tone="neutral" className="px-1.5 py-0.5">{post.categoryName || '미분류'}</StatusBadge>
<span className="tabular-nums">
{formatDate(post.createdAt)}
</span>
</div>
</div>
<ChevronRight className="shrink-0 text-[var(--color-text-subtle)] transition-colors group-hover/item:text-[var(--color-accent)]" size={18} />
</Surface>
</Link>
))}
</div>
</div>
);
})}
</div>
</div>
);
})}
</div>
) : (
<EmptyState title="조건에 맞는 글이 없습니다." className="py-20" />
)}
</div>
);
}

View File

@@ -31,7 +31,7 @@ export default function MarkdownRenderer({ content }: MarkdownRendererProps) {
return ( return (
<code <code
className="mx-1 break-words rounded-md bg-black/[0.05] px-1.5 py-0.5 font-mono text-[0.9em] font-medium text-red-600 dark:bg-white/10 dark:text-red-300" className="mx-1 max-w-full break-words rounded-md bg-black/[0.05] px-1.5 py-0.5 font-mono text-[0.9em] font-medium text-red-600 [overflow-wrap:anywhere] dark:bg-white/10 dark:text-red-300"
{...props} {...props}
> >
{children} {children}
@@ -56,10 +56,10 @@ export default function MarkdownRenderer({ content }: MarkdownRendererProps) {
href={href} href={href}
target={isExternal ? '_blank' : undefined} target={isExternal ? '_blank' : undefined}
rel={isExternal ? 'noopener noreferrer' : undefined} rel={isExternal ? 'noopener noreferrer' : undefined}
className="inline-flex items-center gap-0.5 font-semibold text-[var(--color-accent)] underline-offset-4 transition-colors hover:underline" className="break-words font-semibold text-[var(--color-accent)] underline-offset-4 transition-colors [overflow-wrap:anywhere] hover:underline"
> >
{children} {children}
{isExternal && <ExternalLink size={12} className="opacity-70" />} {isExternal && <ExternalLink size={12} className="ml-0.5 inline-block align-text-bottom opacity-70" />}
</a> </a>
); );
}, },
@@ -67,8 +67,8 @@ export default function MarkdownRenderer({ content }: MarkdownRendererProps) {
// 4. 테이블 // 4. 테이블
table({ children }) { table({ children }) {
return ( return (
<div className="my-8 overflow-x-auto rounded-lg border border-[var(--color-line)] bg-[var(--color-surface)] shadow-[var(--shadow-card)]"> <div className="my-8 max-w-full overflow-x-auto rounded-lg border border-[var(--color-line)] bg-[var(--color-surface)] shadow-[var(--shadow-card)]">
<table className="w-full text-left text-sm text-[var(--color-text-muted)]"> <table className="w-full min-w-[520px] text-left text-sm text-[var(--color-text-muted)]">
{children} {children}
</table> </table>
</div> </div>
@@ -78,10 +78,10 @@ export default function MarkdownRenderer({ content }: MarkdownRendererProps) {
return <thead className="border-b border-[var(--color-line)] bg-black/[0.03] text-xs text-[var(--color-text-muted)] dark:bg-white/10">{children}</thead>; return <thead className="border-b border-[var(--color-line)] bg-black/[0.03] text-xs text-[var(--color-text-muted)] dark:bg-white/10">{children}</thead>;
}, },
th({ children }) { th({ children }) {
return <th className="px-5 py-3 font-bold text-[var(--color-text)]">{children}</th>; return <th className="break-words px-5 py-3 font-bold text-[var(--color-text)]">{children}</th>;
}, },
td({ children }) { td({ children }) {
return <td className="border-b border-[var(--color-line)] px-5 py-4 whitespace-pre-wrap">{children}</td>; return <td className="whitespace-pre-wrap break-words border-b border-[var(--color-line)] px-5 py-4">{children}</td>;
}, },
// 5. 이미지 // 5. 이미지
@@ -157,18 +157,18 @@ function CodeBlock({ language, code }: { language: string; code: string }) {
}; };
return ( return (
<div className="group relative my-8 overflow-hidden rounded-lg border border-gray-700/50 bg-[#1e1e1e] shadow-[var(--shadow-card)]"> <div className="group relative my-8 max-w-full overflow-hidden rounded-lg border border-gray-700/50 bg-[#1e1e1e] shadow-[var(--shadow-card)]">
<div className="flex items-center justify-between px-4 py-2.5 bg-[#2d2d2d] border-b border-gray-700 select-none"> <div className="flex min-w-0 items-center justify-between gap-3 border-b border-gray-700 bg-[#2d2d2d] px-4 py-2.5 select-none">
<div className="flex items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
<div className="flex gap-1.5"> <div className="flex gap-1.5">
<div className="w-3 h-3 rounded-full bg-[#FF5F56] border border-[#E0443E]" /> <div className="w-3 h-3 rounded-full bg-[#FF5F56] border border-[#E0443E]" />
<div className="w-3 h-3 rounded-full bg-[#FFBD2E] border border-[#DEA123]" /> <div className="w-3 h-3 rounded-full bg-[#FFBD2E] border border-[#DEA123]" />
<div className="w-3 h-3 rounded-full bg-[#27C93F] border border-[#1AAB29]" /> <div className="w-3 h-3 rounded-full bg-[#27C93F] border border-[#1AAB29]" />
</div> </div>
{language && ( {language && (
<div className="ml-4 flex items-center gap-1.5 px-2 py-0.5 rounded text-[10px] font-mono font-medium text-gray-400 bg-gray-700/50 border border-gray-600/50"> <div className="ml-2 flex min-w-0 items-center gap-1.5 rounded border border-gray-600/50 bg-gray-700/50 px-2 py-0.5 font-mono text-[10px] font-medium text-gray-400 sm:ml-4">
<Terminal size={10} /> <Terminal size={10} />
<span className="uppercase tracking-wider">{language}</span> <span className="truncate uppercase tracking-wider">{language}</span>
</div> </div>
)} )}
</div> </div>
@@ -176,7 +176,7 @@ function CodeBlock({ language, code }: { language: string; code: string }) {
<button <button
onClick={handleCopy} onClick={handleCopy}
className={clsx( className={clsx(
"flex items-center gap-1.5 px-2 py-1 rounded-md text-[11px] font-medium transition-all duration-200 border", "flex shrink-0 items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] font-medium transition-all duration-200",
isCopied isCopied
? "bg-green-500/10 text-green-400 border-green-500/20" ? "bg-green-500/10 text-green-400 border-green-500/20"
: "bg-gray-700/50 text-gray-400 border-transparent hover:bg-gray-600 hover:text-white" : "bg-gray-700/50 text-gray-400 border-transparent hover:bg-gray-600 hover:text-white"
@@ -188,17 +188,19 @@ function CodeBlock({ language, code }: { language: string; code: string }) {
</button> </button>
</div> </div>
<div className="relative font-mono text-[14px] leading-relaxed"> <div className="relative max-w-full overflow-x-auto font-mono text-[14px] leading-relaxed">
<SyntaxHighlighter <SyntaxHighlighter
style={vscDarkPlus} style={vscDarkPlus}
language={language} language={language}
PreTag="div" PreTag="div"
showLineNumbers={true} showLineNumbers={true}
wrapLongLines={false}
lineNumberStyle={{ minWidth: '2.5em', paddingRight: '1em', color: '#6e7681', textAlign: 'right' }} lineNumberStyle={{ minWidth: '2.5em', paddingRight: '1em', color: '#6e7681', textAlign: 'right' }}
customStyle={{ customStyle={{
margin: 0, margin: 0,
padding: '1.5rem', padding: '1.5rem',
background: 'transparent', background: 'transparent',
maxWidth: '100%',
}} }}
> >
{code} {code}

View File

@@ -1,11 +1,12 @@
import Link from 'next/link'; import Link from 'next/link';
import { FileText } from 'lucide-react';
import StatusBadge from '@/components/ui/StatusBadge'; import StatusBadge from '@/components/ui/StatusBadge';
import Surface from '@/components/ui/Surface'; import Surface from '@/components/ui/Surface';
import { Post } from '@/types'; import { Post } from '@/types';
const isNoticePost = (post: Post) => { const isNoticePost = (post: Post) => {
const categoryName = post.categoryName || ''; const categoryName = post.categoryName || '';
return categoryName === '공지' || categoryName === '怨듭?' || categoryName.toLowerCase() === 'notice'; return categoryName === '공지' || categoryName.toLowerCase() === 'notice';
}; };
const formatDate = (value: string) => { const formatDate = (value: string) => {
@@ -44,9 +45,14 @@ export default function PostCard({ post }: { post: Post }) {
className="flex h-full min-h-52 flex-col p-5 shadow-none" className="flex h-full min-h-52 flex-col p-5 shadow-none"
> >
<div className="mb-4 flex items-center justify-between gap-3"> <div className="mb-4 flex items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-control)]">
<FileText size={17} />
</span>
<StatusBadge tone={isNotice ? 'danger' : 'neutral'} className="shrink-0"> <StatusBadge tone={isNotice ? 'danger' : 'neutral'} className="shrink-0">
{post.categoryName || '미분류'} {post.categoryName || '미분류'}
</StatusBadge> </StatusBadge>
</div>
<time className="text-xs font-medium text-[var(--color-text-subtle)]"> <time className="text-xs font-medium text-[var(--color-text-subtle)]">
{formatDate(post.createdAt)} {formatDate(post.createdAt)}
</time> </time>

View File

@@ -1,7 +1,7 @@
'use client'; 'use client';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { AlertCircle, ArrowLeft, Calendar, ChevronLeft, ChevronRight, Loader2, User } from 'lucide-react'; import { AlertCircle, ArrowLeft, Calendar, ChevronLeft, ChevronRight, Loader2, Monitor, User } from 'lucide-react';
import Image from 'next/image'; import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
@@ -65,7 +65,7 @@ export default function PostDetailClient({ slug, initialPost }: PostDetailClient
const isAuthError = errorStatus === 401 || errorStatus === 403; const isAuthError = errorStatus === 401 || errorStatus === 403;
return ( return (
<WindowSurface className="mx-auto md:w-[70vw] md:max-w-[980px]" bodyClassName="px-4 py-20 text-center"> <WindowSurface className="mx-auto max-w-[980px]" bodyClassName="px-4 py-20 text-center">
<div className="mb-4 flex justify-center"> <div className="mb-4 flex justify-center">
<AlertCircle className="text-[var(--color-text-subtle)]" size={64} /> <AlertCircle className="text-[var(--color-text-subtle)]" size={64} />
</div> </div>
@@ -78,7 +78,7 @@ export default function PostDetailClient({ slug, initialPost }: PostDetailClient
<button <button
type="button" type="button"
onClick={() => router.push('/')} onClick={() => router.push('/')}
className="rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] px-5 py-2.5 font-semibold text-[var(--color-text-muted)] transition-colors hover:bg-[var(--window-bg-strong)]" className="rounded-lg border border-[var(--control-border)] bg-[var(--color-control)] px-5 py-2.5 font-semibold text-[var(--color-text-muted)] transition-colors hover:bg-[var(--card-bg-strong)]"
> >
</button> </button>
@@ -90,44 +90,51 @@ export default function PostDetailClient({ slug, initialPost }: PostDetailClient
const nextPost = post.nextPost; const nextPost = post.nextPost;
return ( return (
<div className="mx-auto w-full px-0 py-4 md:w-[78vw] md:max-w-[1280px] md:py-6"> <div className="mx-auto min-w-0 max-w-[1120px] px-0 py-3 md:py-6">
<Link href="/" className="mb-6 inline-flex items-center gap-1 text-sm font-medium text-[var(--color-text-muted)] transition-colors hover:text-[var(--color-accent)]"> <Link href="/" className="mb-5 inline-flex items-center gap-1 rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] px-3 py-2 text-sm font-semibold text-[var(--color-text-muted)] shadow-[var(--shadow-control)] backdrop-blur-[18px] transition-colors hover:bg-[var(--card-bg-strong)] hover:text-[var(--color-accent)]">
<ArrowLeft size={18} /> <ArrowLeft size={18} />
<span></span> <span>Finder</span>
</Link> </Link>
<div className="relative grid gap-6 xl:grid-cols-[minmax(0,900px)_250px] xl:justify-center xl:gap-8"> <div className="relative grid min-w-0 gap-6 xl:grid-cols-[minmax(0,820px)_220px] xl:justify-center xl:gap-8">
<main className="min-w-0 space-y-6"> <main className="min-w-0 space-y-6">
<WindowSurface <WindowSurface
as="article" as="article"
title="Reader" title="Reader"
subtitle={post.categoryName || '미분류'} subtitle={post.categoryName || '미분류'}
bodyClassName="p-6 md:p-10" className="mx-auto w-full max-w-[820px]"
bodyClassName="px-5 py-7 md:px-10 md:py-10"
controls={(
<div className="hidden items-center gap-1.5 text-xs font-semibold text-[var(--color-text-subtle)] sm:flex">
<Monitor size={14} />
<span className="max-w-44 truncate">{post.slug}</span>
</div>
)}
> >
<header className="mb-10 border-b border-[var(--color-line)] pb-8"> <header className="mb-9 border-b border-[var(--color-line)] pb-7">
<StatusBadge tone="neutral" className="mb-5"> <StatusBadge tone="neutral" className="mb-5">
{post.categoryName || '미분류'} {post.categoryName || '미분류'}
</StatusBadge> </StatusBadge>
<h1 className="mb-7 break-keep text-4xl font-bold leading-[1.08] tracking-normal text-[var(--color-text)] md:text-6xl"> <h1 className="mb-6 break-words text-3xl font-bold leading-tight tracking-normal text-[var(--color-text)] md:text-4xl lg:text-[2.75rem]">
{post.title} {post.title}
</h1> </h1>
<div className="flex flex-wrap items-center gap-5 text-sm text-[var(--color-text-muted)]"> <div className="flex flex-wrap items-center gap-x-5 gap-y-3 text-sm text-[var(--color-text-muted)]">
<div className="flex items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
{profile?.imageUrl ? ( {profile?.imageUrl ? (
<Image <Image
src={profile.imageUrl} src={profile.imageUrl}
alt="작성자" alt="작성자"
width={32} width={32}
height={32} height={32}
className="h-8 w-8 rounded-full border border-[var(--color-line)] object-cover shadow-sm" className="h-8 w-8 shrink-0 rounded-full border border-[var(--color-line)] object-cover shadow-sm"
unoptimized unoptimized
/> />
) : ( ) : (
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-black/[0.05] dark:bg-white/10"> <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-black/[0.05] dark:bg-white/10">
<User size={16} /> <User size={16} />
</div> </div>
)} )}
<span className="font-bold text-[var(--color-text)]">{profile?.name || 'Dev Park'}</span> <span className="min-w-0 truncate font-bold text-[var(--color-text)]">{profile?.name || 'Dev Park'}</span>
</div> </div>
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<Calendar size={16} /> <Calendar size={16} />
@@ -136,20 +143,20 @@ export default function PostDetailClient({ slug, initialPost }: PostDetailClient
</div> </div>
</header> </header>
<div className="prose prose-lg max-w-none prose-headings:font-bold prose-headings:tracking-normal prose-headings:text-[var(--color-text)] prose-p:text-[var(--color-text)] prose-p:leading-8 prose-strong:text-[var(--color-text)] prose-li:text-[var(--color-text-muted)] prose-li:leading-8 prose-a:text-[var(--color-accent)] prose-hr:border-[var(--color-line)] prose-pre:bg-[#1e1e1e] prose-pre:text-gray-100"> <div className="prose prose-base min-w-0 max-w-none break-words prose-headings:font-bold prose-headings:tracking-normal prose-headings:text-[var(--color-text)] prose-p:text-[var(--color-text)] prose-p:leading-8 prose-strong:text-[var(--color-text)] prose-li:text-[var(--color-text-muted)] prose-li:leading-8 prose-a:text-[var(--color-accent)] prose-hr:border-[var(--color-line)] prose-pre:max-w-full prose-pre:overflow-x-auto prose-pre:bg-[#1e1e1e] prose-pre:text-gray-100 md:prose-lg [overflow-wrap:anywhere]">
<MarkdownRenderer content={post.content || ''} /> <MarkdownRenderer content={post.content || ''} />
</div> </div>
</WindowSurface> </WindowSurface>
<WindowSurface title="Navigation" bodyClassName="p-4 md:p-5"> <WindowSurface title="Navigation" showTrafficLights={false} className="mx-auto max-w-[820px]" bodyClassName="p-4 md:p-5">
<nav className="grid grid-cols-1 gap-4 md:grid-cols-2"> <nav className="grid min-w-0 grid-cols-1 gap-4 md:grid-cols-2">
{prevPost ? ( {prevPost ? (
<Link href={`/posts/${prevPost.slug}`} className="group flex w-full flex-col items-start gap-1 rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] p-5 transition-colors hover:bg-[var(--window-bg-strong)]"> <Link href={`/posts/${prevPost.slug}`} className="group flex min-w-0 flex-col items-start gap-1 rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] p-4 shadow-[var(--shadow-card)] transition-colors hover:bg-[var(--card-bg-strong)] md:p-5">
<span className="flex items-center gap-1 text-xs font-bold text-[var(--color-text-subtle)] transition-colors group-hover:text-[var(--color-accent)]"> <span className="flex items-center gap-1 text-xs font-bold text-[var(--color-text-subtle)] transition-colors group-hover:text-[var(--color-accent)]">
<ChevronLeft size={16} /> <ChevronLeft size={16} />
</span> </span>
<span className="line-clamp-1 w-full text-left font-bold text-[var(--color-text-muted)] transition-colors group-hover:text-[var(--color-accent)]"> <span className="line-clamp-2 w-full break-words text-left font-bold text-[var(--color-text-muted)] transition-colors group-hover:text-[var(--color-accent)]">
{prevPost.title} {prevPost.title}
</span> </span>
</Link> </Link>
@@ -163,12 +170,12 @@ export default function PostDetailClient({ slug, initialPost }: PostDetailClient
)} )}
{nextPost ? ( {nextPost ? (
<Link href={`/posts/${nextPost.slug}`} className="group flex w-full flex-col items-end gap-1 rounded-lg border border-[var(--color-line)] bg-[var(--color-control)] p-5 transition-colors hover:bg-[var(--window-bg-strong)]"> <Link href={`/posts/${nextPost.slug}`} className="group flex min-w-0 flex-col items-end gap-1 rounded-lg border border-[var(--card-border)] bg-[var(--card-bg)] p-4 shadow-[var(--shadow-card)] transition-colors hover:bg-[var(--card-bg-strong)] md:p-5">
<span className="flex items-center gap-1 text-xs font-bold text-[var(--color-text-subtle)] transition-colors group-hover:text-[var(--color-accent)]"> <span className="flex items-center gap-1 text-xs font-bold text-[var(--color-text-subtle)] transition-colors group-hover:text-[var(--color-accent)]">
<ChevronRight size={16} /> <ChevronRight size={16} />
</span> </span>
<span className="line-clamp-1 w-full text-right font-bold text-[var(--color-text-muted)] transition-colors group-hover:text-[var(--color-accent)]"> <span className="line-clamp-2 w-full break-words text-right font-bold text-[var(--color-text-muted)] transition-colors group-hover:text-[var(--color-accent)]">
{nextPost.title} {nextPost.title}
</span> </span>
</Link> </Link>
@@ -183,13 +190,13 @@ export default function PostDetailClient({ slug, initialPost }: PostDetailClient
</nav> </nav>
</WindowSurface> </WindowSurface>
<WindowSurface title="Comments" bodyClassName="p-5 md:p-6"> <WindowSurface title="Comments" showTrafficLights={false} className="mx-auto max-w-[820px]" bodyClassName="p-5 md:p-6">
<CommentList postSlug={post.slug} /> <CommentList postSlug={post.slug} />
</WindowSurface> </WindowSurface>
</main> </main>
<aside className="hidden w-[220px] shrink-0 xl:block"> <aside className="hidden w-[220px] shrink-0 xl:block">
<WindowSurface title="Inspector" bodyClassName="p-4" className="sticky top-24"> <WindowSurface title="목차" showTrafficLights={false} bodyClassName="p-4" className="sticky top-16 shadow-[var(--shadow-card)]">
<TOC content={post.content || ''} /> <TOC content={post.content || ''} />
</WindowSurface> </WindowSurface>
</aside> </aside>

View File

@@ -1,5 +1,5 @@
import Link from 'next/link'; import Link from 'next/link';
import { ChevronRight, Eye } from 'lucide-react'; import { ChevronRight, Eye, FileText } from 'lucide-react';
import { clsx } from 'clsx'; import { clsx } from 'clsx';
import StatusBadge from '@/components/ui/StatusBadge'; import StatusBadge from '@/components/ui/StatusBadge';
import { Post } from '@/types'; import { Post } from '@/types';
@@ -11,7 +11,7 @@ interface PostListItemProps {
const isNoticePost = (post: Post) => { const isNoticePost = (post: Post) => {
const categoryName = post.categoryName || ''; const categoryName = post.categoryName || '';
return categoryName === '공지' || categoryName === '怨듭?' || categoryName.toLowerCase() === 'notice'; return categoryName === '공지' || categoryName.toLowerCase() === 'notice';
}; };
const formatDate = (value: string) => { const formatDate = (value: string) => {
@@ -33,10 +33,13 @@ export default function PostListItem({ post, showViews = false }: PostListItemPr
<div <div
className={clsx( className={clsx(
'flex items-center justify-between gap-4 rounded-lg px-3 py-4 transition duration-150', 'flex items-center justify-between gap-4 rounded-lg px-3 py-4 transition duration-150',
isNotice ? 'hover:bg-red-500/[0.06]' : 'hover:bg-black/[0.03] dark:hover:bg-white/10', isNotice ? 'hover:bg-red-500/[0.06]' : 'hover:bg-[var(--card-bg)]',
)} )}
> >
<div className="flex min-w-0 flex-1 items-center gap-3"> <div className="flex min-w-0 flex-1 items-center gap-3">
<span className="hidden h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-[var(--card-border)] bg-[var(--card-bg-strong)] text-[var(--color-accent)] shadow-[var(--shadow-control)] sm:flex">
<FileText size={17} />
</span>
<StatusBadge tone={isNotice ? 'danger' : 'neutral'} className="hidden shrink-0 sm:inline-flex"> <StatusBadge tone={isNotice ? 'danger' : 'neutral'} className="hidden shrink-0 sm:inline-flex">
{post.categoryName || '미분류'} {post.categoryName || '미분류'}
</StatusBadge> </StatusBadge>

View File

@@ -48,7 +48,7 @@ export default function PostSearch({
onChange={(e) => setKeyword(e.target.value)} onChange={(e) => setKeyword(e.target.value)}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
placeholder={placeholder} placeholder={placeholder}
className="w-full rounded-full border border-[var(--color-line)] bg-[var(--color-control)] py-2.5 pl-10 pr-10 text-sm text-[var(--color-text)] shadow-[var(--shadow-control)] outline-none transition-all placeholder:text-[var(--color-text-subtle)] focus:border-[var(--color-accent)] focus:bg-[var(--color-surface-strong)]" className="w-full rounded-full border border-[var(--control-border)] bg-[var(--color-control)] py-2.5 pl-10 pr-10 text-sm text-[var(--color-text)] shadow-[var(--shadow-control)] outline-none transition-all placeholder:text-[var(--color-text-subtle)] focus:border-[var(--color-accent)] focus:bg-[var(--card-bg-strong)]"
/> />
<Search <Search
className="absolute left-3.5 top-1/2 -translate-y-1/2 cursor-pointer text-[var(--color-text-subtle)] transition-colors hover:text-[var(--color-accent)]" className="absolute left-3.5 top-1/2 -translate-y-1/2 cursor-pointer text-[var(--color-text-subtle)] transition-colors hover:text-[var(--color-accent)]"
@@ -58,7 +58,7 @@ export default function PostSearch({
{keyword && ( {keyword && (
<button <button
onClick={handleClear} onClick={handleClear}
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-full p-1 text-[var(--color-text-subtle)] transition-colors hover:bg-black/[0.06] hover:text-[var(--color-text)] dark:hover:bg-white/10" className="absolute right-3 top-1/2 -translate-y-1/2 rounded-full p-1 text-[var(--color-text-subtle)] transition-colors hover:bg-[var(--card-bg)] hover:text-[var(--color-text)]"
aria-label="검색어 지우기" aria-label="검색어 지우기"
> >
<X size={14} /> <X size={14} />

View File

@@ -20,7 +20,7 @@ export default function ThemeToggle() {
return ( return (
<div <div
className="inline-flex h-9 shrink-0 items-center rounded-full border border-[var(--color-line)] bg-[var(--color-control)] p-1 shadow-[var(--shadow-control)] backdrop-blur-2xl" className="inline-flex h-9 shrink-0 items-center rounded-full border border-[var(--control-border)] bg-[var(--color-control)] p-1 shadow-[var(--shadow-control)] backdrop-blur-[18px]"
role="group" role="group"
aria-label="화면 테마" aria-label="화면 테마"
> >
@@ -39,8 +39,8 @@ export default function ThemeToggle() {
className={clsx( className={clsx(
'inline-flex h-7 w-7 items-center justify-center rounded-full text-xs font-semibold transition duration-150 sm:w-8', 'inline-flex h-7 w-7 items-center justify-center rounded-full text-xs font-semibold transition duration-150 sm:w-8',
isSelected isSelected
? 'bg-[var(--window-bg-strong)] text-[var(--color-text)] shadow-sm' ? 'bg-[var(--card-bg-strong)] text-[var(--color-text)] shadow-sm'
: 'text-[var(--color-text-subtle)] hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10', : 'text-[var(--color-text-subtle)] hover:bg-[var(--card-bg)] hover:text-[var(--color-text)]',
)} )}
> >
<Icon size={15} strokeWidth={2.2} /> <Icon size={15} strokeWidth={2.2} />

View File

@@ -17,7 +17,7 @@ export default function EmptyState({
return ( return (
<div <div
className={clsx( className={clsx(
'flex min-h-36 flex-col items-center justify-center rounded-lg border border-dashed border-[var(--color-line)] bg-[var(--color-surface)] px-5 py-10 text-center', 'flex min-h-36 flex-col items-center justify-center rounded-lg border border-dashed border-[var(--card-border)] bg-[var(--card-bg)] px-5 py-10 text-center shadow-[var(--shadow-card)] backdrop-blur-[18px]',
className, className,
)} )}
> >

View File

@@ -7,7 +7,7 @@ export interface SegmentedControlOption<T extends string> {
interface SegmentedControlProps<T extends string> { interface SegmentedControlProps<T extends string> {
ariaLabel: string; ariaLabel: string;
options: SegmentedControlOption<T>[]; options: readonly SegmentedControlOption<T>[];
value: T; value: T;
onChange: (value: T) => void; onChange: (value: T) => void;
className?: string; className?: string;
@@ -23,7 +23,7 @@ export default function SegmentedControl<T extends string>({
return ( return (
<div <div
className={clsx( className={clsx(
'inline-flex h-9 rounded-full border border-[var(--color-line)] bg-[var(--color-control)] p-1 shadow-[var(--shadow-control)] backdrop-blur-xl', 'inline-flex h-9 rounded-full border border-[var(--control-border)] bg-[var(--color-control)] p-1 shadow-[var(--shadow-control)] backdrop-blur-[18px]',
className, className,
)} )}
role="group" role="group"
@@ -41,8 +41,8 @@ export default function SegmentedControl<T extends string>({
className={clsx( className={clsx(
'min-w-14 rounded-full px-3 text-sm font-semibold transition duration-150', 'min-w-14 rounded-full px-3 text-sm font-semibold transition duration-150',
isSelected isSelected
? 'bg-[var(--color-surface-strong)] text-[var(--color-text)] shadow-sm' ? 'bg-[var(--card-bg-strong)] text-[var(--color-text)] shadow-sm'
: 'text-[var(--color-text-muted)] hover:bg-black/[0.04] hover:text-[var(--color-text)] dark:hover:bg-white/10', : 'text-[var(--color-text-muted)] hover:bg-[var(--card-bg)] hover:text-[var(--color-text)]',
)} )}
> >
{option.label} {option.label}

View File

@@ -19,11 +19,11 @@ export default function Surface({
return ( return (
<Component <Component
className={clsx( className={clsx(
'rounded-lg border border-[var(--window-border)] backdrop-blur-2xl', 'rounded-lg border border-[var(--card-border)] backdrop-blur-[20px]',
strong strong
? 'bg-[var(--window-bg-strong)] shadow-[var(--shadow-card)]' ? 'bg-[var(--card-bg-strong)] shadow-[var(--shadow-card)]'
: 'bg-[var(--window-bg)] shadow-[var(--shadow-card)]', : 'bg-[var(--card-bg)] shadow-[var(--shadow-card)]',
interactive && 'transition duration-150 hover:-translate-y-0.5 hover:border-black/15 hover:bg-[var(--window-bg-strong)] hover:shadow-[var(--shadow-control)] dark:hover:border-white/20', interactive && 'transition duration-150 hover:-translate-y-0.5 hover:border-[var(--card-border-hover)] hover:bg-[var(--card-bg-strong)] hover:shadow-[var(--shadow-control)]',
className, className,
)} )}
{...props} {...props}

View File

@@ -28,13 +28,13 @@ export default function WindowSurface({
return ( return (
<Component <Component
className={clsx( className={clsx(
'w-full overflow-hidden rounded-lg border border-[var(--window-border)] bg-[var(--window-bg)] shadow-[var(--shadow-window)] backdrop-blur-2xl', 'window-surface w-full overflow-hidden rounded-lg border border-[var(--window-border)] bg-[var(--window-bg)] shadow-[var(--shadow-window)] backdrop-blur-[30px]',
className, className,
)} )}
{...props} {...props}
> >
{hasTitlebar && ( {hasTitlebar && (
<div className="flex min-h-11 items-center justify-between gap-4 border-b border-[var(--color-line)] bg-[var(--window-titlebar)] px-4 py-2.5"> <div className="flex min-h-11 items-center justify-between gap-4 border-b border-[var(--window-titlebar-border)] bg-[var(--window-titlebar)] px-4 py-2.5 backdrop-blur-[28px]">
<div className="flex min-w-0 items-center gap-3"> <div className="flex min-w-0 items-center gap-3">
{showTrafficLights && ( {showTrafficLights && (
<div className="flex shrink-0 items-center gap-1.5" aria-hidden="true"> <div className="flex shrink-0 items-center gap-1.5" aria-hidden="true">

33
src/lib/site.ts Normal file
View File

@@ -0,0 +1,33 @@
export const SITE_URL = 'https://blog.wypark.me';
export const SITE_NAME = 'WYPark Blog';
export const DEFAULT_DESCRIPTION = '개발 블로그';
const API_DATE_TIMEZONE = '+09:00';
const TIMEZONE_SUFFIX_PATTERN = /(z|[+-]\d{2}:?\d{2})$/i;
const trimSubMilliseconds = (value: string) => {
return value.replace(/(\.\d{3})\d+/, '$1');
};
const withApiTimezone = (value: string) => {
if (TIMEZONE_SUFFIX_PATTERN.test(value)) return value;
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T00:00:00${API_DATE_TIMEZONE}`;
return `${value}${API_DATE_TIMEZONE}`;
};
export const getCanonicalUrl = (path = '/') => {
return new URL(path, SITE_URL).toString();
};
export const parseApiDate = (value?: string | null, fallback = new Date()) => {
if (!value) return fallback;
const date = new Date(withApiTimezone(trimSubMilliseconds(value.trim())));
if (Number.isNaN(date.getTime())) return fallback;
const now = new Date();
return date > now ? now : date;
};

View File

@@ -60,6 +60,72 @@ export interface ChessPuzzle {
sourceUrl: string; sourceUrl: string;
} }
export type ChessOutcome = 'IN_PROGRESS' | 'WIN' | 'LOSS' | 'DRAW' | 'UNKNOWN';
export type ChessColor = 'white' | 'black';
export type MaiaModel = '3m' | '5m' | '23m' | '79m';
export interface ChessGameCreateRequest {
rating?: number;
playerColor?: ChessColor;
model?: MaiaModel;
temperature?: number;
topP?: number;
}
export interface ChessGameResponse {
gameId: string;
rating: number;
playerColor: ChessColor;
model: MaiaModel;
fen: string;
turn: ChessColor;
moves: string[];
status: string;
result: string | null;
outcome: ChessOutcome;
pgn: string;
maiaMove: string | null;
}
export interface ChessGameSummaryResponse {
gameId: string;
rating: number;
playerColor: ChessColor;
model: string;
status: string;
result: string | null;
outcome: ChessOutcome;
movesCount: number;
createdAt: string;
updatedAt: string;
}
export interface ChessGameStatsResponse {
total: number;
inProgress: number;
wins: number;
losses: number;
draws: number;
unknown: number;
}
export interface ChessGamePgnResponse {
gameId: string;
pgn: string;
}
export interface ChessMoveRequest {
move: string;
}
export interface ChessGamePageResponse extends PageMeta {
content: ChessGameSummaryResponse[];
page?: PageMeta;
size?: number;
first?: boolean;
empty?: boolean;
}
// 4. 로그인 응답 // 4. 로그인 응답
export interface AuthResponse { export interface AuthResponse {
grantType: string; grantType: string;