import { Input } from "antd"; import { Check, ImagePlus, Loader2, Pause, Play, Search, Upload } from "lucide-react"; import { useEffect, useRef, useState, type ReactNode } from "react"; import { useInfiniteQuery } from "@tanstack/react-query"; import { CachedResourceImage } from "@/components/cached-resource-image"; import { useDebouncedValue } from "@/hooks/use-debounced-value"; import { getResourceAccess, resolveResourceAccessURL, resourceIdFromStorageKey } from "@/services/api/resources"; import { loadAssetLibraryPage } from "@/services/user-data-sync"; import type { AudioAsset, ImageAsset } from "@/stores/use-asset-store"; const PAGE_SIZE = { image: 18, audio: 20 } as const; /** 素材库分页查询:只保留已同步到云端、可被角色卡绑定的素材,滚到底部自动加载下一页。 */ function useCharacterMediaPages(kind: K, keyword: string) { const query = useDebouncedValue(keyword.trim(), 250); const pages = useInfiniteQuery({ queryKey: ["character-media-library", kind, query], initialPageParam: 1, queryFn: ({ signal, pageParam }) => loadAssetLibraryPage({ page: pageParam, pageSize: PAGE_SIZE[kind], kind, status: "active", query: query || undefined, signal }), getNextPageParam: (page, all) => (all.reduce((count, item) => count + item.assets.length, 0) < page.total ? all.length + 1 : undefined), }); const items = (pages.data?.pages.flatMap((page) => page.assets) || []).filter( (asset): asset is K extends "image" ? ImageAsset : AudioAsset => asset.kind === kind && Boolean(resourceIdFromStorageKey((asset as ImageAsset | AudioAsset).data.storageKey)), ); const sentinelRef = useRef(null); const { hasNextPage, isFetchingNextPage, fetchNextPage } = pages; useEffect(() => { const target = sentinelRef.current; if (!target || !hasNextPage || typeof IntersectionObserver === "undefined") return; const observer = new IntersectionObserver( (entries) => { if (entries.some((entry) => entry.isIntersecting) && !isFetchingNextPage) void fetchNextPage(); }, { rootMargin: "160px" }, ); observer.observe(target); return () => observer.disconnect(); }, [fetchNextPage, hasNextPage, isFetchingNextPage]); return { items, query, loading: pages.isLoading, loadingMore: isFetchingNextPage, sentinelRef }; } function SearchField({ value, placeholder, onChange }: { value: string; placeholder: string; onChange: (value: string) => void }) { return } placeholder={placeholder} onChange={(event) => onChange(event.target.value)} />; } function FilePicker({ accept, onFile, children }: { accept: string; onFile: (file: File) => void; children: (open: () => void) => ReactNode }) { const inputRef = useRef(null); return ( <> {children(() => inputRef.current?.click())} { const file = event.target.files?.[0]; event.target.value = ""; if (file) onFile(file); }} /> ); } function ListState({ loading, empty, loadingMore }: { loading: boolean; empty: string; loadingMore: boolean }) { if (loading) return

正在读取素材库

; if (empty) return

{empty}

; return loadingMore ?

正在加载更多

: null; } /** 同一资源在当前画布上有节点时,用节点名(用户改过的名字)代替素材库里的默认标题。 */ export type CanvasMediaTitles = ReadonlyMap; /** 形象选择:缩略图网格,点选即绑定;第一格为本地上传。 */ export function CharacterImageLibrary({ currentResourceId, busyKey, canvasTitles, onPick, onUpload }: { currentResourceId: string; canvasTitles?: CanvasMediaTitles; busyKey: string; onPick: (resourceId: string) => void; onUpload: (file: File) => void }) { const [keyword, setKeyword] = useState(""); const { items, query, loading, loadingMore, sentinelRef } = useCharacterMediaPages("image", keyword); return (
{(open) => ( )} {items.map((asset) => { const resourceId = resourceIdFromStorageKey(asset.data.storageKey); const current = resourceId === currentResourceId; const busy = busyKey === resourceId; const title = canvasTitles?.get(resourceId) || asset.title; return ( ); })}
); } /** 共用一个播放器试听,避免每行一个原生控件把列表挤乱。 */ function useAudition() { const audioRef = useRef(null); const [playing, setPlaying] = useState(""); useEffect(() => () => audioRef.current?.pause(), []); const toggle = async (resourceId: string, storageKey?: string) => { const audio = audioRef.current || (audioRef.current = new Audio()); if (playing === resourceId) { audio.pause(); setPlaying(""); return; } audio.pause(); setPlaying(resourceId); try { audio.src = resolveResourceAccessURL((await getResourceAccess(storageKey, "display", "playback")).url); audio.onended = () => setPlaying(""); await audio.play(); } catch { setPlaying(""); } }; return { playing, toggle }; } /** 声音选择:列表 + 单击试听,右侧“使用”即绑定。 */ export function CharacterVoiceLibrary({ currentResourceId, busyKey, canvasTitles, onPick, onUpload, }: { currentResourceId: string; canvasTitles?: CanvasMediaTitles; busyKey: string; onPick: (resourceId: string, title: string) => void; onUpload: (file: File) => void; }) { const [keyword, setKeyword] = useState(""); const { items, query, loading, loadingMore, sentinelRef } = useCharacterMediaPages("audio", keyword); const { playing, toggle } = useAudition(); return (
{(open) => ( )}
    {items.map((asset) => { const resourceId = resourceIdFromStorageKey(asset.data.storageKey); const current = resourceId === currentResourceId; const seconds = asset.data.durationMs ? Math.round(asset.data.durationMs / 1000) : 0; const title = canvasTitles?.get(resourceId) || asset.title; return (
  • {title} {seconds ? `${seconds} 秒` : "音频"} {current ? ( 使用中 ) : ( )}
  • ); })}
); }