mirror of
https://github.com/headporter81/ss-front-react.git
synced 2026-12-06 07:41:11 +09:00
feat : BBS 게시판 탭·모바일 제스처 추가, 로그인 유지 및 뒤로가기 새로고침 버그 수정
SpecialSource Frontend (React) CD / deploy (push) Successful in 15s
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:
1 parent
523b90be15
commit
8914954c55
9 files changed
+173
-40
No files matched your search
@@ -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} />
|
||||
|
||||
@@ -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 (
|
||||
<>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user