import { useQueryClient } from "@tanstack/react-query"; import { EventType } from "@umt/contracts"; import { ArrowDownAZ, ArrowUpAZ, ClipboardCopy, Copy, Eye, EyeOff, FileStack, FolderInput, FolderOpen, FolderPlus, FolderTree, Library, PenLine, RotateCw, ScanSearch, Search, SearchX, ServerCrash, Sparkles, Trash2, Wand2, X, } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Link, useNavigate, useSearchParams } from "react-router"; import { toast } from "sonner"; import { useSession } from "~/api/auth.ts"; import { type FileEntry, type FileRef, filesErrorText, filesKeys, filesMockEnabled, isRootOffline, type ListQuery, refKey, useFileList, useFileRoots, useProbe, } from "~/api/files.ts"; import { EmptyState, ErrorState, LoadingState } from "~/components/console/empty-state.tsx"; import { PageHeader } from "~/components/console/page-header.tsx"; import { StatusBadge } from "~/components/console/status-badge.tsx"; import { ContextMenu, type MenuAnchor, type MenuItem } from "~/components/files/context-menu.tsx"; import { CopyPathDialog, DeleteDialog, MkdirDialog, RenameDialog, ScrapeDialog, TransferDialog, } from "~/components/files/dialogs.tsx"; import { DirTree } from "~/components/files/dir-tree.tsx"; import { FileDetail } from "~/components/files/file-detail.tsx"; import { DRAG_MIME, FileList } from "~/components/files/file-list.tsx"; import { emptySelection, FILTER_CHIPS, opDisabledReason, parentRel, pruneSelection, type Selection, SORT_OPTIONS, totalSize, } from "~/components/files/model.ts"; import { OrganizeWizard } from "~/components/files/organize-wizard.tsx"; import { PathBreadcrumb } from "~/components/files/path-breadcrumb.tsx"; import { Button, buttonVariants } from "~/components/ui/button.tsx"; import { Input } from "~/components/ui/input.tsx"; import { Sheet, SheetContent, SheetHeader, SheetTitle } from "~/components/ui/sheet.tsx"; import { relTime } from "~/components/workbench/release-fields.ts"; import { useSse } from "~/lib/sse.ts"; import { cn, formatBytes } from "~/lib/utils.ts"; const HEALTH_REASON: Record = { root_missing: "挂载点不存在", sentinel_missing: "根目录里找不到哨兵文件,可能挂载未生效", timeout: "探测超时", permission_denied: "没有读取权限", }; const healthReasonText = (r: string | null) => (r ? (HEALTH_REASON[r] ?? r) : "挂载点没有响应"); type Dialog = | { kind: "rename"; entry: FileEntry } | { kind: "transfer"; items: FileRef[]; mode: "move" | "copy"; target?: FileRef | null } | { kind: "delete"; items: FileRef[] } | { kind: "mkdir" } | { kind: "copyPath"; entry: FileEntry } | { kind: "scrape"; entry: FileEntry } | { kind: "wizard"; entries: FileEntry[] }; const TREE_W_KEY = "umt-files-tree-w"; const FILES_CHANGED = "files.changed"; function useIsMobile() { const [m, setM] = useState(false); useEffect(() => { const mq = window.matchMedia("(max-width: 767px)"); const on = () => setM(mq.matches); on(); mq.addEventListener("change", on); return () => mq.removeEventListener("change", on); }, []); return m; } function useTreeWidth() { const [w, setW] = useState(260); useEffect(() => { try { const v = Number(localStorage.getItem(TREE_W_KEY)); if (v >= 200 && v <= 440) setW(v); } catch { // 存储不可用时用默认宽度 } }, []); const save = (v: number) => { const c = Math.max(200, Math.min(440, Math.round(v))); setW(c); try { localStorage.setItem(TREE_W_KEY, String(c)); } catch { // 忽略 } }; return [w, save] as const; } export default function FilesPage() { const [params, setParams] = useSearchParams(); const navigate = useNavigate(); const qc = useQueryClient(); const session = useSession(); const isAdmin = session.data?.actor?.type === "admin"; const mobile = useIsMobile(); const [treeW, setTreeW] = useTreeWidth(); const roots = useFileRoots(); const rootList = roots.data ?? []; const rootId = params.get("root") ?? ""; const path = params.get("path") ?? ""; const sort = (params.get("sort") ?? "name") as ListQuery["sort"]; const order = (params.get("order") ?? "asc") as "asc" | "desc"; const filter = params.get("f") ?? ""; const hidden = params.get("hidden") === "1"; const selParam = params.get("sel"); const [qInput, setQInput] = useState(params.get("q") ?? ""); const q = params.get("q") ?? ""; const root = rootList.find((r) => r.id === rootId); const patch = useCallback( (p: Record, replace = false) => setParams( (prev) => { const next = new URLSearchParams(prev); for (const [k, v] of Object.entries(p)) { if (v === null || v === "") next.delete(k); else next.set(k, v); } return next; }, { replace }, ), [setParams], ); // 默认进第一个在线的库根 useEffect(() => { if (rootId || !rootList.length) return; const first = rootList.find((r) => r.health !== "offline") ?? rootList[0]; if (first) patch({ root: first.id, path: null }, true); }, [rootId, rootList, patch]); // 搜索 300 ms 防抖写回 URL useEffect(() => { const t = setTimeout(() => { if (qInput.trim() !== q) patch({ q: qInput.trim() || null }, true); }, 300); return () => clearTimeout(t); }, [qInput, q, patch]); const listQ: ListQuery | null = root && root.health !== "offline" ? { root: root.id, path, sort, order, q, filter, hidden } : null; const list = useFileList(listQ); const pages = useMemo(() => list.data?.pages ?? [], [list.data]); const entries = useMemo(() => pages.flatMap((p) => p.entries), [pages]); const first = pages[0]; const keyOf = useCallback((e: FileEntry) => refKey({ root: rootId, path: e.path }), [rootId]); // 目录快照变了(cursor stale)→ 从头重载 const refetchList = list.refetch; useEffect(() => { if (pages.some((p) => p.stale)) void refetchList(); }, [pages, refetchList]); const [sel, setSel] = useState(emptySelection); // biome-ignore lint/correctness/useExhaustiveDependencies: 换目录清空选择 useEffect(() => setSel(emptySelection()), [rootId, path]); useEffect(() => { setSel((s) => { const n = pruneSelection(s, entries.map(keyOf)); return n.keys.size === s.keys.size && n.anchor === s.anchor && n.focus === s.focus ? s : n; }); }, [entries, keyOf]); const [dialog, setDialog] = useState(null); const [menu, setMenu] = useState<{ at: MenuAnchor; entry: FileEntry } | null>(null); const [treeOpen, setTreeOpen] = useState(false); const dragRefs = useRef([]); const gridRef = useRef(null); const searchRef = useRef(null); const probe = useProbe(); const selected = useMemo(() => entries.filter((e) => sel.keys.has(keyOf(e))), [entries, sel.keys, keyOf]); const detail = selParam != null ? (entries.find((e) => e.path === selParam) ?? null) : null; // SSE:files.changed 与整理事件 → 刷新受影响目录 useSse([FILES_CHANGED, EventType.organizationChanged], (ev) => { const p = ev.payload as { rootId?: string; dirs?: string[] } | undefined; if (ev.type === FILES_CHANGED && p?.rootId) { for (const d of p.dirs ?? [""]) { void qc.invalidateQueries({ queryKey: ["files", "list", p.rootId, d] }); void qc.invalidateQueries({ queryKey: filesKeys.tree(p.rootId, d) }); } } else void qc.invalidateQueries({ queryKey: ["files", "list"] }); }); // "/" 聚焦搜索 useEffect(() => { const on = (e: KeyboardEvent) => { if (e.key !== "/" || e.ctrlKey || e.metaKey) return; const t = e.target as HTMLElement; if (t.closest("input,textarea,select,[contenteditable=true],[role=dialog]")) return; e.preventDefault(); searchRef.current?.focus(); }; window.addEventListener("keydown", on); return () => window.removeEventListener("keydown", on); }, []); const go = (loc: { root: string; path: string }) => { setTreeOpen(false); patch({ root: loc.root, path: loc.path || null, sel: null, q: null }); setQInput(""); }; const open = (e: FileEntry) => { if (e.escape) return toast.error("链接指向登记根之外,已禁用"); if (e.type === "dir") go({ root: rootId, path: e.path }); else patch({ sel: e.path }); }; const up = () => { if (path) go({ root: rootId, path: parentRel(path) }); }; const refs = (list: FileEntry[]) => list.map((e) => ({ root: rootId, path: e.path })); const targets = (e?: FileEntry) => (e && !sel.keys.has(keyOf(e)) ? [e] : selected.length ? selected : e ? [e] : []); const doProbe = (list: FileEntry[]) => { const vids = list.filter((e) => e.type === "file" && e.fileKind === "video").slice(0, 20); if (!vids.length) return toast.info("选中项里没有视频文件"); probe.mutate( { items: refs(vids) }, { onSuccess: (r) => { const ok = r.items.filter((i) => i.status === "ok").length; toast.success(`探测完成:${ok}/${r.items.length} 个读到媒体信息`, { description: r.items.some((i) => i.savedToAsset) ? "已登记资产已写回媒体信息" : "未登记文件的结果缓存 24 小时", }); }, onError: (err) => toast.error(filesErrorText(err, "探测失败")), }, ); }; const openDelete = (list: FileEntry[]) => { if (!root || !list.length) return; const blocked = list.map((e) => opDisabledReason("delete", e, root)).find(Boolean); if (blocked && list.length === 1) return toast.error(blocked); setDialog({ kind: "delete", items: refs(list) }); }; const openRename = (e: FileEntry) => { if (!root) return; const why = opDisabledReason("rename", e, root); if (why) return toast.error(why); setDialog({ kind: "rename", entry: e }); }; const menuItems = (e: FileEntry): MenuItem[] => { if (!root) return []; const list = targets(e); const multi = list.length > 1; const why = (op: Parameters[0]) => list.map((x) => opDisabledReason(op, x, root)).find(Boolean) ?? null; const items: MenuItem[] = []; if (!multi) items.push({ key: "open", label: e.type === "dir" ? "打开" : "详情", icon: FolderOpen, hint: "Enter", onSelect: () => open(e), }); if (multi) items.push({ key: "wizard", label: `整理向导(${list.length} 项)`, icon: Wand2, disabled: why("organize"), onSelect: () => setDialog({ kind: "wizard", entries: list }), }); if (!multi) items.push({ key: "rename", label: "重命名", icon: PenLine, hint: "F2", disabled: why("rename"), onSelect: () => openRename(e), }); items.push( { key: "move", label: "移动到…", icon: FolderInput, disabled: why("move"), onSelect: () => setDialog({ kind: "transfer", items: refs(list), mode: "move" }), }, { key: "copy", label: "复制到…", icon: Copy, disabled: e.escape ? "链接指向登记根之外,已禁用" : null, onSelect: () => setDialog({ kind: "transfer", items: refs(list), mode: "copy" }), }, ); if (!multi) items.push({ key: "organize", label: "整理到…", icon: Wand2, disabled: why("organize"), onSelect: () => setDialog({ kind: "wizard", entries: list }), }); items.push({ key: "identify", label: "识别", icon: Sparkles, disabled: why("identify"), onSelect: () => setDialog({ kind: "wizard", entries: list }), }); if (!multi) items.push({ key: "scrape", label: "刮削", icon: Library, disabled: why("scrape"), onSelect: () => setDialog({ kind: "scrape", entry: e }), }); items.push({ key: "probe", label: "探测", icon: ScanSearch, disabled: list.some((x) => x.type === "file" && x.fileKind === "video") ? null : "只能探测视频文件", onSelect: () => doProbe(list), }); items.push({ key: "sep1", separator: true }); if (!multi) { items.push({ key: "copyPath", label: "复制路径…", icon: ClipboardCopy, onSelect: () => setDialog({ kind: "copyPath", entry: e }), }); items.push({ key: "openMedia", label: "打开作品", icon: Library, disabled: why("openMedia"), onSelect: () => e.asset && navigate(`/console/library/${e.asset.mediaEntityId}`), }); items.push({ key: "records", label: "在整理记录中查看", icon: FileStack, disabled: why("records"), onSelect: () => e.asset && navigate(`/console/organize?mediaEntityId=${e.asset.mediaEntityId}`), }); items.push({ key: "sep2", separator: true }); } items.push({ key: "delete", label: multi ? `删除 ${list.length} 项` : "删除", icon: Trash2, hint: "Del", destructive: true, disabled: why("delete"), onSelect: () => openDelete(list), }); return items; }; // 拖拽:列表项 → 树节点 / 面包屑 / 列表里的目录 = 移动到(Alt 复制),一律先出 dryRun 预览 const onDragRows = (e: FileEntry, ev: React.DragEvent) => { const k = keyOf(e); const list = sel.keys.has(k) ? selected : [e]; if (!sel.keys.has(k)) setSel({ keys: new Set([k]), anchor: k, focus: k }); dragRefs.current = refs(list); ev.dataTransfer.effectAllowed = "copyMove"; ev.dataTransfer.setData(DRAG_MIME, JSON.stringify(dragRefs.current)); ev.dataTransfer.setData("text/plain", list.map((x) => x.name).join("\n")); }; const onDropTo = (target: FileRef, ev: React.DragEvent) => { const items = dragRefs.current; dragRefs.current = []; if (!items.length) return; if (items.some((i) => i.root === target.root && (i.path === target.path || parentRel(i.path) === target.path))) { if (items.every((i) => i.root === target.root && parentRel(i.path) === target.path)) return; } const tRoot = rootList.find((r) => r.id === target.root); if (!tRoot?.writable) return toast.error("只能拖到可写的媒体库根"); setDialog({ kind: "transfer", items, mode: ev.altKey ? "copy" : "move", target }); }; const clearFilters = () => { setQInput(""); patch({ q: null, f: null }); }; // ── 左栏 ── const tree = (
{roots.isPending ? : null} {roots.error ? void roots.refetch()} /> : null} {rootList.length ? ( ) : null} {roots.data && !rootList.length ? ( ) : null} 回收站
); // ── 列表区主体 ── const offline = list.error && isRootOffline(list.error); const filtered = !!(q || filter); let body: React.ReactNode; if (!root) { body = roots.isPending ? : null; } else if (root.health === "offline" || offline) { body = (

{root.name} 离线

{offline ? filesErrorText(list.error) : healthReasonText(root.healthReason)} 。不会把离线当成空目录,也不会改变任何资产状态。

上次检查:{relTime(root.checkedAt)}

); } else if (list.isPending) { body = ; } else if (list.error && !entries.length) { body = ( void list.refetch()} /> ); } else if (!entries.length) { body = filtered ? ( 清除筛选 } /> ) : ( setDialog({ kind: "mkdir" })}> 新建目录 ) : undefined } /> ); } else { body = ( setMenu({ entry, at })} onRename={openRename} onDelete={openDelete} onDragRows={onDragRows} onDropToDir={(dir, ev) => onDropTo({ root: rootId, path: dir.path }, ev)} hasMore={!!list.hasNextPage} onLoadMore={() => void list.fetchNextPage()} loadingMore={list.isFetchingNextPage} mobile={mobile} /> ); } const selCount = selected.length; const actionBar = selCount > 0 && root ? (
已选 {selCount} 项{totalSize(selected) ? ` · ${formatBytes(totalSize(selected), 1)}` : ""}
) : null; return ( <> {filesMockEnabled() ? 演示数据 : null} 回收站 } />
{/* 桌面左栏:根 + 目录树(可拖宽) */}
{/* 工具栏 */}
{root ? ( go({ root: root.id, path: p })} onDropTo={(p, ev) => onDropTo({ root: root.id, path: p }, ev)} className="min-w-0 flex-1" /> ) : ( )}
setQInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Escape") { setQInput(""); gridRef.current?.focus(); } if (e.key === "ArrowDown") gridRef.current?.focus(); }} placeholder="名称或 glob,如 *.mkv ( / )" aria-label="搜索当前目录" className="h-8 pl-9" />
{FILTER_CHIPS.map((c) => ( ))}
{first?.truncated ? (
目录过大,只读取了前 {first.total.toLocaleString("zh-CN")} 项。请用搜索或进入子目录缩小范围。
) : null}
{body}
{/* 状态栏 */} {root && !offline && root.health !== "offline" ? (
{first ? `${entries.length.toLocaleString("zh-CN")} / ${first.total.toLocaleString("zh-CN")} 项` : "—"} {selCount ? ( 已选 {selCount} {totalSize(selected) ? ` · ${formatBytes(totalSize(selected), 1)}` : ""} ) : null} {root.usage ? 剩余 {formatBytes(root.usage.freeBytes, 1)} : null} {!root.writable ? 只读 : null}
) : null} {!mobile ? actionBar : null}
{mobile ? actionBar : null} {/* 手机:根与目录树收进抽屉 */} 根与目录
{tree}
setMenu(null)} /> {detail && root ? ( patch({ sel: null })} actions={ <> {detail.asset ? null : ( )} } /> ) : null} {dialog?.kind === "rename" && root ? ( setDialog(null)} /> ) : null} {dialog?.kind === "transfer" ? ( setDialog(null)} /> ) : null} {dialog?.kind === "delete" ? ( setDialog(null)} /> ) : null} {root ? ( !o && setDialog(null)} /> ) : null} {dialog?.kind === "copyPath" && root ? ( setDialog(null)} /> ) : null} {dialog?.kind === "scrape" ? setDialog(null)} /> : null} {dialog?.kind === "wizard" && root ? ( setDialog(null)} /> ) : null} ); }