mirror of
https://github.com/headporter81/ss-front-react.git
synced 2026-12-06 07:41:11 +09:00
- 목록을 30건씩 id 커서로 이어 불러옴 (MoreSentinel 재사용), 글 보기에서 돌아와도 불러온 글·스크롤 유지 - 받는 중 진행률 갱신은 첫 페이지만 다시 받아 합침 (아래쪽 불러온 글 유지) - 날짜 검색: 브라우저 기본 달력 대신 <dialog> 레이어 달력 (방향키·PageUp/Down·Enter·Esc, 오늘/지우기) - 글 수정 시 목록에도 바로 반영 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d359c35304
commit
60ab3e9ff6
9 files changed
+283
-34
No files matched your search
@@ -99,36 +99,57 @@ export default function BbsTerminal() {
|
||||
};
|
||||
}, [feedKind, feedBoard, state.token, state.rev]);
|
||||
|
||||
// 자료실 목록: 들어오거나, 분류 탭·검색 조건을 바꾸거나, "L"을 누르면 다시 불러옴
|
||||
// 받는 중인 글이 있으면 2초마다 다시 불러와 진행률 갱신
|
||||
// 자료실 목록(첫 페이지): 자료실에 들어오거나, 분류 탭·검색 조건을 바꾸거나, "L"을 누르면 다시 불러옴
|
||||
// 글 보기(mediaPost)에서 돌아올 때는 다시 안 불러옴 → 무한 스크롤로 불러온 글과 스크롤 위치 유지 (스크랩 게시판과 같음)
|
||||
// 받는 중인 글이 있으면 2초마다 첫 페이지만 다시 받아 진행률 갱신
|
||||
const onApiError = useCallback((e: unknown) => dispatch(apiError(e)), []);
|
||||
const inMedia = state.screen === "media" || state.screen === "mediaPost";
|
||||
const loadingMoreMedia = useRef(false);
|
||||
useEffect(() => {
|
||||
if (state.screen !== "media" || !state.token) return;
|
||||
if (!inMedia || !state.token) return;
|
||||
const token = state.token;
|
||||
let stale = false;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const load = () =>
|
||||
loadingMoreMedia.current = false;
|
||||
const load = (poll: boolean) =>
|
||||
fetchMediaPosts(token, state.mediaQuery)
|
||||
.then((media) => {
|
||||
.then(({ posts, total, last }) => {
|
||||
if (stale) return;
|
||||
dispatch({ media });
|
||||
if (media.some((p) => p.status === "DOWNLOADING")) timer = setTimeout(load, 2000);
|
||||
dispatch(poll ? { mediaPoll: posts, total, last } : { media: posts, mediaTotal: total, mediaLast: last });
|
||||
if (posts.some((p) => p.status === "DOWNLOADING")) timer = setTimeout(() => load(true), 2000);
|
||||
})
|
||||
.catch((e) => !stale && onApiError(e));
|
||||
load();
|
||||
load(false);
|
||||
return () => {
|
||||
stale = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [state.screen, state.token, state.rev, state.mediaQuery, onApiError]);
|
||||
}, [inMedia, state.token, state.rev, state.mediaQuery, onApiError]);
|
||||
|
||||
// 무한 스크롤: 목록 맨 아래가 보이면 다음 페이지 (붙일지 말지는 execute가 판단)
|
||||
const loadMoreMedia = () => {
|
||||
const after = state.media;
|
||||
if (!state.token || !after || state.mediaLast || loadingMoreMedia.current) return;
|
||||
loadingMoreMedia.current = true;
|
||||
fetchMediaPosts(state.token, state.mediaQuery, after.at(-1)?.id)
|
||||
.then(({ posts, last }) => {
|
||||
loadingMoreMedia.current = false;
|
||||
dispatch({ mediaMore: posts, last, after });
|
||||
})
|
||||
.catch(onApiError); // 실패하면 잠금 유지 → 무한 재시도 방지. "L"이면 풀림
|
||||
};
|
||||
|
||||
// 자료실 분류 탭: 들어오거나 "L"·등록하면 다시 받음 (새 분류로 등록하면 탭이 생김)
|
||||
const loadMediaCategories = useCallback(
|
||||
(token: string) =>
|
||||
fetchMediaCategories(token)
|
||||
.then((mediaCategories) => dispatch({ mediaCategories }))
|
||||
.catch(onApiError),
|
||||
[onApiError],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (state.screen !== "media" || !state.token) return;
|
||||
fetchMediaCategories(state.token)
|
||||
.then((mediaCategories) => dispatch({ mediaCategories }))
|
||||
.catch(onApiError);
|
||||
}, [state.screen, state.token, state.rev, onApiError]);
|
||||
if (inMedia && state.token) loadMediaCategories(state.token);
|
||||
}, [inMedia, state.token, state.rev, loadMediaCategories]);
|
||||
|
||||
// 오류·안내 메시지가 생기면 팝업으로 띄우고, 다른 경로로 지워지면 닫음
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
@@ -288,6 +309,9 @@ export default function BbsTerminal() {
|
||||
{state.screen === "media" && (
|
||||
<MediaList
|
||||
posts={state.media}
|
||||
total={state.mediaTotal}
|
||||
last={state.mediaLast}
|
||||
onMore={loadMoreMedia}
|
||||
categories={state.mediaCategories}
|
||||
query={state.mediaQuery}
|
||||
token={state.token}
|
||||
@@ -303,6 +327,11 @@ export default function BbsTerminal() {
|
||||
token={state.token}
|
||||
categories={state.mediaCategories}
|
||||
onError={onApiError}
|
||||
// 목록을 다시 안 불러오므로(스크롤 유지) 바뀐 글만 목록에 반영, 새 분류일 수 있으니 탭은 다시 받음
|
||||
onEdited={(u) => {
|
||||
dispatch({ media: state.media?.map((p) => (p.id === u.id ? { ...u, files: [] } : p)) ?? null });
|
||||
if (state.token) loadMediaCategories(state.token);
|
||||
}}
|
||||
onDeleted={() => dispatch({ screen: "media", rev: state.rev + 1 })}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
|
||||
import styles from "./bbs.module.css";
|
||||
|
||||
const WEEK = ["일", "월", "화", "수", "목", "금", "토"];
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const fmt = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
const parse = (s: string) => {
|
||||
const [y, m, d] = s.split("-").map(Number);
|
||||
return new Date(y, m - 1, d);
|
||||
};
|
||||
const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
|
||||
// 한 달 이동: 31일 → 다음 달에 31일이 없으면 그 달 마지막 날로
|
||||
const addMonths = (d: Date, n: number) => {
|
||||
const last = new Date(d.getFullYear(), d.getMonth() + n + 1, 0).getDate();
|
||||
return new Date(d.getFullYear(), d.getMonth() + n, Math.min(d.getDate(), last));
|
||||
};
|
||||
|
||||
interface Props {
|
||||
name: string; // 폼 제출 시 이 이름의 hidden input으로 yyyy-MM-dd (비우면 "")
|
||||
defaultValue: string;
|
||||
label: string; // 팝업 제목·버튼 이름 (예: 시작일)
|
||||
}
|
||||
|
||||
/**
|
||||
* TUI 스타일 달력 팝업. 버튼을 누르면 <dialog>.showModal()로 화면 위에 레이어로 뜸 (알림 팝업과 같은 이중선 창)
|
||||
* 키보드: ←→ 하루, ↑↓ 일주일, PageUp/PageDown 한 달, Home 오늘, Enter 선택, Esc 닫기
|
||||
*/
|
||||
export default function DatePicker({ name, defaultValue, label }: Props) {
|
||||
const [value, setValue] = useState(defaultValue);
|
||||
const [cursor, setCursor] = useState(() => (defaultValue ? parse(defaultValue) : new Date())); // 커서가 있는 날
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
|
||||
// 커서가 움직이면 그 날짜 버튼으로 포커스 → 방향키를 계속 누를 수 있고, 화면 읽기 프로그램도 따라감
|
||||
useEffect(() => {
|
||||
if (dialogRef.current?.open) dialogRef.current.querySelector<HTMLButtonElement>("[data-cursor]")?.focus();
|
||||
}, [cursor]);
|
||||
|
||||
const open = () => {
|
||||
setCursor(value ? parse(value) : new Date());
|
||||
dialogRef.current?.showModal();
|
||||
// 열린 직후에는 위 effect가 이미 지나갔을 수 있어 한 번 더
|
||||
requestAnimationFrame(() => dialogRef.current?.querySelector<HTMLButtonElement>("[data-cursor]")?.focus());
|
||||
};
|
||||
const close = () => dialogRef.current?.close();
|
||||
const pick = (v: string) => {
|
||||
setValue(v);
|
||||
close();
|
||||
};
|
||||
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
const move: Record<string, () => Date> = {
|
||||
ArrowLeft: () => addDays(cursor, -1),
|
||||
ArrowRight: () => addDays(cursor, 1),
|
||||
ArrowUp: () => addDays(cursor, -7),
|
||||
ArrowDown: () => addDays(cursor, 7),
|
||||
PageUp: () => addMonths(cursor, -1),
|
||||
PageDown: () => addMonths(cursor, 1),
|
||||
Home: () => new Date(),
|
||||
};
|
||||
if (move[e.key]) {
|
||||
e.preventDefault();
|
||||
setCursor(move[e.key]());
|
||||
} else if (e.key === "Enter" && (e.target as HTMLElement).dataset.day) {
|
||||
e.preventDefault(); // 바깥 검색 폼이 제출되지 않게
|
||||
pick(fmt(cursor));
|
||||
}
|
||||
};
|
||||
|
||||
// 달력 칸: 그 달 1일의 요일만큼 빈칸 + 1일~말일, 7칸씩 끊어 주(週)로
|
||||
const year = cursor.getFullYear();
|
||||
const month = cursor.getMonth();
|
||||
const days = new Date(year, month + 1, 0).getDate();
|
||||
const cells: (number | null)[] = [...Array(new Date(year, month, 1).getDay()).fill(null), ...Array.from({ length: days }, (_, i) => i + 1)];
|
||||
while (cells.length % 7) cells.push(null);
|
||||
const weeks = Array.from({ length: cells.length / 7 }, (_, w) => cells.slice(w * 7, w * 7 + 7));
|
||||
const today = fmt(new Date());
|
||||
|
||||
return (
|
||||
<>
|
||||
<input type="hidden" name={name} value={value} />
|
||||
<button type="button" className={styles.dateBtn} onClick={open} aria-label={`${label} 고르기`} aria-haspopup="dialog">
|
||||
{value || "연도-월-일"} ▾
|
||||
</button>
|
||||
|
||||
{/* 바깥(어두운 배경)을 누르면 닫힘: 배경 클릭은 dialog 자신이 target */}
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
className={`${styles.dialog} ${styles.calendar}`}
|
||||
aria-label={label}
|
||||
onKeyDown={onKey}
|
||||
onClick={(e) => e.target === e.currentTarget && close()}
|
||||
>
|
||||
<span className={styles.cap}>═ {label} ═</span>
|
||||
<div className={styles.calHead}>
|
||||
<button type="button" onClick={() => setCursor(addMonths(cursor, -1))} aria-label="이전 달">
|
||||
◄
|
||||
</button>
|
||||
<span>
|
||||
{year}년 {pad(month + 1)}월
|
||||
</span>
|
||||
<button type="button" onClick={() => setCursor(addMonths(cursor, 1))} aria-label="다음 달">
|
||||
►
|
||||
</button>
|
||||
</div>
|
||||
<table className={styles.calGrid}>
|
||||
<thead>
|
||||
<tr>
|
||||
{WEEK.map((w, i) => (
|
||||
<th key={w} className={i === 0 ? styles.sun : i === 6 ? styles.sat : undefined}>
|
||||
{w}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{weeks.map((week, w) => (
|
||||
<tr key={w}>
|
||||
{week.map((d, i) => {
|
||||
if (d === null) return <td key={i} />;
|
||||
const v = fmt(new Date(year, month, d));
|
||||
const isCursor = d === cursor.getDate();
|
||||
return (
|
||||
<td key={i}>
|
||||
<button
|
||||
type="button"
|
||||
data-day={d}
|
||||
data-cursor={isCursor || undefined}
|
||||
tabIndex={isCursor ? 0 : -1} // Tab은 커서 날짜 하나만 → 날짜 사이 이동은 방향키
|
||||
aria-pressed={v === value}
|
||||
aria-current={v === today ? "date" : undefined}
|
||||
className={i === 0 ? styles.sun : i === 6 ? styles.sat : undefined}
|
||||
onClick={() => pick(v)}
|
||||
>
|
||||
{pad(d)}
|
||||
</button>
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<div className={styles.calFoot}>
|
||||
<button type="button" onClick={() => pick(today)}>
|
||||
오늘
|
||||
</button>
|
||||
<button type="button" onClick={() => pick("")}>
|
||||
지우기
|
||||
</button>
|
||||
<button type="button" onClick={close}>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
</dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -23,21 +23,23 @@ interface Props {
|
||||
categories: string[]; // 수정 칸 분류 자동완성
|
||||
onError: (e: unknown) => void;
|
||||
onDeleted: () => void; // 삭제 성공 → 목록으로
|
||||
onEdited: (post: MediaPost) => void; // 수정 성공 → 목록에도 반영
|
||||
}
|
||||
|
||||
export default function MediaDetail({ id, token, categories, onError, onDeleted }: Props) {
|
||||
export default function MediaDetail({ id, token, categories, onError, onDeleted, onEdited }: Props) {
|
||||
const [post, setPost] = useState<MediaPost | null>(null);
|
||||
const [confirming, setConfirming] = useState(false); // [삭제] 한 번 누르면 "정말?" 확인 단계
|
||||
const [editing, setEditing] = useState(false); // [수정] 누르면 제목·분류 입력칸으로 바뀜
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
// 목록으로 돌아가면 목록·분류 탭을 다시 불러오므로 바뀐 내용이 그대로 반영됨
|
||||
const save = async (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const data = new FormData(e.currentTarget);
|
||||
setBusy(true);
|
||||
try {
|
||||
setPost(await updateMediaPost(token, id, String(data.get("title")).trim(), String(data.get("category")).trim()));
|
||||
const updated = await updateMediaPost(token, id, String(data.get("title")).trim(), String(data.get("category")).trim());
|
||||
setPost(updated);
|
||||
onEdited(updated);
|
||||
setEditing(false);
|
||||
} catch (err) {
|
||||
onError(err);
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { createMediaPost } from "../api";
|
||||
import type { MediaPost, MediaQuery } from "../types";
|
||||
import DatePicker from "./DatePicker";
|
||||
import { MoreSentinel } from "./PostList";
|
||||
import styles from "./bbs.module.css";
|
||||
|
||||
interface Props {
|
||||
posts: MediaPost[] | null;
|
||||
total: number; // 조건에 맞는 전체 건수
|
||||
last: boolean; // 더 불러올 글이 없음
|
||||
onMore: () => void; // 목록 끝이 보이면 다음 페이지 불러오기 (무한 스크롤)
|
||||
categories: string[];
|
||||
query: MediaQuery;
|
||||
token: string | null;
|
||||
@@ -24,8 +29,9 @@ export const bar = (percent: number, width = 10) => {
|
||||
|
||||
const EMPTY_SEARCH = { q: "", from: "", to: "" };
|
||||
|
||||
/** [4] 자료실: 분류 탭 / 링크 등록 / 검색 / 목록. 받는 중인 글이 있으면 BbsTerminal이 2초마다 새로고침 */
|
||||
export default function MediaList({ posts, categories, query, token, onSelect, onQuery, onCreated, onError }: Props) {
|
||||
/** [4] 자료실: 분류 탭 / 링크 등록 / 검색 / 목록(무한 스크롤). 받는 중인 글이 있으면 BbsTerminal이 2초마다 진행률 갱신 */
|
||||
export default function MediaList(props: Props) {
|
||||
const { posts, total, last, onMore, categories, query, token, onSelect, onQuery, onCreated, onError } = props;
|
||||
const [busy, setBusy] = useState(false);
|
||||
const tabs = [{ key: null, name: "전체" }, ...categories.map((c) => ({ key: c, name: c })), { key: "", name: "미분류" }];
|
||||
const searching = query.q || query.from || query.to;
|
||||
@@ -61,7 +67,7 @@ export default function MediaList({ posts, categories, query, token, onSelect, o
|
||||
return (
|
||||
<section className={`${styles.win} ${styles.full}`}>
|
||||
<span className={styles.cap}>
|
||||
═ [4] 자료실{posts && ` (${posts.length}건${searching ? " 검색됨" : ""})`} ═
|
||||
═ [4] 자료실{posts && ` (${total}건${searching ? " 검색됨" : ""})`} ═
|
||||
</span>
|
||||
{!token ? (
|
||||
<div className={styles.dim}>로그인이 필요합니다. (F5 또는 메인에서 7)</div>
|
||||
@@ -107,11 +113,13 @@ export default function MediaList({ posts, categories, query, token, onSelect, o
|
||||
<span className={styles.num}>검색</span>
|
||||
<input name="q" defaultValue={query.q} placeholder="제목" />
|
||||
</label>
|
||||
<label>
|
||||
{/* 브라우저 기본 달력 대신 TUI 스타일 달력 팝업 (DatePicker가 hidden input으로 from/to 제출) */}
|
||||
{/* label이 아닌 div: label 안이면 팝업 배경을 눌러 닫을 때 그 클릭이 첫 버튼으로 전달돼 다시 열림 */}
|
||||
<div className={styles.dates}>
|
||||
<span className={styles.num}>날짜</span>
|
||||
<input name="from" type="date" className={styles.date} defaultValue={query.from} aria-label="시작일" />~
|
||||
<input name="to" type="date" className={styles.date} defaultValue={query.to} aria-label="종료일" />
|
||||
</label>
|
||||
<DatePicker name="from" defaultValue={query.from} label="시작일" />~
|
||||
<DatePicker name="to" defaultValue={query.to} label="종료일" />
|
||||
</div>
|
||||
<span>
|
||||
<button type="submit">검색</button>{" "}
|
||||
{searching && (
|
||||
@@ -156,6 +164,7 @@ export default function MediaList({ posts, categories, query, token, onSelect, o
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{posts && posts.length > 0 && <MoreSentinel last={last} onMore={onMore} />}
|
||||
</>
|
||||
)}
|
||||
<div className={styles.footer}>
|
||||
|
||||
@@ -13,7 +13,7 @@ interface Props {
|
||||
}
|
||||
|
||||
/** 목록 맨 아래 표시줄: 화면에 보이면 onMore 호출 (불러온 뒤에도 계속 보이면 화면이 찰 때까지 이어서 호출) */
|
||||
function MoreSentinel({ last, onMore }: { last: boolean; onMore: () => void }) {
|
||||
export function MoreSentinel({ last, onMore }: { last: boolean; onMore: () => void }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (last || !ref.current) return;
|
||||
|
||||
@@ -123,8 +123,7 @@
|
||||
/* 자료실 검색줄: 한 줄로 흘려 배치 (좁으면 줄바꿈) */
|
||||
.searchForm { flex-direction: row; flex-wrap: wrap; align-items: center; gap: 0.3em 2ch; }
|
||||
.searchForm label { flex: 1 1 24ch; }
|
||||
.searchForm label:has(.date) { flex: 0 1 auto; }
|
||||
.loginForm input.date { flex: 0 1 auto; color-scheme: dark; } /* 달력 아이콘을 어두운 배경에 맞게 */
|
||||
.searchForm .dates { display: flex; gap: 1ch; align-items: center; flex: 0 1 auto; }
|
||||
.loginForm button {
|
||||
align-self: flex-start; background: none; border: 1px solid var(--bbs-accent); color: var(--bbs-accent);
|
||||
font: inherit; padding: 0 1.5ch; cursor: pointer;
|
||||
@@ -148,6 +147,28 @@
|
||||
.dialog button::after { content: " ]"; }
|
||||
.dialog button:focus-visible, .dialog button:hover { background: var(--bbs-highlight); outline: none; }
|
||||
|
||||
/* 달력 팝업 (DatePicker): 알림 팝업(.dialog)과 같은 창, 날짜·화살표 버튼은 [ ] 장식 없이 글자처럼 */
|
||||
.dateBtn {
|
||||
background: none; border: none; border-bottom: 1px solid var(--bbs-dim); color: var(--bbs-hi);
|
||||
font: inherit; padding: 0 0.5ch; cursor: pointer; white-space: nowrap;
|
||||
}
|
||||
.dateBtn:hover { border-bottom-color: var(--bbs-accent); }
|
||||
.calendar { max-width: none; padding-bottom: 0.7em; }
|
||||
.calHead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.3em; color: var(--bbs-highlight); font-weight: 700; }
|
||||
.calendar .calHead button, .calendar .calGrid button { background: none; color: var(--bbs-hi); font-weight: normal; padding: 0 0.6ch; }
|
||||
.calendar .calHead button::before, .calendar .calHead button::after,
|
||||
.calendar .calGrid button::before, .calendar .calGrid button::after { content: none; }
|
||||
.calGrid { border-collapse: collapse; margin: 0 auto; font-variant-numeric: tabular-nums; }
|
||||
.calGrid th { color: var(--bbs-accent); font-weight: 700; padding: 0 0.6ch; border-bottom: 1px dashed var(--bbs-dim); }
|
||||
.calGrid td { text-align: center; padding: 0.1em 0; }
|
||||
.calGrid .sun { color: #ff6b6b; }
|
||||
.calGrid .sat { color: var(--bbs-accent); }
|
||||
.calendar .calGrid button[aria-current="date"] { color: var(--bbs-highlight); text-decoration: underline; } /* 오늘 */
|
||||
.calendar .calGrid button[aria-pressed="true"] { background: var(--bbs-bar); color: var(--bbs-bar-fg); } /* 고른 날 */
|
||||
.calendar .calGrid button:hover, .calendar .calGrid button:focus-visible,
|
||||
.calendar .calHead button:hover, .calendar .calHead button:focus-visible { background: var(--bbs-sel); color: var(--bbs-bar-fg); outline: none; }
|
||||
.calFoot { display: flex; justify-content: center; gap: 2ch; margin-top: 0.6em; }
|
||||
|
||||
/* 명령줄 */
|
||||
.cmdline { display: flex; align-items: center; gap: 1ch; padding: 0.3em 16px; border-top: 1px solid var(--bbs-dim); }
|
||||
.prompt { color: var(--bbs-highlight); font-weight: 700; white-space: nowrap; }
|
||||
|
||||
Reference in new issue
Block a user