feat : BBS 게시판을 백엔드 스크랩 게시물 API로 교체 (JWT 인증, 읽음 처리)
SpecialSource Frontend (React) CD / deploy (push) Successful in 13s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
headporterandClaude Opus 5.5 committed 2026-11-23 17:35:51 +09:00
1 parent cc814a484b
commit 4b10d4d3b2
11 files changed
+197 -85

No files matched your search

+29 -9
View File
@@ -2,8 +2,9 @@
import { useEffect, useReducer, useRef, useState, useSyncExternalStore } from "react";
import { PALETTE_KEY, PALETTES } from "../constants";
import { execute, initialState } from "../lib/command";
import type { Nav, Palette } from "../types";
import { fetchFeed } from "../api";
import { apiError, execute, initialState, LOGOUT } from "../lib/command";
import type { ListKind, Nav, Palette } from "../types";
import LoginForm from "./LoginForm";
import MainMenu from "./MainMenu";
import PostDetail from "./PostDetail";
@@ -57,6 +58,19 @@ export default function BbsTerminal() {
}
}, [state.screen, state.list, state.postId]);
// 메인(새 글)·목록 화면에 들어오거나 "L"을 누르면 서버에서 목록을 다시 불러옴
const feedKind: ListKind | null = state.screen === "main" ? "board" : state.screen === "list" ? state.list : null;
useEffect(() => {
if (!feedKind || !state.token) return;
let stale = false; // 응답 전에 화면이 바뀌면 늦게 온 응답은 버림
fetchFeed(state.token, feedKind)
.then((feed) => !stale && dispatch({ feed }))
.catch((e) => !stale && dispatch(apiError(e)));
return () => {
stale = true;
};
}, [feedKind, state.token, state.rev]);
useEffect(() => {
const onPop = (e: PopStateEvent) => {
if (e.state?.bbs) dispatch(e.state.bbs);
@@ -83,7 +97,7 @@ export default function BbsTerminal() {
{
key: "F5",
label: state.user ? "로그아웃" : "로그인",
run: () => dispatch(state.user ? { user: null } : { screen: "login" }),
run: () => dispatch(state.user ? LOGOUT : { screen: "login" }),
},
];
@@ -119,19 +133,25 @@ export default function BbsTerminal() {
<div className={styles.grid}>
{state.screen === "main" && (
<MainMenu
readIds={state.readIds}
feed={state.feed}
loggedIn={!!state.user}
onSelect={submitFromClick}
onOpenPost={(id) => {
onOpenPost={(num) => {
// 메인에서 숫자는 메뉴 번호라서, 게시판으로 옮긴 뒤 글 번호를 실행
dispatch({ screen: "list", list: "board" });
dispatch(String(id));
dispatch(String(num));
}}
/>
)}
{state.screen === "login" && <LoginForm onSuccess={(user) => dispatch({ screen: "main", user })} />}
{state.screen === "list" && <PostList kind={state.list} readIds={state.readIds} onSelect={submitFromClick} />}
{state.screen === "post" && state.postId !== null && <PostDetail postId={state.postId} />}
{state.screen === "login" && (
<LoginForm onSuccess={(user, token) => dispatch({ screen: "main", user, token })} />
)}
{state.screen === "list" && (
<PostList kind={state.list} feed={state.feed} loggedIn={!!state.user} onSelect={submitFromClick} />
)}
{state.screen === "post" && state.token && (
<PostDetail post={state.feed?.posts.find((p) => p.id === state.postId)} token={state.token} />
)}
{state.error && <div className={`${styles.full} ${styles.error}`}>{state.error}</div>}
</div>
</div>
+4 -7
View File
@@ -1,11 +1,8 @@
import { useState, type FormEvent } from "react";
import { API_URL } from "../api";
import styles from "./bbs.module.css";
// 개발은 로컬 백엔드 직접 호출, 운영(nginx)은 같은 도메인의 /api 프록시. NEXT_PUBLIC_API_URL로 덮어쓰기 가능
const API_URL =
process.env.NEXT_PUBLIC_API_URL ?? (process.env.NODE_ENV === "development" ? "http://localhost:8080" : "");
export default function LoginForm({ onSuccess }: { onSuccess: (user: string) => void }) {
export default function LoginForm({ onSuccess }: { onSuccess: (user: string, token: string) => void }) {
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
@@ -22,8 +19,8 @@ export default function LoginForm({ onSuccess }: { onSuccess: (user: string) =>
body: JSON.stringify({ username, password: form.get("password") }),
});
if (!res.ok) throw new Error(res.status === 401 ? "아이디 또는 비밀번호가 틀렸습니다." : `서버 오류 (${res.status})`);
// ponytail: 토큰은 아직 쓰는 API가 없어 버림. 인증 API 호출이 생기면 저장해서 Authorization 헤더로 전달
onSuccess(username);
const { token } = await res.json(); // 이후 API 호출의 Authorization 헤더에 사용
onSuccess(username, token);
} catch (err) {
setError(err instanceof TypeError ? "서버에 연결할 수 없습니다." : (err as Error).message);
} finally {
+11 -8
View File
@@ -1,10 +1,10 @@
import { MENU } from "../constants";
import { POSTS } from "../mocks/posts";
import type { Feed } from "../types";
import { PostTable } from "./PostList";
import styles from "./bbs.module.css";
interface Props {
readIds: number[];
feed: Feed | null;
loggedIn: boolean;
onSelect: (cmd: string) => void;
onOpenPost: (id: number) => void;
@@ -23,8 +23,8 @@ const LOGO = '';
// \__ \| (_) || |_| || /| (__ | _|
// |___/ \___/ \___/ |_|_\ \___||___|`;
export default function MainMenu({ readIds, loggedIn, onSelect, onOpenPost }: Props) {
const unread = POSTS.filter((p) => !readIds.includes(p.id));
export default function MainMenu({ feed, loggedIn, onSelect, onOpenPost }: Props) {
const board = feed?.kind === "board" ? feed : null; // 메인에서는 스크랩 게시판(안 읽은 글)을 불러옴
return (
<>
@@ -43,8 +43,7 @@ export default function MainMenu({ readIds, loggedIn, onSelect, onOpenPost }: Pr
<li key={m.num} onClick={() => onSelect(String(m.num))}>
<span className={styles.num}>{m.num}.</span>
<span>{logout ? "로그아웃" : m.label}</span>
{m.key === "board" && <span className={styles.accent}>[새글 {unread.length}]</span>}
{m.key === "viewed" && <span className={styles.accent}>[{readIds.length}건]</span>}
{m.key === "board" && board && <span className={styles.accent}>[새글 {board.total}]</span>}
<span className={`${styles.dim} ${styles.en}`}>{logout ? "LOGOUT" : m.en}</span>
</li>
);
@@ -54,10 +53,14 @@ export default function MainMenu({ readIds, loggedIn, onSelect, onOpenPost }: Pr
<section className={styles.win}>
<span className={styles.cap}>═ 새 글 ═</span>
{unread.length === 0 ? (
{!loggedIn ? (
<div className={styles.dim}>로그인하면 스크랩된 새 글이 보입니다.</div>
) : !board ? (
<div className={styles.dim}>불러오는 중...</div>
) : board.posts.length === 0 ? (
<div className={styles.dim}>새 글을 모두 읽었습니다.</div>
) : (
<PostTable posts={unread.slice(0, 5)} onSelect={onOpenPost} />
<PostTable posts={board.posts.slice(0, 5)} onSelect={onOpenPost} />
)}
<div className={styles.footer}>
줄을 누르면 바로 읽기 · <b>2</b>=게시판 전체
+47 -8
View File
@@ -1,24 +1,63 @@
import { POSTS } from "../mocks/posts";
import { useEffect } from "react";
import { markViewed } from "../api";
import type { ScrapedPost } from "../types";
import styles from "./bbs.module.css";
export default function PostDetail({ postId }: { postId: number }) {
const post = POSTS.find((p) => p.id === postId);
if (!post) return null;
// 외부 사이트 이미지는 Referer를 보고 차단하는 경우가 많음 → 안 보내기. 본문 링크는 새 탭으로
const prepare = (html: string) =>
html
.replaceAll("<img ", '<img referrerpolicy="no-referrer" loading="lazy" ')
.replaceAll("<a ", '<a target="_blank" rel="noreferrer" ');
export default function PostDetail({ post, token }: { post: ScrapedPost | undefined; token: string }) {
// 글을 열면 서버에 "읽음" 기록 → 스크랩 게시판에서 빠지고 "내가 읽은 글"로 이동
useEffect(() => {
if (post) markViewed(token, post.id).catch(() => {}); // 실패해도 읽기엔 지장 없음
}, [token, post]);
if (!post) {
return (
<section className={`${styles.win} ${styles.full}`}>
<div className={styles.dim}>글을 찾을 수 없습니다. &quot;L&quot;로 목록을 다시 불러오세요.</div>
</section>
);
}
return (
<section className={`${styles.win} ${styles.full}`}>
<span className={styles.cap}>═ 자유게시판 #{post.id} ═</span>
<span className={styles.cap}>
═ {post.siteName} {post.boardName} ═
</span>
<div className={styles.postHead}>
<span>제목 :</span> {post.title}
</div>
<div className={styles.postHead}>
<span>글쓴이:</span> {post.author} <span>날짜:</span> {post.date} <span>조회:</span> {post.views}
<span>글쓴이:</span> {post.author ?? "-"} <span>날짜:</span> {post.postedAt ?? "-"} <span>조회:</span>{" "}
{post.viewCount ?? "-"} <span>추천:</span> {post.likeCount ?? "-"}
</div>
<hr className={styles.rule} />
<div className={styles.body}>{post.body}</div>
{post.content ? (
// content는 백엔드에서 Jsoup Safelist로 script·이벤트 속성을 제거한 HTML이라 그대로 렌더링
<div className={styles.html} dangerouslySetInnerHTML={{ __html: prepare(post.content) }} />
) : post.imageUrls.length > 0 ? (
post.imageUrls.map((src, i) => (
<figure key={src} className={styles.figure}>
{/* eslint-disable-next-line @next/next/no-img-element -- 정적 export라 next/image 최적화 불가 */}
<img src={src} alt={`첨부 그림 ${i + 1}`} referrerPolicy="no-referrer" loading="lazy" />
<figcaption>
<span>[그림 {i + 1}]</span>
</figcaption>
</figure>
))
) : (
<div className={styles.dim}>본문을 가져오지 못했습니다. 원문에서 확인하세요.</div>
)}
<hr className={styles.rule} />
<div className={styles.footer}>
<b>L</b>=목록 · <b>M</b>=메인
<a className={styles.accent} href={post.link} target="_blank" rel="noreferrer">
원문 보기 ↗
</a>{" "}
· <b>L</b>=목록 · <b>M</b>=메인
</div>
</section>
);
+26 -16
View File
@@ -1,20 +1,21 @@
import { POSTS } from "../mocks/posts";
import type { ListKind, Post } from "../types";
import type { Feed, ListKind, ScrapedPost } from "../types";
import styles from "./bbs.module.css";
interface Props {
kind: ListKind;
readIds: number[];
feed: Feed | null;
loggedIn: boolean;
onSelect: (cmd: string) => void;
}
/** 번호 / 글쓴이 / 날짜 / 조회 / 제목 표 (메인의 "새 글" 창에서도 사용) */
export function PostTable({ posts, dim, onSelect }: { posts: Post[]; dim?: boolean; onSelect: (id: number) => void }) {
/** 번호 / 게시판 / 글쓴이 / 날짜 / 조회 / 제목 표 (메인의 "새 글" 창에서도 사용). 번호 = 목록 순서 */
export function PostTable({ posts, dim, onSelect }: { posts: ScrapedPost[]; dim?: boolean; onSelect: (num: number) => void }) {
return (
<table className={styles.tbl}>
<thead>
<tr>
<th className={styles.idx}>번호</th>
<th className={styles.wide}>게시판</th>
<th className={styles.wide}>글쓴이</th>
<th>날짜</th>
<th className={`${styles.idx} ${styles.wide}`}>조회</th>
@@ -22,13 +23,17 @@ export function PostTable({ posts, dim, onSelect }: { posts: Post[]; dim?: boole
</tr>
</thead>
<tbody>
{posts.map((p) => (
<tr key={p.id} onClick={() => onSelect(p.id)}>
<td className={styles.idx}>{p.id}</td>
{posts.map((p, i) => (
<tr key={p.id} onClick={() => onSelect(i + 1)}>
<td className={styles.idx}>{i + 1}</td>
<td className={`${styles.wide} ${styles.accent}`}>{p.boardName}</td>
<td className={styles.wide}>{p.author}</td>
<td>{p.date}</td>
<td className={`${styles.idx} ${styles.wide}`}>{p.views}</td>
<td className={`${styles.title} ${dim ? styles.dim : ""}`}>{p.title}</td>
<td>{p.postedAt}</td>
<td className={`${styles.idx} ${styles.wide}`}>{p.viewCount}</td>
<td className={`${styles.title} ${dim ? styles.dim : ""}`}>
{p.title}
{p.imageUrls.length > 0 && <span className={styles.accent}> [그림{p.imageUrls.length}]</span>}
</td>
</tr>
))}
</tbody>
@@ -36,19 +41,24 @@ export function PostTable({ posts, dim, onSelect }: { posts: Post[]; dim?: boole
);
}
export default function PostList({ kind, readIds, onSelect }: Props) {
export default function PostList({ kind, feed, loggedIn, onSelect }: Props) {
const viewed = kind === "viewed";
const posts = POSTS.filter((p) => readIds.includes(p.id) === viewed);
const ready = feed?.kind === kind ? feed : null;
return (
<section className={`${styles.win} ${styles.full}`}>
<span className={styles.cap}>
═ [{viewed ? 3 : 2}] {viewed ? "내가 읽은 글" : "자유게시판"} ({posts.length}건) ═
═ [{viewed ? 3 : 2}] {viewed ? "내가 읽은 글" : "스크랩 게시판"}
{ready && ` (${ready.total}건)`} ═
</span>
{posts.length === 0 ? (
{!loggedIn ? (
<div className={styles.dim}>로그인이 필요합니다. (F5 또는 메인에서 7)</div>
) : !ready ? (
<div className={styles.dim}>불러오는 중...</div>
) : ready.posts.length === 0 ? (
<div className={styles.dim}>표시할 글이 없습니다.</div>
) : (
<PostTable posts={posts} dim={viewed} onSelect={(id) => onSelect(String(id))} />
<PostTable posts={ready.posts} dim={viewed} onSelect={(n) => onSelect(String(n))} />
)}
<div className={styles.footer}>
<b>번호</b>=글읽기 · <b>M</b>=메인 · <b>L</b>=새로고침
@@ -80,6 +80,16 @@
/* 글 읽기 */
.postHead span { color: var(--bbs-accent); }
.body { white-space: pre-wrap; color: var(--bbs-hi); }
/* 스크랩 본문 HTML (원문 문단·이미지 위치 그대로) */
.html { color: var(--bbs-hi); overflow-wrap: anywhere; }
.html p { margin: 0 0 0.6em; }
.html a { color: var(--bbs-accent); }
.html img, .html video, .html iframe { display: block; max-width: min(100%, 60ch); height: auto; margin: 0.6em 0; border: 4px double var(--bbs-hi); }
/* 첨부 이미지(본문이 없을 때): 이중선 액자 + 캡션 */
.figure { margin: 1em 0 0; max-width: 60ch; }
.figure img { display: block; width: 100%; height: auto; border: 4px double var(--bbs-hi); }
.figure figcaption { color: var(--bbs-dim); }
.figure figcaption span { color: var(--bbs-accent); }
/* 로그인 */
.loginForm { display: flex; flex-direction: column; gap: 0.5em; }