feat : BBS 게시판 탭·모바일 제스처 추가, 로그인 유지 및 뒤로가기 새로고침 버그 수정
SpecialSource Frontend (React) CD / deploy (push) Successful in 15s

- 로그인 토큰을 sessionStorage에 보관해 새로고침해도 로그인 유지
- 메인 화면에서 L이 로그아웃되던 문제 수정 (L = 목록으로 통일)
- 게시판 목록을 번호/게시판/제목/날짜(YYYYMMDD) 레이아웃으로 변경
- 게시판 종류별 탭 추가 (클릭 또는 B번호 입력, /boards API 사용)
- 모바일 제스처: 좌우 스와이프로 뒤로/앞으로, 당겨서 목록 새로고침
- 뒤로가기 시 Next.js가 페이지를 새로고침해 메인으로 튕기던 버그 수정
- study-notes 5번 정정

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
headporterandClaude Opus 5.5 committed 2026-11-25 15:22:50 +09:00
1 parent 523b90be15
commit 8914954c55
9 files changed
+173 -40

No files matched your search

+8 -4
View File
@@ -1,4 +1,4 @@
import type { Feed, ListKind } from "./types";
import type { Board, Feed, ListKind } from "./types";
// 개발은 로컬 백엔드 직접 호출, 운영(nginx)은 같은 도메인의 /api 프록시. NEXT_PUBLIC_API_URL로 덮어쓰기 가능
export const API_URL =
@@ -15,11 +15,15 @@ async function call(path: string, token: string, init?: RequestInit) {
}
// ponytail: 첫 페이지 30건만 가져옴. 페이지 넘김이 필요해지면 page 파라미터 추가
export async function fetchFeed(token: string, kind: ListKind): Promise<Feed> {
const res = await call(`/api/scraped-posts${kind === "viewed" ? "/viewed" : ""}?size=30`, token);
export async function fetchFeed(token: string, kind: ListKind, board: string | null): Promise<Feed> {
const filter = board ? `&board=${encodeURIComponent(board)}` : "";
const res = await call(`/api/scraped-posts${kind === "viewed" ? "/viewed" : ""}?size=30${filter}`, token);
const data = await res.json(); // Spring Page 응답: { content: [...], totalElements, ... }
return { kind, posts: data.content, total: data.totalElements };
return { kind, board, posts: data.content, total: data.totalElements };
}
export const fetchBoards = async (token: string): Promise<Board[]> =>
(await call("/api/scraped-posts/boards", token)).json();
export const markViewed = (token: string, id: number) =>
call(`/api/scraped-posts/${id}/view`, token, { method: "POST" });
+84 -13
View File
@@ -1,8 +1,8 @@
"use client";
import { useEffect, useReducer, useRef, useState, useSyncExternalStore } from "react";
import { PALETTE_KEY, PALETTES } from "../constants";
import { fetchFeed } from "../api";
import { AUTH_KEY, PALETTE_KEY, PALETTES } from "../constants";
import { fetchBoards, fetchFeed } from "../api";
import { apiError, execute, initialState, LOGOUT } from "../lib/command";
import type { ListKind, Nav, Palette } from "../types";
import LoginForm from "./LoginForm";
@@ -12,6 +12,10 @@ import PostList from "./PostList";
import styles from "./bbs.module.css";
const DEFAULT_PALETTE: Palette = "blue";
// 터치 제스처 기준 (px): 가장자리 폭 / 좌우로 밀어야 하는 거리 / 아래로 당겨야 하는 거리
const EDGE = 30;
const SWIPE = 70;
const PULL = 90;
// localStorage를 외부 저장소로 보고 React가 구독 (다른 탭에서 바꿔도 동기화됨)
const subscribe = (onChange: () => void) => {
@@ -46,37 +50,67 @@ export default function BbsTerminal() {
const [input, setInput] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const mounted = useRef(false);
const touch = useRef<{ x: number; y: number; top: boolean } | null>(null); // 손가락을 댄 위치
const [pulling, setPulling] = useState(false); // 아래로 충분히 당겼는지 (안내 문구 표시)
// 새로고침해도 로그인 유지: 탭이 열려 있는 동안만 sessionStorage에 보관 (탭 닫으면 사라짐)
// 서버 렌더링 결과와 어긋나지 않도록 첫 렌더링 뒤(useEffect)에 복원. 아래 저장 effect보다 먼저 읽어야 함
useEffect(() => {
try {
const saved = JSON.parse(sessionStorage.getItem(AUTH_KEY) ?? "null");
if (saved?.token) dispatch({ user: saved.user, token: saved.token });
} catch {}
}, []);
useEffect(() => {
try {
if (state.token) sessionStorage.setItem(AUTH_KEY, JSON.stringify({ user: state.user, token: state.token }));
else sessionStorage.removeItem(AUTH_KEY);
} catch {}
}, [state.user, state.token]);
// 화면 이동을 브라우저 history에 기록 → 스와이프/뒤로가기 버튼/Alt+←가 그대로 앞뒤 이동이 됨
useEffect(() => {
const nav: Nav = { screen: state.screen, list: state.list, postId: state.postId };
const nav: Nav = { screen: state.screen, list: state.list, board: state.board, postId: state.postId };
if (!mounted.current) {
mounted.current = true;
history.replaceState({ bbs: nav }, ""); // 새로고침 시 이전 기록 대신 현재 화면으로 시작
} else if (JSON.stringify(history.state?.bbs) !== JSON.stringify(nav)) {
history.pushState({ bbs: nav }, "");
}
}, [state.screen, state.list, state.postId]);
}, [state.screen, state.list, state.board, state.postId]);
// 메인(새 글)·목록 화면에 들어오거나 "L"을 누르면 서버에서 목록을 다시 불러옴
// 메인(새 글)·목록 화면에 들어오거나, 게시판 탭을 바꾸거나, "L"을 누르면 서버에서 목록을 다시 불러옴
const feedKind: ListKind | null = state.screen === "main" ? "board" : state.screen === "list" ? state.list : null;
const feedBoard = state.screen === "main" ? null : state.board; // 메인의 "새 글"은 항상 전체
useEffect(() => {
if (!feedKind || !state.token) return;
let stale = false; // 응답 전에 화면이 바뀌면 늦게 온 응답은 버림
fetchFeed(state.token, feedKind)
fetchFeed(state.token, feedKind, feedBoard)
.then((feed) => !stale && dispatch({ feed }))
.catch((e) => !stale && dispatch(apiError(e)));
return () => {
stale = true;
};
}, [feedKind, state.token, state.rev]);
}, [feedKind, feedBoard, state.token, state.rev]);
// 게시판 탭 목록: 로그인하면 한 번 받아옴
useEffect(() => {
if (!state.token) return;
fetchBoards(state.token)
.then((boards) => dispatch({ boards }))
.catch((e) => dispatch(apiError(e)));
}, [state.token]);
useEffect(() => {
const onPop = (e: PopStateEvent) => {
if (e.state?.bbs) dispatch(e.state.bbs);
if (!e.state?.bbs) return;
// Next.js는 자기가 만들지 않은 기록(__NA 표시 없음)으로 돌아오면 페이지를 통째로 새로고침함 → 메인으로 튕김
// 우리 기록이면 Next.js의 popstate 처리를 막음 (capture 단계라 Next.js 리스너보다 먼저 실행)
e.stopImmediatePropagation();
dispatch(e.state.bbs);
};
addEventListener("popstate", onPop);
return () => removeEventListener("popstate", onPop);
addEventListener("popstate", onPop, { capture: true });
return () => removeEventListener("popstate", onPop, { capture: true });
}, []);
// F4: 블루 → 그린 → 앰버 순서로 돌아가며 변경
@@ -129,7 +163,37 @@ export default function BbsTerminal() {
<span className={styles.opt}>{clock}</span>
</div>
<div className={styles.screen}>
{/* 모바일 제스처: 오른쪽으로 밀기 = 뒤로, 왼쪽으로 밀기 = 앞으로, 맨 위에서 아래로 당기기 = 새로고침 */}
<div
className={styles.screen}
onTouchStart={(e) => {
const t = e.touches[0];
// 화면 가장자리는 브라우저 기본 스와이프(iOS 사파리)에 양보 → 한 번에 두 칸 이동하는 것 방지
const edge = t.clientX < EDGE || t.clientX > innerWidth - EDGE;
touch.current = edge ? null : { x: t.clientX, y: t.clientY, top: e.currentTarget.scrollTop <= 0 };
}}
onTouchMove={(e) => {
const s = touch.current;
if (!s?.top) return;
const dy = e.touches[0].clientY - s.y;
setPulling(dy > PULL && Math.abs(e.touches[0].clientX - s.x) < dy / 2);
}}
onTouchEnd={(e) => {
const s = touch.current;
touch.current = null;
setPulling(false);
if (!s) return;
const dx = e.changedTouches[0].clientX - s.x;
const dy = e.changedTouches[0].clientY - s.y;
if (Math.abs(dx) > SWIPE && Math.abs(dx) > Math.abs(dy) * 2) {
if (dx < 0) history.forward();
else if (state.screen !== "main") history.back(); // 메인에서 뒤로 가면 사이트를 벗어나므로 막음 (F3과 같음)
} else if (s.top && dy > PULL && Math.abs(dx) < dy / 2) {
dispatch({ rev: state.rev + 1 }); // "L"과 같음: 목록 다시 불러오기
}
}}
>
{pulling && <div className={styles.pull}>↓ 놓으면 새로고침</div>}
<div className={styles.grid}>
{state.screen === "main" && (
<MainMenu
@@ -138,7 +202,7 @@ export default function BbsTerminal() {
onSelect={submitFromClick}
onOpenPost={(num) => {
// 메인에서 숫자는 메뉴 번호라서, 게시판으로 옮긴 뒤 글 번호를 실행
dispatch({ screen: "list", list: "board" });
dispatch({ screen: "list", list: "board", board: null });
dispatch(String(num));
}}
/>
@@ -147,7 +211,14 @@ export default function BbsTerminal() {
<LoginForm onSuccess={(user, token) => dispatch({ screen: "main", user, token })} />
)}
{state.screen === "list" && (
<PostList kind={state.list} feed={state.feed} loggedIn={!!state.user} onSelect={submitFromClick} />
<PostList
kind={state.list}
board={state.board}
boards={state.boards}
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} />
+1 -1
View File
@@ -24,7 +24,7 @@ const LOGO = '';
// |___/ \___/ \___/ |_|_\ \___||___|`;
export default function MainMenu({ feed, loggedIn, onSelect, onOpenPost }: Props) {
const board = feed?.kind === "board" ? feed : null; // 메인에서는 스크랩 게시판(안 읽은 글)을 불러옴
const board = feed?.kind === "board" && !feed.board ? feed : null; // 메인에서는 스크랩 게시판 전체(안 읽은 글)를 불러옴
return (
<>
+39 -13
View File
@@ -1,39 +1,48 @@
import type { Feed, ListKind, ScrapedPost } from "../types";
import type { Board, Feed, ListKind, ScrapedPost } from "../types";
import styles from "./bbs.module.css";
interface Props {
kind: ListKind;
board: string | null;
boards: Board[];
feed: Feed | null;
loggedIn: boolean;
onSelect: (cmd: string) => void;
}
/** 번호 / 게시판 / 글쓴이 / 날짜 / 조회 / 제목 표 (메인의 "새 글" 창에서도 사용). 번호 = 목록 순서 */
// 연.월.일이 들어 있는 부분 (2026-11-25 14:32:10, 2026.11.24, 26.11.24, 2026-11-25T14:32 ...)
const YMD = /(\d{2,4})[.\-/](\d{1,2})[.\-/](\d{1,2})/;
/** 사이트마다 다른 날짜 표기 → YYYYMMDD. 오늘 글처럼 시각(14:32)만 있으면 스크랩한 날짜로 대신 */
function toYmd(postedAt: string | null, scrapedAt: string) {
const m = postedAt?.match(YMD) ?? scrapedAt.match(YMD);
if (!m) return "";
const year = m[1].length === 2 ? `20${m[1]}` : m[1];
return year + m[2].padStart(2, "0") + m[3].padStart(2, "0");
}
/** 번호 / 게시판 / 제목 / 날짜 표 (메인의 "새 글" 창에서도 사용). 번호 = 목록 순서 */
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>
<th>게시판</th>
<th>제목</th>
<th>날짜</th>
</tr>
</thead>
<tbody>
{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.postedAt}</td>
<td className={`${styles.idx} ${styles.wide}`}>{p.viewCount}</td>
<td className={styles.accent}>{p.boardName}</td>
<td className={`${styles.title} ${dim ? styles.dim : ""}`}>
{p.title}
{p.imageUrls.length > 0 && <span className={styles.accent}> [그림{p.imageUrls.length}]</span>}
</td>
<td>{toYmd(p.postedAt, p.scrapedAt)}</td>
</tr>
))}
</tbody>
@@ -41,16 +50,33 @@ export function PostTable({ posts, dim, onSelect }: { posts: ScrapedPost[]; dim?
);
}
export default function PostList({ kind, feed, loggedIn, onSelect }: Props) {
export default function PostList({ kind, board, boards, feed, loggedIn, onSelect }: Props) {
const viewed = kind === "viewed";
const ready = feed?.kind === kind ? feed : null;
const ready = feed?.kind === kind && feed.board === board ? feed : null;
const tabs = [{ boardKey: null, boardName: "전체" }, ...boards]; // 탭 순서 = B0, B1, B2 ...
const current = boards.find((b) => b.boardKey === board);
return (
<section className={`${styles.win} ${styles.full}`}>
<span className={styles.cap}>
═ [{viewed ? 3 : 2}] {viewed ? "내가 읽은 글" : "스크랩 게시판"}
{current && ` - ${current.boardName}`}
{ready && ` (${ready.total}건)`} ═
</span>
{loggedIn && boards.length > 0 && (
<nav className={styles.tabs} aria-label="게시판">
{tabs.map((t, i) => (
<button
key={t.boardKey ?? "all"}
type="button"
aria-pressed={t.boardKey === board}
onClick={() => onSelect(`B${i}`)}
>
<span className={styles.num}>B{i}</span> {t.boardName}
</button>
))}
</nav>
)}
{!loggedIn ? (
<div className={styles.dim}>로그인이 필요합니다. (F5 또는 메인에서 7)</div>
) : !ready ? (
@@ -61,7 +87,7 @@ export default function PostList({ kind, feed, loggedIn, onSelect }: Props) {
<PostTable posts={ready.posts} dim={viewed} onSelect={(n) => onSelect(String(n))} />
)}
<div className={styles.footer}>
<b>번호</b>=글읽기 · <b>M</b>=메인 · <b>L</b>=새로고침
<b>번호</b>=글읽기 · <b>B번호</b>=게시판 · <b>M</b>=메인 · <b>L</b>=새로고침
</div>
</section>
);
+9 -2
View File
@@ -36,7 +36,9 @@
}
/* 본문: 이중선 창들을 배치하는 격자 */
.screen { overflow-y: auto; min-height: 0; padding: 1.4em 16px; }
/* overscroll-behavior: 브라우저 기본 당겨서 새로고침(페이지 전체 리로드) 대신 앱의 목록 새로고침만 동작 */
.screen { overflow-y: auto; min-height: 0; padding: 1.4em 16px; overscroll-behavior-y: contain; }
.pull { text-align: center; color: var(--bbs-highlight); font-weight: 700; margin-bottom: 0.6em; }
.grid {
display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: 1.6em 2ch;
max-width: 120ch; margin: 0 auto;
@@ -77,6 +79,12 @@
.tbl tbody tr { cursor: pointer; }
.tbl tbody tr:hover td { background: var(--bbs-sel); color: var(--bbs-bar-fg); }
/* 게시판 탭: 고른 탭은 반전 막대 */
.tabs { display: flex; flex-wrap: wrap; gap: 0.2em 1.5ch; margin-bottom: 0.6em; }
.tabs button { background: none; border: none; color: var(--bbs-fg); font: inherit; padding: 0 0.5ch; cursor: pointer; }
.tabs button:hover, .tabs button[aria-pressed="true"],
.tabs button:hover *, .tabs button[aria-pressed="true"] * { background: var(--bbs-sel); color: var(--bbs-bar-fg); }
/* 글 읽기 */
.postHead span { color: var(--bbs-accent); }
.body { white-space: pre-wrap; color: var(--bbs-hi); }
@@ -130,7 +138,6 @@
.grid { grid-template-columns: minmax(0, 1fr); }
.opt { display: none; }
.logo { font-size: 3.4vw; }
.tbl .wide { display: none; } /* 글쓴이·조회 숨김 */
.tbl .title { max-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fkeys button { flex-direction: column; align-items: center; gap: 0; padding: 0.4em 0; font-size: 13px; border-top: 1px solid var(--bbs-dim); }
}
+2 -1
View File
@@ -7,10 +7,11 @@ export const MENU: MenuItem[] = [
{ num: 4, key: "youtube", label: "유튜브 자료실", en: "YOUTUBE", aliases: ["유튜브", "youtube"] },
{ num: 5, key: "about", label: "회사 소개", en: "ABOUT", aliases: ["소개", "회사소개", "about"] },
{ num: 6, key: "contact", label: "문의하기", en: "CONTACT", aliases: ["문의", "contact"] },
{ num: 7, key: "login", label: "로그인", en: "LOGIN", aliases: ["l", "로그인", "로그아웃", "login", "logout"] },
{ num: 7, key: "login", label: "로그인", en: "LOGIN", aliases: ["로그인", "로그아웃", "login", "logout"] },
];
export const PALETTE_KEY = "bbs-palette";
export const AUTH_KEY = "bbs-auth";
export const PALETTES: { key: Palette; label: string }[] = [
{ key: "blue", label: "블루" },
+13 -2
View File
@@ -5,6 +5,8 @@ import type { BbsState, MenuItem, Nav } from "../types";
export const initialState: BbsState = {
screen: "main",
list: "board",
board: null,
boards: [],
postId: null,
user: null,
token: null,
@@ -39,9 +41,10 @@ export function execute(prev: BbsState, input: string | Nav | Partial<BbsState>)
const isList = cmd === "l" || cmd === "목록";
if (state.screen === "main") {
if (isList) return { ...state, screen: "list" }; // 다른 화면과 똑같이 L = 목록
const m = findMenu(raw);
if (!m) return { ...state, error: `※ 알 수 없는 메뉴입니다: "${raw}"` };
if (m.key === "board" || m.key === "viewed") return { ...state, screen: "list", list: m.key };
if (m.key === "board" || m.key === "viewed") return { ...state, screen: "list", list: m.key, board: null };
if (m.key === "login") return state.user ? { ...state, ...LOGOUT } : { ...state, screen: "login" };
return { ...state, error: `※ "${m.label}"는 아직 준비 중입니다.` };
}
@@ -53,8 +56,16 @@ export function execute(prev: BbsState, input: string | Nav | Partial<BbsState>)
if (state.screen === "list") {
if (isList) return { ...state, rev: state.rev + 1 };
if (!state.user) return { ...state, error: '※ 로그인이 필요합니다. F5 또는 "M" → 7' };
// B0 = 전체, B1~ = 게시판 탭 순서 (숫자만 입력하면 글 번호라서 B를 붙임)
const tab = /^b(\d+)$/.exec(cmd);
if (tab) {
const n = Number(tab[1]);
if (n > state.boards.length) return { ...state, error: `※ 없는 게시판입니다: "${raw}"` };
return { ...state, board: n === 0 ? null : state.boards[n - 1].boardKey };
}
// 화면의 번호 = 목록 순서(1부터). DB id는 너무 길어서 입력용으로 안 씀
const post = state.feed?.kind === state.list ? state.feed.posts[Number(raw) - 1] : undefined;
const feed = state.feed?.kind === state.list && state.feed.board === state.board ? state.feed : null;
const post = feed?.posts[Number(raw) - 1];
if (!post) return { ...state, error: `※ 목록에 없는 번호입니다: "${raw}"` };
return { ...state, screen: "post", postId: post.id };
}
+13 -3
View File
@@ -30,9 +30,17 @@ export type Palette = "blue" | "green" | "amber";
export type Screen = "main" | "list" | "post" | "login";
export type ListKind = "board" | "viewed";
/** 마지막으로 불러온 목록 (어느 목록인지 같이 기억 → 다른 목록이 잠깐 섞여 보이는 것 방지) */
/** 백엔드 BoardSummaryResponse와 같은 모양 (스크랩 대상 게시판 하나) */
export interface Board {
boardKey: string;
siteName: string;
boardName: string;
}
/** 마지막으로 불러온 목록 (어느 목록·게시판인지 같이 기억 → 다른 목록이 잠깐 섞여 보이는 것 방지) */
export interface Feed {
kind: ListKind;
board: string | null; // boardKey, 전체면 null
posts: ScrapedPost[];
total: number;
}
@@ -40,13 +48,15 @@ export interface Feed {
export interface BbsState {
screen: Screen;
list: ListKind;
board: string | null; // 목록에서 고른 게시판 boardKey, 전체면 null
boards: Board[]; // 게시판 탭 (로그인 뒤 서버에서 받아옴)
postId: number | null;
user: string | null; // 로그인한 아이디, 비로그인이면 null
token: string | null; // JWT (메모리에만 보관 → 새로고침하면 다시 로그인)
token: string | null; // JWT (sessionStorage에도 보관 → 새로고침해도 유지, 탭 닫으면 다시 로그인)
feed: Feed | null;
rev: number; // "L"(새로고침)할 때마다 +1 → 목록 다시 불러오기
error: string | null;
}
/** 브라우저 history에 저장하는 화면 위치 (뒤로/앞으로 제스처로 복원) */
export type Nav = Pick<BbsState, "screen" | "list" | "postId">;
export type Nav = Pick<BbsState, "screen" | "list" | "board" | "postId">;
+4 -1
View File
@@ -114,7 +114,10 @@ FOUC, 인라인 스크립트, render-blocking script, suppressHydrationWarning,
- 이걸로 공짜로 되는 것: iOS 가장자리 스와이프, Android 뒤로 제스처, 맥 트랙패드 스와이프, 마우스 앞/뒤 버튼, Alt+←/→
- 기록하는 것은 **화면 위치만** (`screen`, `list`, `postId`). "읽은 글" 목록은 넣지 않음 → 뒤로 가도 읽음 표시는 유지.
- 같은 화면이면 push 안 함 (중복 기록 방지). 첫 렌더는 `replaceState` (새로고침 시 옛 기록과 꼬이지 않게).
- Next.js는 `pushState`를 감싸서 자기 내부 상태(`__NA`)를 자동으로 함께 저장 → 직접 써도 라우터와 충돌 없음.
- ~~Next.js는 `pushState`를 감싸서 자기 내부 상태(`__NA`)를 자동으로 함께 저장 → 직접 써도 라우터와 충돌 없음.~~
**정정:** 현재 Next.js 버전에서는 `__NA`가 안 붙는 경우가 있음. 그러면 뒤로 갈 때 Next.js가 "모르는 기록"으로 보고
`location.reload()` → 페이지가 처음(메인)부터 다시 시작됨. 해결: 우리 `popstate` 리스너를 `{ capture: true }`로 등록하고
우리 기록(`e.state.bbs`)이면 `e.stopImmediatePropagation()`으로 Next.js 처리를 막음.
### 모바일 대응 (CSS)
- `@media (max-width: 560px)` : 화면 **너비** 기준 (작은 화면 레이아웃)