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 12s
SpecialSource Frontend (React) CD / deploy (push) Successful in 12s
- 목록 끝이 보이면 다음 페이지(30건)를 불러와 이어 붙임 (IntersectionObserver) - 글 읽기에서 돌아오면 불러온 목록과 스크롤 위치를 그대로 유지 - 다음 페이지 중복 요청·실패 시 무한 재시도 방지 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
94d7bd3409
commit
d94aaa6f0a
5 files changed
+71
-12
No files matched your search
@@ -14,12 +14,15 @@ async function call(path: string, token: string, init?: RequestInit) {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: 첫 페이지 30건만 가져옴. 페이지 넘김이 필요해지면 page 파라미터 추가
|
const PAGE_SIZE = 30;
|
||||||
export async function fetchFeed(token: string, kind: ListKind, board: string | null): Promise<Feed> {
|
|
||||||
|
/** 목록 한 페이지 (page는 0부터). 무한 스크롤은 page+1을 불러와 이어 붙임 */
|
||||||
|
export async function fetchFeed(token: string, kind: ListKind, board: string | null, page = 0): Promise<Feed> {
|
||||||
const filter = board ? `&board=${encodeURIComponent(board)}` : "";
|
const filter = board ? `&board=${encodeURIComponent(board)}` : "";
|
||||||
const res = await call(`/api/scraped-posts${kind === "viewed" ? "/viewed" : ""}?size=30${filter}`, token);
|
const path = `/api/scraped-posts${kind === "viewed" ? "/viewed" : ""}?size=${PAGE_SIZE}&page=${page}${filter}`;
|
||||||
const data = await res.json(); // Spring Page 응답: { content: [...], totalElements, ... }
|
const data = await (await call(path, token)).json(); // Spring Page 응답: { content: [...], totalElements, ... }
|
||||||
return { kind, board, posts: data.content, total: data.totalElements };
|
const last = (page + 1) * PAGE_SIZE >= data.totalElements;
|
||||||
|
return { kind, board, posts: data.content, total: data.totalElements, page, last };
|
||||||
}
|
}
|
||||||
|
|
||||||
export const fetchBoards = async (token: string): Promise<Board[]> =>
|
export const fetchBoards = async (token: string): Promise<Board[]> =>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
import { useEffect, useLayoutEffect, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
||||||
import { AUTH_KEY, PALETTE_KEY, PALETTES } from "../constants";
|
import { AUTH_KEY, PALETTE_KEY, PALETTES } from "../constants";
|
||||||
import { fetchBoards, fetchFeed } from "../api";
|
import { fetchBoards, fetchFeed } from "../api";
|
||||||
import { apiError, execute, initialState, LOGOUT } from "../lib/command";
|
import { apiError, execute, initialState, LOGOUT } from "../lib/command";
|
||||||
@@ -52,6 +52,7 @@ export default function BbsTerminal() {
|
|||||||
const mounted = useRef(false);
|
const mounted = useRef(false);
|
||||||
const touch = useRef<{ x: number; y: number; top: boolean } | null>(null); // 손가락을 댄 위치
|
const touch = useRef<{ x: number; y: number; top: boolean } | null>(null); // 손가락을 댄 위치
|
||||||
const [pulling, setPulling] = useState(false); // 아래로 충분히 당겼는지 (안내 문구 표시)
|
const [pulling, setPulling] = useState(false); // 아래로 충분히 당겼는지 (안내 문구 표시)
|
||||||
|
const loadingMore = useRef(false); // 무한 스크롤 다음 페이지를 불러오는 중 (중복 요청 방지)
|
||||||
|
|
||||||
// 새로고침해도 로그인 유지: 탭이 열려 있는 동안만 sessionStorage에 보관 (탭 닫으면 사라짐)
|
// 새로고침해도 로그인 유지: 탭이 열려 있는 동안만 sessionStorage에 보관 (탭 닫으면 사라짐)
|
||||||
// 서버 렌더링 결과와 어긋나지 않도록 첫 렌더링 뒤(useEffect)에 복원. 아래 저장 effect보다 먼저 읽어야 함
|
// 서버 렌더링 결과와 어긋나지 않도록 첫 렌더링 뒤(useEffect)에 복원. 아래 저장 effect보다 먼저 읽어야 함
|
||||||
@@ -79,12 +80,15 @@ export default function BbsTerminal() {
|
|||||||
}
|
}
|
||||||
}, [state.screen, state.list, state.board, 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 feedKind: ListKind | null =
|
||||||
|
state.screen === "main" ? "board" : state.screen === "list" || state.screen === "post" ? state.list : null;
|
||||||
const feedBoard = state.screen === "main" ? null : state.board; // 메인의 "새 글"은 항상 전체
|
const feedBoard = state.screen === "main" ? null : state.board; // 메인의 "새 글"은 항상 전체
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!feedKind || !state.token) return;
|
if (!feedKind || !state.token) return;
|
||||||
let stale = false; // 응답 전에 화면이 바뀌면 늦게 온 응답은 버림
|
let stale = false; // 응답 전에 화면이 바뀌면 늦게 온 응답은 버림
|
||||||
|
loadingMore.current = false; // 첫 페이지부터 다시 → 무한 스크롤 잠금 해제
|
||||||
fetchFeed(state.token, feedKind, feedBoard)
|
fetchFeed(state.token, feedKind, feedBoard)
|
||||||
.then((feed) => !stale && dispatch({ feed }))
|
.then((feed) => !stale && dispatch({ feed }))
|
||||||
.catch((e) => !stale && dispatch(apiError(e)));
|
.catch((e) => !stale && dispatch(apiError(e)));
|
||||||
@@ -93,6 +97,27 @@ export default function BbsTerminal() {
|
|||||||
};
|
};
|
||||||
}, [feedKind, feedBoard, state.token, state.rev]);
|
}, [feedKind, feedBoard, state.token, state.rev]);
|
||||||
|
|
||||||
|
// 무한 스크롤: 목록 맨 아래가 보이면 다음 페이지를 불러와 이어 붙임 (붙일지 말지는 execute가 판단)
|
||||||
|
const loadMore = () => {
|
||||||
|
const f = state.feed;
|
||||||
|
if (!state.token || !f || f.last || loadingMore.current) return;
|
||||||
|
loadingMore.current = true;
|
||||||
|
fetchFeed(state.token, f.kind, f.board, f.page + 1)
|
||||||
|
.then((more) => {
|
||||||
|
loadingMore.current = false;
|
||||||
|
dispatch({ more });
|
||||||
|
})
|
||||||
|
.catch((e) => dispatch(apiError(e))); // 실패하면 잠금을 풀지 않음 → 무한 재시도 방지. "L"(새로고침)하면 풀림
|
||||||
|
};
|
||||||
|
|
||||||
|
// 화면별 스크롤 위치 기억: 글을 읽고 돌아오면 보던 위치로, 글 읽기는 항상 맨 위부터
|
||||||
|
const screenRef = useRef<HTMLDivElement>(null);
|
||||||
|
const scrollPos = useRef<Record<string, number>>({});
|
||||||
|
const scrollKey = state.screen === "list" ? `list:${state.list}:${state.board}` : state.screen;
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (screenRef.current) screenRef.current.scrollTop = scrollPos.current[scrollKey] ?? 0;
|
||||||
|
}, [scrollKey, state.postId]);
|
||||||
|
|
||||||
// 게시판 탭 목록: 로그인하면 한 번 받아옴
|
// 게시판 탭 목록: 로그인하면 한 번 받아옴
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!state.token) return;
|
if (!state.token) return;
|
||||||
@@ -165,7 +190,11 @@ export default function BbsTerminal() {
|
|||||||
|
|
||||||
{/* 모바일 제스처: 오른쪽으로 밀기 = 뒤로, 왼쪽으로 밀기 = 앞으로, 맨 위에서 아래로 당기기 = 새로고침 */}
|
{/* 모바일 제스처: 오른쪽으로 밀기 = 뒤로, 왼쪽으로 밀기 = 앞으로, 맨 위에서 아래로 당기기 = 새로고침 */}
|
||||||
<div
|
<div
|
||||||
|
ref={screenRef}
|
||||||
className={styles.screen}
|
className={styles.screen}
|
||||||
|
onScroll={(e) => {
|
||||||
|
if (state.screen !== "post") scrollPos.current[scrollKey] = e.currentTarget.scrollTop;
|
||||||
|
}}
|
||||||
onTouchStart={(e) => {
|
onTouchStart={(e) => {
|
||||||
const t = e.touches[0];
|
const t = e.touches[0];
|
||||||
// 화면 가장자리는 브라우저 기본 스와이프(iOS 사파리)에 양보 → 한 번에 두 칸 이동하는 것 방지
|
// 화면 가장자리는 브라우저 기본 스와이프(iOS 사파리)에 양보 → 한 번에 두 칸 이동하는 것 방지
|
||||||
@@ -218,6 +247,7 @@ export default function BbsTerminal() {
|
|||||||
feed={state.feed}
|
feed={state.feed}
|
||||||
loggedIn={!!state.user}
|
loggedIn={!!state.user}
|
||||||
onSelect={submitFromClick}
|
onSelect={submitFromClick}
|
||||||
|
onMore={loadMore}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{state.screen === "post" && state.token && (
|
{state.screen === "post" && state.token && (
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { useEffect, useRef } from "react";
|
||||||
import type { Board, Feed, ListKind, ScrapedPost } from "../types";
|
import type { Board, Feed, ListKind, ScrapedPost } from "../types";
|
||||||
import styles from "./bbs.module.css";
|
import styles from "./bbs.module.css";
|
||||||
|
|
||||||
@@ -8,6 +9,19 @@ interface Props {
|
|||||||
feed: Feed | null;
|
feed: Feed | null;
|
||||||
loggedIn: boolean;
|
loggedIn: boolean;
|
||||||
onSelect: (cmd: string) => void;
|
onSelect: (cmd: string) => void;
|
||||||
|
onMore: () => void; // 목록 끝이 보이면 다음 페이지 불러오기
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 목록 맨 아래 표시줄: 화면에 보이면 onMore 호출 (불러온 뒤에도 계속 보이면 화면이 찰 때까지 이어서 호출) */
|
||||||
|
function MoreSentinel({ last, onMore }: { last: boolean; onMore: () => void }) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (last || !ref.current) return;
|
||||||
|
const io = new IntersectionObserver(([e]) => e.isIntersecting && onMore());
|
||||||
|
io.observe(ref.current);
|
||||||
|
return () => io.disconnect();
|
||||||
|
}, [last, onMore]);
|
||||||
|
return <div ref={ref} className={styles.dim}>{last ? "── 마지막 글입니다 ──" : "불러오는 중..."}</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 연.월.일이 들어 있는 부분 (2026-11-25 14:32:10, 2026.11.24, 26.11.24, 2026-11-25T14:32 ...)
|
// 연.월.일이 들어 있는 부분 (2026-11-25 14:32:10, 2026.11.24, 26.11.24, 2026-11-25T14:32 ...)
|
||||||
@@ -50,7 +64,7 @@ export function PostTable({ posts, dim, onSelect }: { posts: ScrapedPost[]; dim?
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PostList({ kind, board, boards, feed, loggedIn, onSelect }: Props) {
|
export default function PostList({ kind, board, boards, feed, loggedIn, onSelect, onMore }: Props) {
|
||||||
const viewed = kind === "viewed";
|
const viewed = kind === "viewed";
|
||||||
const ready = feed?.kind === kind && feed.board === board ? feed : null;
|
const ready = feed?.kind === kind && feed.board === board ? feed : null;
|
||||||
const tabs = [{ boardKey: null, boardName: "전체" }, ...boards]; // 탭 순서 = B0, B1, B2 ...
|
const tabs = [{ boardKey: null, boardName: "전체" }, ...boards]; // 탭 순서 = B0, B1, B2 ...
|
||||||
@@ -84,7 +98,10 @@ export default function PostList({ kind, board, boards, feed, loggedIn, onSelect
|
|||||||
) : ready.posts.length === 0 ? (
|
) : ready.posts.length === 0 ? (
|
||||||
<div className={styles.dim}>표시할 글이 없습니다.</div>
|
<div className={styles.dim}>표시할 글이 없습니다.</div>
|
||||||
) : (
|
) : (
|
||||||
|
<>
|
||||||
<PostTable posts={ready.posts} dim={viewed} onSelect={(n) => onSelect(String(n))} />
|
<PostTable posts={ready.posts} dim={viewed} onSelect={(n) => onSelect(String(n))} />
|
||||||
|
<MoreSentinel last={ready.last} onMore={onMore} />
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
<div className={styles.footer}>
|
<div className={styles.footer}>
|
||||||
<b>번호</b>=글읽기 · <b>B번호</b>=게시판 · <b>M</b>=메인 · <b>L</b>=새로고침
|
<b>번호</b>=글읽기 · <b>B번호</b>=게시판 · <b>M</b>=메인 · <b>L</b>=새로고침
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { AuthError } from "../api";
|
import { AuthError } from "../api";
|
||||||
import { MENU } from "../constants";
|
import { MENU } from "../constants";
|
||||||
import type { BbsState, MenuItem, Nav } from "../types";
|
import type { BbsState, Feed, MenuItem, Nav } from "../types";
|
||||||
|
|
||||||
export const initialState: BbsState = {
|
export const initialState: BbsState = {
|
||||||
screen: "main",
|
screen: "main",
|
||||||
@@ -31,7 +31,14 @@ function findMenu(raw: string): MenuItem | undefined {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 클릭/키보드 입력이 모두 거치는 단일 명령 처리기 (순수 함수 → useReducer reducer로 사용) */
|
/** 클릭/키보드 입력이 모두 거치는 단일 명령 처리기 (순수 함수 → useReducer reducer로 사용) */
|
||||||
export function execute(prev: BbsState, input: string | Nav | Partial<BbsState>): BbsState {
|
export function execute(prev: BbsState, input: string | Nav | Partial<BbsState> | { more: Feed }): BbsState {
|
||||||
|
if (typeof input !== "string" && "more" in input) {
|
||||||
|
// 무한 스크롤 다음 페이지: 지금 목록의 바로 다음 페이지일 때만 이어 붙임 (그 사이 탭을 바꿨거나 새로고침했으면 버림)
|
||||||
|
const { more } = input;
|
||||||
|
const f = prev.feed;
|
||||||
|
if (!f || f.kind !== more.kind || f.board !== more.board || more.page !== f.page + 1) return prev;
|
||||||
|
return { ...prev, feed: { ...more, posts: [...f.posts, ...more.posts] } };
|
||||||
|
}
|
||||||
if (typeof input !== "string") return { ...prev, error: null, ...input }; // 화면 복원, 로그인, 목록 도착, 오류
|
if (typeof input !== "string") return { ...prev, error: null, ...input }; // 화면 복원, 로그인, 목록 도착, 오류
|
||||||
const raw = input.trim();
|
const raw = input.trim();
|
||||||
if (!raw) return prev;
|
if (!raw) return prev;
|
||||||
|
|||||||
@@ -41,8 +41,10 @@ export interface Board {
|
|||||||
export interface Feed {
|
export interface Feed {
|
||||||
kind: ListKind;
|
kind: ListKind;
|
||||||
board: string | null; // boardKey, 전체면 null
|
board: string | null; // boardKey, 전체면 null
|
||||||
posts: ScrapedPost[];
|
posts: ScrapedPost[]; // 지금까지 불러온 모든 페이지의 글 (무한 스크롤로 이어 붙임)
|
||||||
total: number;
|
total: number;
|
||||||
|
page: number; // 마지막으로 불러온 페이지 (0부터)
|
||||||
|
last: boolean; // 더 불러올 페이지가 없음
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BbsState {
|
export interface BbsState {
|
||||||
|
|||||||
Reference in new issue
Block a user