mirror of
https://github.com/headporter81/ss-front-react.git
synced 2026-12-06 07:41:11 +09:00
SpecialSource Frontend (React) CD / deploy (push) Successful in 14s
- 분류 탭(B0 전체 · B1~ 분류 · 마지막 미분류), 등록 칸은 datalist로 고르거나 새로 입력 - 제목·날짜 범위 검색 + 초기화 - 받는 중이면 2초마다 갱신하며 ▓░ 진행 막대와 속도 표시 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
354 lines
15 KiB
TypeScript
354 lines
15 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useLayoutEffect, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
|
import { AUTH_KEY, PALETTE_KEY, PALETTES } from "../constants";
|
|
import { fetchBoards, fetchFeed, fetchMediaCategories, fetchMediaPosts } 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 MediaDetail from "./MediaDetail";
|
|
import MediaList from "./MediaList";
|
|
import PostDetail from "./PostDetail";
|
|
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) => {
|
|
const handler = () => {
|
|
document.documentElement.dataset.palette = readPalette(); // 색은 CSS가 <html> 속성으로 적용
|
|
onChange(); // F4가 다음 색을 고를 수 있게 React state도 갱신
|
|
};
|
|
window.addEventListener("storage", handler);
|
|
return () => window.removeEventListener("storage", handler);
|
|
};
|
|
|
|
// 상태줄 시계: 1초마다 다시 읽음 (서버 렌더링 땐 자리표시 문자열)
|
|
const subscribeClock = (onChange: () => void) => {
|
|
const t = setInterval(onChange, 1000);
|
|
return () => clearInterval(t);
|
|
};
|
|
const readClock = () => new Date().toTimeString().slice(0, 8);
|
|
|
|
const readPalette = (): Palette => {
|
|
try {
|
|
const saved = localStorage.getItem(PALETTE_KEY);
|
|
return PALETTES.find((p) => p.key === saved)?.key ?? DEFAULT_PALETTE;
|
|
} catch {
|
|
return DEFAULT_PALETTE;
|
|
}
|
|
};
|
|
|
|
export default function BbsTerminal() {
|
|
const [state, dispatch] = useReducer(execute, initialState);
|
|
const palette = useSyncExternalStore(subscribe, readPalette, () => DEFAULT_PALETTE);
|
|
const clock = useSyncExternalStore(subscribeClock, readClock, () => "--:--:--");
|
|
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); // 아래로 충분히 당겼는지 (안내 문구 표시)
|
|
const loadingMore = useRef(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, 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.board, state.postId]);
|
|
|
|
// 메인(새 글)·목록 화면에 들어오거나, 게시판 탭을 바꾸거나, "L"을 누르면 서버에서 목록(첫 페이지)을 다시 불러옴
|
|
// 글 읽기 화면은 보던 목록을 그대로 유지 → 돌아왔을 때 무한 스크롤로 불러온 글과 위치가 남아 있음
|
|
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; // 메인의 "새 글"은 항상 전체
|
|
useEffect(() => {
|
|
if (!feedKind || !state.token) return;
|
|
let stale = false; // 응답 전에 화면이 바뀌면 늦게 온 응답은 버림
|
|
loadingMore.current = false; // 첫 페이지부터 다시 → 무한 스크롤 잠금 해제
|
|
fetchFeed(state.token, feedKind, feedBoard)
|
|
.then((feed) => !stale && dispatch({ feed }))
|
|
.catch((e) => !stale && dispatch(apiError(e)));
|
|
return () => {
|
|
stale = true;
|
|
};
|
|
}, [feedKind, feedBoard, state.token, state.rev]);
|
|
|
|
// 자료실 목록: 들어오거나, 분류 탭·검색 조건을 바꾸거나, "L"을 누르면 다시 불러옴
|
|
// 받는 중인 글이 있으면 2초마다 다시 불러와 진행률 갱신
|
|
const onApiError = useCallback((e: unknown) => dispatch(apiError(e)), []);
|
|
useEffect(() => {
|
|
if (state.screen !== "media" || !state.token) return;
|
|
const token = state.token;
|
|
let stale = false;
|
|
let timer: ReturnType<typeof setTimeout>;
|
|
const load = () =>
|
|
fetchMediaPosts(token, state.mediaQuery)
|
|
.then((media) => {
|
|
if (stale) return;
|
|
dispatch({ media });
|
|
if (media.some((p) => p.status === "DOWNLOADING")) timer = setTimeout(load, 2000);
|
|
})
|
|
.catch((e) => !stale && onApiError(e));
|
|
load();
|
|
return () => {
|
|
stale = true;
|
|
clearTimeout(timer);
|
|
};
|
|
}, [state.screen, state.token, state.rev, state.mediaQuery, onApiError]);
|
|
|
|
// 자료실 분류 탭: 들어오거나 "L"·등록하면 다시 받음 (새 분류로 등록하면 탭이 생김)
|
|
useEffect(() => {
|
|
if (state.screen !== "media" || !state.token) return;
|
|
fetchMediaCategories(state.token)
|
|
.then((mediaCategories) => dispatch({ mediaCategories }))
|
|
.catch(onApiError);
|
|
}, [state.screen, state.token, state.rev, onApiError]);
|
|
|
|
// 오류·안내 메시지가 생기면 팝업으로 띄우고, 다른 경로로 지워지면 닫음
|
|
const dialogRef = useRef<HTMLDialogElement>(null);
|
|
useEffect(() => {
|
|
const d = dialogRef.current;
|
|
if (state.error && !d?.open) d?.showModal();
|
|
else if (!state.error && d?.open) d.close();
|
|
}, [state.error]);
|
|
|
|
// 무한 스크롤: 목록 맨 아래가 보이면 다음 페이지를 불러와 이어 붙임 (붙일지 말지는 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)
|
|
.then((more) => {
|
|
loadingMore.current = false;
|
|
dispatch({ more, after: f });
|
|
})
|
|
.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(() => {
|
|
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) return;
|
|
// Next.js는 자기가 만들지 않은 기록(__NA 표시 없음)으로 돌아오면 페이지를 통째로 새로고침함 → 메인으로 튕김
|
|
// 우리 기록이면 Next.js의 popstate 처리를 막음 (capture 단계라 Next.js 리스너보다 먼저 실행)
|
|
e.stopImmediatePropagation();
|
|
dispatch(e.state.bbs);
|
|
};
|
|
addEventListener("popstate", onPop, { capture: true });
|
|
return () => removeEventListener("popstate", onPop, { capture: true });
|
|
}, []);
|
|
|
|
// F4: 블루 → 그린 → 앰버 순서로 돌아가며 변경
|
|
const cyclePalette = () => {
|
|
const next = PALETTES[(PALETTES.findIndex((p) => p.key === palette) + 1) % PALETTES.length].key;
|
|
try {
|
|
localStorage.setItem(PALETTE_KEY, next);
|
|
} catch {}
|
|
window.dispatchEvent(new StorageEvent("storage")); // 같은 탭은 storage 이벤트가 안 오므로 직접 알림
|
|
};
|
|
|
|
// 하단 기능키 (PC는 키보드 F1~F5도 동작)
|
|
const fkeys = [
|
|
{ key: "F1", label: "메인", run: () => dispatch({ screen: "main" }) },
|
|
{ key: "F2", label: "게시판", run: () => dispatch({ screen: "list", list: "board" }) },
|
|
{ key: "F3", label: "이전", run: () => history.back(), disabled: state.screen === "main" },
|
|
{ key: "F4", label: "색상", run: cyclePalette },
|
|
{
|
|
key: "F5",
|
|
label: state.user ? "로그아웃" : "로그인",
|
|
run: () => dispatch(state.user ? LOGOUT : { screen: "login" }),
|
|
},
|
|
];
|
|
|
|
// 클릭 = 명령어 대리 입력: 입력창에 채운 뒤 엔터와 같은 경로로 실행
|
|
const submitFromClick = (cmd: string) => {
|
|
setInput(cmd);
|
|
// 터치 기기에서 포커스하면 가상 키보드가 튀어나와 화면을 가림 → 마우스 환경에서만
|
|
if (matchMedia("(pointer: fine)").matches) inputRef.current?.focus();
|
|
setTimeout(() => {
|
|
dispatch(cmd);
|
|
setInput("");
|
|
}, 160);
|
|
};
|
|
|
|
return (
|
|
<div
|
|
className={styles.frame}
|
|
onKeyDown={(e) => {
|
|
const f = fkeys.find((k) => k.key === e.key);
|
|
if (!f || f.disabled) return;
|
|
e.preventDefault(); // F5 새로고침 등 브라우저 기본 동작 막기
|
|
f.run();
|
|
}}
|
|
>
|
|
<div className={styles.status}>
|
|
<span>SPECIALSOURCE-BBS</span>
|
|
{/*<span className={styles.opt}></span>*/}
|
|
<span>{state.user ? `${state.user} 접속중` : "손님 (비로그인)"}</span>
|
|
<span className={styles.opt}>{clock}</span>
|
|
</div>
|
|
|
|
{/* 모바일 제스처: 오른쪽으로 밀기 = 뒤로, 왼쪽으로 밀기 = 앞으로, 맨 위에서 아래로 당기기 = 새로고침 */}
|
|
<div
|
|
ref={screenRef}
|
|
className={styles.screen}
|
|
onScroll={(e) => {
|
|
if (state.screen !== "post" && state.screen !== "mediaPost") scrollPos.current[scrollKey] = e.currentTarget.scrollTop;
|
|
}}
|
|
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 feed={state.feed} loggedIn={!!state.user} onSelect={submitFromClick} />
|
|
)}
|
|
{state.screen === "login" && (
|
|
<LoginForm onSuccess={(user, token) => dispatch({ screen: "main", user, token })} />
|
|
)}
|
|
{state.screen === "list" && (
|
|
<PostList
|
|
kind={state.list}
|
|
board={state.board}
|
|
boards={state.boards}
|
|
feed={state.feed}
|
|
loggedIn={!!state.user}
|
|
onSelect={submitFromClick}
|
|
onMore={loadMore}
|
|
/>
|
|
)}
|
|
{state.screen === "post" && state.token && (
|
|
<PostDetail post={state.feed?.posts.find((p) => p.id === state.postId)} token={state.token} />
|
|
)}
|
|
{state.screen === "media" && (
|
|
<MediaList
|
|
posts={state.media}
|
|
categories={state.mediaCategories}
|
|
query={state.mediaQuery}
|
|
token={state.token}
|
|
onSelect={submitFromClick}
|
|
onQuery={(mediaQuery) => dispatch({ media: null, mediaQuery })}
|
|
onCreated={() => dispatch({ rev: state.rev + 1 })}
|
|
onError={onApiError}
|
|
/>
|
|
)}
|
|
{state.screen === "mediaPost" && state.token && state.postId !== null && (
|
|
<MediaDetail
|
|
id={state.postId}
|
|
token={state.token}
|
|
onError={onApiError}
|
|
onDeleted={() => dispatch({ screen: "media", rev: state.rev + 1 })}
|
|
/>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* 알림 팝업: <dialog>.showModal()이 화면 맨 위에 띄우고 뒤를 막음. Esc·확인으로 닫으면 입력창으로 포커스가 돌아감 */}
|
|
<dialog ref={dialogRef} className={styles.dialog} onClose={() => dispatch({ error: null })}>
|
|
<span className={styles.cap}>═ 알림 ═</span>
|
|
<p>{state.error}</p>
|
|
<form method="dialog">
|
|
<button autoFocus>확인</button>
|
|
</form>
|
|
</dialog>
|
|
|
|
<div className={styles.cmdline}>
|
|
<label htmlFor="bbs-cmd" className={styles.prompt}>
|
|
선택 >
|
|
</label>
|
|
<input
|
|
id="bbs-cmd"
|
|
ref={inputRef}
|
|
type="text"
|
|
value={input}
|
|
onChange={(e) => setInput(e.target.value)}
|
|
onKeyDown={(e) => {
|
|
if (e.key !== "Enter" || e.nativeEvent.isComposing) return;
|
|
// 기본 동작을 막아야 이어지는 keypress가 안 생김. 안 막으면 명령 실행으로 뜬 알림 팝업의 [확인]이 같은 Enter로 바로 눌림
|
|
e.preventDefault();
|
|
dispatch(input);
|
|
setInput("");
|
|
}}
|
|
placeholder="번호 또는 메뉴명 (M 메인 · L 목록)"
|
|
autoComplete="off"
|
|
autoFocus
|
|
/>
|
|
</div>
|
|
|
|
<nav className={styles.fkeys} aria-label="기능키">
|
|
{fkeys.map((f) => (
|
|
<button key={f.key} type="button" onClick={f.run} disabled={f.disabled}>
|
|
<span>{f.key}</span>
|
|
{f.label}
|
|
</button>
|
|
))}
|
|
</nav>
|
|
</div>
|
|
);
|
|
}
|