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
+13
-4
@@ -21,14 +21,23 @@ async function call(path: string, token: string, init?: RequestInit) {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ponytail: 자료실은 직접 등록하는 글이라 적음 → 조건에 맞는 최근 100건만. 넘치면 fetchFeed처럼 before 커서로 무한 스크롤
|
/**
|
||||||
export async function fetchMediaPosts(token: string, query: MediaQuery): Promise<MediaPost[]> {
|
* 자료실 목록 한 페이지 (무한 스크롤). before = 이미 받은 마지막 글 id → 그보다 오래된 글 (id 커서라 중복·누락 없음)
|
||||||
const params = new URLSearchParams({ size: "100" });
|
* total: 첫 페이지면 조건에 맞는 전체 건수 (커서 조회의 totalElements = 커서 이후 남은 글 수)
|
||||||
|
*/
|
||||||
|
export async function fetchMediaPosts(
|
||||||
|
token: string,
|
||||||
|
query: MediaQuery,
|
||||||
|
before?: number,
|
||||||
|
): Promise<{ posts: MediaPost[]; total: number; last: boolean }> {
|
||||||
|
const params = new URLSearchParams({ size: String(PAGE_SIZE) });
|
||||||
if (query.category !== null) params.set("category", query.category); // "" = 미분류
|
if (query.category !== null) params.set("category", query.category); // "" = 미분류
|
||||||
if (query.q.trim()) params.set("q", query.q.trim());
|
if (query.q.trim()) params.set("q", query.q.trim());
|
||||||
if (query.from) params.set("from", query.from);
|
if (query.from) params.set("from", query.from);
|
||||||
if (query.to) params.set("to", query.to);
|
if (query.to) params.set("to", query.to);
|
||||||
return (await (await call(`/api/media-posts?${params}`, token)).json()).content;
|
if (before !== undefined) params.set("before", String(before));
|
||||||
|
const data = await (await call(`/api/media-posts?${params}`, token)).json();
|
||||||
|
return { posts: data.content, total: data.totalElements, last: data.totalElements <= PAGE_SIZE };
|
||||||
}
|
}
|
||||||
|
|
||||||
export const fetchMediaCategories = async (token: string): Promise<string[]> =>
|
export const fetchMediaCategories = async (token: string): Promise<string[]> =>
|
||||||
|
|||||||
@@ -99,36 +99,57 @@ export default function BbsTerminal() {
|
|||||||
};
|
};
|
||||||
}, [feedKind, feedBoard, state.token, state.rev]);
|
}, [feedKind, feedBoard, state.token, state.rev]);
|
||||||
|
|
||||||
// 자료실 목록: 들어오거나, 분류 탭·검색 조건을 바꾸거나, "L"을 누르면 다시 불러옴
|
// 자료실 목록(첫 페이지): 자료실에 들어오거나, 분류 탭·검색 조건을 바꾸거나, "L"을 누르면 다시 불러옴
|
||||||
// 받는 중인 글이 있으면 2초마다 다시 불러와 진행률 갱신
|
// 글 보기(mediaPost)에서 돌아올 때는 다시 안 불러옴 → 무한 스크롤로 불러온 글과 스크롤 위치 유지 (스크랩 게시판과 같음)
|
||||||
|
// 받는 중인 글이 있으면 2초마다 첫 페이지만 다시 받아 진행률 갱신
|
||||||
const onApiError = useCallback((e: unknown) => dispatch(apiError(e)), []);
|
const onApiError = useCallback((e: unknown) => dispatch(apiError(e)), []);
|
||||||
|
const inMedia = state.screen === "media" || state.screen === "mediaPost";
|
||||||
|
const loadingMoreMedia = useRef(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (state.screen !== "media" || !state.token) return;
|
if (!inMedia || !state.token) return;
|
||||||
const token = state.token;
|
const token = state.token;
|
||||||
let stale = false;
|
let stale = false;
|
||||||
let timer: ReturnType<typeof setTimeout>;
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
const load = () =>
|
loadingMoreMedia.current = false;
|
||||||
|
const load = (poll: boolean) =>
|
||||||
fetchMediaPosts(token, state.mediaQuery)
|
fetchMediaPosts(token, state.mediaQuery)
|
||||||
.then((media) => {
|
.then(({ posts, total, last }) => {
|
||||||
if (stale) return;
|
if (stale) return;
|
||||||
dispatch({ media });
|
dispatch(poll ? { mediaPoll: posts, total, last } : { media: posts, mediaTotal: total, mediaLast: last });
|
||||||
if (media.some((p) => p.status === "DOWNLOADING")) timer = setTimeout(load, 2000);
|
if (posts.some((p) => p.status === "DOWNLOADING")) timer = setTimeout(() => load(true), 2000);
|
||||||
})
|
})
|
||||||
.catch((e) => !stale && onApiError(e));
|
.catch((e) => !stale && onApiError(e));
|
||||||
load();
|
load(false);
|
||||||
return () => {
|
return () => {
|
||||||
stale = true;
|
stale = true;
|
||||||
clearTimeout(timer);
|
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"·등록하면 다시 받음 (새 분류로 등록하면 탭이 생김)
|
// 자료실 분류 탭: 들어오거나 "L"·등록하면 다시 받음 (새 분류로 등록하면 탭이 생김)
|
||||||
useEffect(() => {
|
const loadMediaCategories = useCallback(
|
||||||
if (state.screen !== "media" || !state.token) return;
|
(token: string) =>
|
||||||
fetchMediaCategories(state.token)
|
fetchMediaCategories(token)
|
||||||
.then((mediaCategories) => dispatch({ mediaCategories }))
|
.then((mediaCategories) => dispatch({ mediaCategories }))
|
||||||
.catch(onApiError);
|
.catch(onApiError),
|
||||||
}, [state.screen, state.token, state.rev, onApiError]);
|
[onApiError],
|
||||||
|
);
|
||||||
|
useEffect(() => {
|
||||||
|
if (inMedia && state.token) loadMediaCategories(state.token);
|
||||||
|
}, [inMedia, state.token, state.rev, loadMediaCategories]);
|
||||||
|
|
||||||
// 오류·안내 메시지가 생기면 팝업으로 띄우고, 다른 경로로 지워지면 닫음
|
// 오류·안내 메시지가 생기면 팝업으로 띄우고, 다른 경로로 지워지면 닫음
|
||||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||||
@@ -288,6 +309,9 @@ export default function BbsTerminal() {
|
|||||||
{state.screen === "media" && (
|
{state.screen === "media" && (
|
||||||
<MediaList
|
<MediaList
|
||||||
posts={state.media}
|
posts={state.media}
|
||||||
|
total={state.mediaTotal}
|
||||||
|
last={state.mediaLast}
|
||||||
|
onMore={loadMoreMedia}
|
||||||
categories={state.mediaCategories}
|
categories={state.mediaCategories}
|
||||||
query={state.mediaQuery}
|
query={state.mediaQuery}
|
||||||
token={state.token}
|
token={state.token}
|
||||||
@@ -303,6 +327,11 @@ export default function BbsTerminal() {
|
|||||||
token={state.token}
|
token={state.token}
|
||||||
categories={state.mediaCategories}
|
categories={state.mediaCategories}
|
||||||
onError={onApiError}
|
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 })}
|
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[]; // 수정 칸 분류 자동완성
|
categories: string[]; // 수정 칸 분류 자동완성
|
||||||
onError: (e: unknown) => void;
|
onError: (e: unknown) => void;
|
||||||
onDeleted: () => 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 [post, setPost] = useState<MediaPost | null>(null);
|
||||||
const [confirming, setConfirming] = useState(false); // [삭제] 한 번 누르면 "정말?" 확인 단계
|
const [confirming, setConfirming] = useState(false); // [삭제] 한 번 누르면 "정말?" 확인 단계
|
||||||
const [editing, setEditing] = useState(false); // [수정] 누르면 제목·분류 입력칸으로 바뀜
|
const [editing, setEditing] = useState(false); // [수정] 누르면 제목·분류 입력칸으로 바뀜
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
// 목록으로 돌아가면 목록·분류 탭을 다시 불러오므로 바뀐 내용이 그대로 반영됨
|
|
||||||
const save = async (e: FormEvent<HTMLFormElement>) => {
|
const save = async (e: FormEvent<HTMLFormElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const data = new FormData(e.currentTarget);
|
const data = new FormData(e.currentTarget);
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
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);
|
setEditing(false);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
onError(err);
|
onError(err);
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
import { useState, type FormEvent } from "react";
|
import { useState, type FormEvent } from "react";
|
||||||
import { createMediaPost } from "../api";
|
import { createMediaPost } from "../api";
|
||||||
import type { MediaPost, MediaQuery } from "../types";
|
import type { MediaPost, MediaQuery } from "../types";
|
||||||
|
import DatePicker from "./DatePicker";
|
||||||
|
import { MoreSentinel } from "./PostList";
|
||||||
import styles from "./bbs.module.css";
|
import styles from "./bbs.module.css";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
posts: MediaPost[] | null;
|
posts: MediaPost[] | null;
|
||||||
|
total: number; // 조건에 맞는 전체 건수
|
||||||
|
last: boolean; // 더 불러올 글이 없음
|
||||||
|
onMore: () => void; // 목록 끝이 보이면 다음 페이지 불러오기 (무한 스크롤)
|
||||||
categories: string[];
|
categories: string[];
|
||||||
query: MediaQuery;
|
query: MediaQuery;
|
||||||
token: string | null;
|
token: string | null;
|
||||||
@@ -24,8 +29,9 @@ export const bar = (percent: number, width = 10) => {
|
|||||||
|
|
||||||
const EMPTY_SEARCH = { q: "", from: "", to: "" };
|
const EMPTY_SEARCH = { q: "", from: "", to: "" };
|
||||||
|
|
||||||
/** [4] 자료실: 분류 탭 / 링크 등록 / 검색 / 목록. 받는 중인 글이 있으면 BbsTerminal이 2초마다 새로고침 */
|
/** [4] 자료실: 분류 탭 / 링크 등록 / 검색 / 목록(무한 스크롤). 받는 중인 글이 있으면 BbsTerminal이 2초마다 진행률 갱신 */
|
||||||
export default function MediaList({ posts, categories, query, token, onSelect, onQuery, onCreated, onError }: Props) {
|
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 [busy, setBusy] = useState(false);
|
||||||
const tabs = [{ key: null, name: "전체" }, ...categories.map((c) => ({ key: c, name: c })), { key: "", name: "미분류" }];
|
const tabs = [{ key: null, name: "전체" }, ...categories.map((c) => ({ key: c, name: c })), { key: "", name: "미분류" }];
|
||||||
const searching = query.q || query.from || query.to;
|
const searching = query.q || query.from || query.to;
|
||||||
@@ -61,7 +67,7 @@ export default function MediaList({ posts, categories, query, token, onSelect, o
|
|||||||
return (
|
return (
|
||||||
<section className={`${styles.win} ${styles.full}`}>
|
<section className={`${styles.win} ${styles.full}`}>
|
||||||
<span className={styles.cap}>
|
<span className={styles.cap}>
|
||||||
═ [4] 자료실{posts && ` (${posts.length}건${searching ? " 검색됨" : ""})`} ═
|
═ [4] 자료실{posts && ` (${total}건${searching ? " 검색됨" : ""})`} ═
|
||||||
</span>
|
</span>
|
||||||
{!token ? (
|
{!token ? (
|
||||||
<div className={styles.dim}>로그인이 필요합니다. (F5 또는 메인에서 7)</div>
|
<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>
|
<span className={styles.num}>검색</span>
|
||||||
<input name="q" defaultValue={query.q} placeholder="제목" />
|
<input name="q" defaultValue={query.q} placeholder="제목" />
|
||||||
</label>
|
</label>
|
||||||
<label>
|
{/* 브라우저 기본 달력 대신 TUI 스타일 달력 팝업 (DatePicker가 hidden input으로 from/to 제출) */}
|
||||||
|
{/* label이 아닌 div: label 안이면 팝업 배경을 눌러 닫을 때 그 클릭이 첫 버튼으로 전달돼 다시 열림 */}
|
||||||
|
<div className={styles.dates}>
|
||||||
<span className={styles.num}>날짜</span>
|
<span className={styles.num}>날짜</span>
|
||||||
<input name="from" type="date" className={styles.date} defaultValue={query.from} aria-label="시작일" />~
|
<DatePicker name="from" defaultValue={query.from} label="시작일" />~
|
||||||
<input name="to" type="date" className={styles.date} defaultValue={query.to} aria-label="종료일" />
|
<DatePicker name="to" defaultValue={query.to} label="종료일" />
|
||||||
</label>
|
</div>
|
||||||
<span>
|
<span>
|
||||||
<button type="submit">검색</button>{" "}
|
<button type="submit">검색</button>{" "}
|
||||||
{searching && (
|
{searching && (
|
||||||
@@ -156,6 +164,7 @@ export default function MediaList({ posts, categories, query, token, onSelect, o
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
|
{posts && posts.length > 0 && <MoreSentinel last={last} onMore={onMore} />}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<div className={styles.footer}>
|
<div className={styles.footer}>
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 목록 맨 아래 표시줄: 화면에 보이면 onMore 호출 (불러온 뒤에도 계속 보이면 화면이 찰 때까지 이어서 호출) */
|
/** 목록 맨 아래 표시줄: 화면에 보이면 onMore 호출 (불러온 뒤에도 계속 보이면 화면이 찰 때까지 이어서 호출) */
|
||||||
function MoreSentinel({ last, onMore }: { last: boolean; onMore: () => void }) {
|
export function MoreSentinel({ last, onMore }: { last: boolean; onMore: () => void }) {
|
||||||
const ref = useRef<HTMLDivElement>(null);
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (last || !ref.current) return;
|
if (last || !ref.current) return;
|
||||||
|
|||||||
@@ -123,8 +123,7 @@
|
|||||||
/* 자료실 검색줄: 한 줄로 흘려 배치 (좁으면 줄바꿈) */
|
/* 자료실 검색줄: 한 줄로 흘려 배치 (좁으면 줄바꿈) */
|
||||||
.searchForm { flex-direction: row; flex-wrap: wrap; align-items: center; gap: 0.3em 2ch; }
|
.searchForm { flex-direction: row; flex-wrap: wrap; align-items: center; gap: 0.3em 2ch; }
|
||||||
.searchForm label { flex: 1 1 24ch; }
|
.searchForm label { flex: 1 1 24ch; }
|
||||||
.searchForm label:has(.date) { flex: 0 1 auto; }
|
.searchForm .dates { display: flex; gap: 1ch; align-items: center; flex: 0 1 auto; }
|
||||||
.loginForm input.date { flex: 0 1 auto; color-scheme: dark; } /* 달력 아이콘을 어두운 배경에 맞게 */
|
|
||||||
.loginForm button {
|
.loginForm button {
|
||||||
align-self: flex-start; background: none; border: 1px solid var(--bbs-accent); color: var(--bbs-accent);
|
align-self: flex-start; background: none; border: 1px solid var(--bbs-accent); color: var(--bbs-accent);
|
||||||
font: inherit; padding: 0 1.5ch; cursor: pointer;
|
font: inherit; padding: 0 1.5ch; cursor: pointer;
|
||||||
@@ -148,6 +147,28 @@
|
|||||||
.dialog button::after { content: " ]"; }
|
.dialog button::after { content: " ]"; }
|
||||||
.dialog button:focus-visible, .dialog button:hover { background: var(--bbs-highlight); outline: none; }
|
.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); }
|
.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; }
|
.prompt { color: var(--bbs-highlight); font-weight: 700; white-space: nowrap; }
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import { AuthError } from "../api";
|
import { AuthError } from "../api";
|
||||||
import { MENU } from "../constants";
|
import { MENU } from "../constants";
|
||||||
import type { BbsState, Feed, MenuItem, Nav } from "../types";
|
import type { BbsState, Feed, MediaPost, MenuItem, Nav } from "../types";
|
||||||
|
|
||||||
|
/** 자료실 페이지 도착: more = 다음 페이지 (after = 요청 당시 목록), poll = 받는 중 글 진행률 갱신용 첫 페이지 */
|
||||||
|
export type MediaPage =
|
||||||
|
| { mediaMore: MediaPost[]; last: boolean; after: MediaPost[] }
|
||||||
|
| { mediaPoll: MediaPost[]; total: number; last: boolean };
|
||||||
|
|
||||||
export const initialState: BbsState = {
|
export const initialState: BbsState = {
|
||||||
screen: "main",
|
screen: "main",
|
||||||
@@ -12,6 +17,8 @@ export const initialState: BbsState = {
|
|||||||
token: null,
|
token: null,
|
||||||
feed: null,
|
feed: null,
|
||||||
media: null,
|
media: null,
|
||||||
|
mediaTotal: 0,
|
||||||
|
mediaLast: true,
|
||||||
mediaQuery: { category: null, q: "", from: "", to: "" },
|
mediaQuery: { category: null, q: "", from: "", to: "" },
|
||||||
mediaCategories: [],
|
mediaCategories: [],
|
||||||
rev: 0,
|
rev: 0,
|
||||||
@@ -36,8 +43,21 @@ function findMenu(raw: string): MenuItem | undefined {
|
|||||||
/** 클릭/키보드 입력이 모두 거치는 단일 명령 처리기 (순수 함수 → useReducer reducer로 사용) */
|
/** 클릭/키보드 입력이 모두 거치는 단일 명령 처리기 (순수 함수 → useReducer reducer로 사용) */
|
||||||
export function execute(
|
export function execute(
|
||||||
prev: BbsState,
|
prev: BbsState,
|
||||||
input: string | Nav | Partial<BbsState> | { more: Feed; after: Feed },
|
input: string | Nav | Partial<BbsState> | { more: Feed; after: Feed } | MediaPage,
|
||||||
): BbsState {
|
): BbsState {
|
||||||
|
if (typeof input !== "string" && "mediaMore" in input) {
|
||||||
|
// 요청할 때의 목록이 지금도 그대로일 때만 이어 붙임 (그 사이 탭·검색을 바꿨으면 버림)
|
||||||
|
if (prev.media !== input.after) return prev;
|
||||||
|
return { ...prev, media: [...prev.media, ...input.mediaMore], mediaLast: input.last };
|
||||||
|
}
|
||||||
|
if (typeof input !== "string" && "mediaPoll" in input) {
|
||||||
|
// 진행률 갱신: 첫 페이지는 새로 받은 것으로, 무한 스크롤로 더 불러온 아래쪽 글은 그대로 유지
|
||||||
|
// (받는 중인 글은 방금 등록한 최신 글이라 항상 첫 페이지 안에 있음)
|
||||||
|
const fresh = input.mediaPoll;
|
||||||
|
const oldest = fresh.at(-1)?.id ?? 0;
|
||||||
|
const rest = (prev.media ?? []).filter((p) => p.id < oldest);
|
||||||
|
return { ...prev, media: [...fresh, ...rest], mediaTotal: input.total, mediaLast: rest.length ? prev.mediaLast : input.last };
|
||||||
|
}
|
||||||
if (typeof input !== "string" && "more" in input) {
|
if (typeof input !== "string" && "more" in input) {
|
||||||
// 무한 스크롤 다음 페이지: 요청할 때의 목록이 지금도 그대로일 때만 이어 붙임 (그 사이 탭을 바꿨거나 새로고침했으면 버림)
|
// 무한 스크롤 다음 페이지: 요청할 때의 목록이 지금도 그대로일 때만 이어 붙임 (그 사이 탭을 바꿨거나 새로고침했으면 버림)
|
||||||
const { more, after } = input;
|
const { more, after } = input;
|
||||||
|
|||||||
@@ -99,7 +99,9 @@ export interface BbsState {
|
|||||||
user: string | null; // 로그인한 아이디, 비로그인이면 null
|
user: string | null; // 로그인한 아이디, 비로그인이면 null
|
||||||
token: string | null; // JWT (sessionStorage에도 보관 → 새로고침해도 유지, 탭 닫으면 다시 로그인)
|
token: string | null; // JWT (sessionStorage에도 보관 → 새로고침해도 유지, 탭 닫으면 다시 로그인)
|
||||||
feed: Feed | null;
|
feed: Feed | null;
|
||||||
media: MediaPost[] | null; // 자료실 목록
|
media: MediaPost[] | null; // 자료실 목록 (무한 스크롤로 불러온 모든 페이지)
|
||||||
|
mediaTotal: number; // 조건에 맞는 전체 건수 (첫 페이지 기준)
|
||||||
|
mediaLast: boolean; // 더 불러올 글이 없음
|
||||||
mediaQuery: MediaQuery; // 자료실 분류 탭·검색 조건
|
mediaQuery: MediaQuery; // 자료실 분류 탭·검색 조건
|
||||||
mediaCategories: string[]; // 자료실 분류 탭 (글에 쓰인 분류, 이름순)
|
mediaCategories: string[]; // 자료실 분류 탭 (글에 쓰인 분류, 이름순)
|
||||||
rev: number; // "L"(새로고침)할 때마다 +1 → 목록 다시 불러오기
|
rev: number; // "L"(새로고침)할 때마다 +1 → 목록 다시 불러오기
|
||||||
|
|||||||
Reference in new issue
Block a user