Files
ss-front-react/src/features/bbs/components/MediaList.tsx
T
headporterandClaude Opus 5.5 9a8ee17075
SpecialSource Frontend (React) CD / deploy (push) Successful in 17s
feat : 업로드 조각 3개 동시 전송, 조각 진행(n/전체) 표시, 실패 시 조각 번호·원인 표시
https가 아닌 주소에서도 동작하도록 업로드 id 생성 대체 구현.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:26:33 +09:00

193 lines
8.7 KiB
TypeScript

import { useState, type FormEvent } from "react";
import { createMediaPost, uploadMediaFiles, type UploadProgress } 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;
onSelect: (cmd: string) => void;
onQuery: (query: MediaQuery) => void; // 검색 조건 바꾸기 (분류 탭은 onSelect("B번호"))
onCreated: () => void; // 등록 성공 → 목록·분류 다시 불러오기
onError: (e: unknown) => void;
}
export const STATUS: Record<MediaPost["status"], string> = { DOWNLOADING: "받는중", DONE: "완료", FAILED: "실패" };
/** 텍스트 진행 막대: 45% → "▓▓▓▓░░░░░░ 45%" */
export const bar = (percent: number, width = 10) => {
const filled = Math.round((percent / 100) * width);
return `${"▓".repeat(filled)}${"░".repeat(width - filled)} ${percent}%`;
};
const EMPTY_SEARCH = { q: "", from: "", to: "" };
/** [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 [uploaded, setUploaded] = useState<UploadProgress | null>(null); // 업로드 중이면 진행 상황
const tabs = [{ key: null, name: "전체" }, ...categories.map((c) => ({ key: c, name: c })), { key: "", name: "미분류" }];
const searching = query.q || query.from || query.to;
const submit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!token) return;
const form = e.currentTarget;
const data = new FormData(form);
const url = String(data.get("url")).trim();
const title = String(data.get("title")).trim();
const category = String(data.get("category")).trim();
// 빈 파일 칸도 FormData에는 이름 없는 File로 들어옴 → 이름 있는 것만
const files = data.getAll("files").filter((f): f is File => f instanceof File && f.name !== "");
if (!url && files.length === 0) {
onError(new Error("※ 링크를 넣거나 파일을 고르세요."));
return;
}
setBusy(true);
try {
// 파일을 골랐으면 업로드, 아니면 링크 다운로드
if (files.length > 0) await uploadMediaFiles(token, files, title, category, setUploaded);
else await createMediaPost(token, url, title, category);
form.reset();
onCreated();
} catch (err) {
onError(err);
} finally {
setBusy(false);
setUploaded(null);
}
};
const search = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const data = new FormData(e.currentTarget);
onQuery({ ...query, q: String(data.get("q")), from: String(data.get("from")), to: String(data.get("to")) });
};
return (
<section className={`${styles.win} ${styles.full}`}>
<span className={styles.cap}>
═ [4] 자료실{posts && ` (${total}건${searching ? " 검색됨" : ""})`} ═
</span>
{!token ? (
<div className={styles.dim}>로그인이 필요합니다. (F5 또는 메인에서 7)</div>
) : (
<>
<nav className={styles.tabs} aria-label="분류">
{tabs.map((t, i) => (
<button key={t.key ?? "all"} type="button" aria-pressed={t.key === query.category} onClick={() => onSelect(`B${i}`)}>
<span className={styles.num}>B{i}</span> {t.name}
</button>
))}
</nav>
{/* key: 분류 탭을 바꾸면 폼을 새로 그려 분류 칸 기본값을 그 탭으로 */}
<form key={query.category ?? "all"} className={styles.loginForm} onSubmit={submit}>
<label>
<span className={styles.num}>링크</span>
<input name="url" type="url" className={styles.wide} placeholder="유튜브·인스타 주소" />
</label>
<label>
<span className={styles.num}>파일</span>
{/* 고르면 링크 대신 내 PC 파일을 업로드 (여러 개 가능) */}
<input name="files" type="file" multiple />
</label>
<label>
<span className={styles.num}>분류</span>
{/* datalist: 기존 분류에서 고르거나 새 이름을 그대로 입력 (비우면 미분류) */}
<input name="category" list="media-categories" defaultValue={query.category ?? ""} placeholder="고르거나 새로 입력" maxLength={50} />
<datalist id="media-categories">
{categories.map((c) => (
<option key={c} value={c} />
))}
</datalist>
</label>
<label>
<span className={styles.num}>제목</span>
<input name="title" className={styles.wide} placeholder="비우면 영상·파일 제목으로" maxLength={500} />
</label>
<button type="submit" disabled={busy}>
{uploaded !== null
? `업로드 ${bar(uploaded.percent, 10)} · 조각 ${uploaded.done}/${uploaded.total}`
: busy
? "요청중..."
: "등록"}
</button>
</form>
<hr className={styles.rule} />
{/* key: 초기화하면 입력칸도 비워지도록 조건이 바뀔 때마다 새로 그림 */}
<form key={`${query.q}|${query.from}|${query.to}`} className={`${styles.loginForm} ${styles.searchForm}`} onSubmit={search}>
<label>
<span className={styles.num}>검색</span>
<input name="q" defaultValue={query.q} placeholder="제목" />
</label>
{/* 브라우저 기본 달력 대신 TUI 스타일 달력 팝업 (DatePicker가 hidden input으로 from/to 제출) */}
{/* label이 아닌 div: label 안이면 팝업 배경을 눌러 닫을 때 그 클릭이 첫 버튼으로 전달돼 다시 열림 */}
<div className={styles.dates}>
<span className={styles.num}>날짜</span>
<DatePicker name="from" defaultValue={query.from} label="시작일" />~
<DatePicker name="to" defaultValue={query.to} label="종료일" />
</div>
<span>
<button type="submit">검색</button>{" "}
{searching && (
<button type="button" onClick={() => onQuery({ ...query, ...EMPTY_SEARCH })}>
초기화
</button>
)}
</span>
</form>
<hr className={styles.rule} />
{!posts ? (
<div className={styles.dim}>불러오는 중...</div>
) : posts.length === 0 ? (
<div className={styles.dim}>{searching ? "검색 결과가 없습니다." : "등록된 자료가 없습니다."}</div>
) : (
<table className={styles.tbl}>
<thead>
<tr>
<th className={styles.idx}>번호</th>
<th>상태</th>
<th>분류</th>
<th>제목</th>
<th>날짜</th>
</tr>
</thead>
<tbody>
{posts.map((p, i) => (
<tr key={p.id} onClick={() => onSelect(String(i + 1))}>
<td className={styles.idx}>{i + 1}</td>
<td className={p.status === "FAILED" ? styles.error : styles.accent}>
{p.status === "DOWNLOADING" && p.progress !== null ? bar(p.progress, 5) : STATUS[p.status]}
</td>
<td className={styles.accent}>{p.category ?? "미분류"}</td>
<td className={styles.title}>
{p.title}
{p.status === "DOWNLOADING" && p.speed && <span className={styles.dim}> ({p.speed})</span>}
</td>
<td>{p.createdAt.slice(0, 10).replaceAll("-", "")}</td>
</tr>
))}
</tbody>
</table>
)}
{posts && posts.length > 0 && <MoreSentinel last={last} onMore={onMore} />}
</>
)}
<div className={styles.footer}>
<b>번호</b>=보기 · <b>B번호</b>=분류 · <b>M</b>=메인 · <b>L</b>=새로고침
</div>
</section>
);
}