Files
flypic/frontend/src/components/AIGenModal.jsx
T
jinghui c25f8b474c feat: AI生图弹窗新增生图模型点选 (v1.4.11)
- 弹窗按通道分组列出8个可选模型(CF Workers AI/Pollinations), 点击即选中高亮
- 所选模型存localStorage下次沿用; 自动初始化=设置默认模型
- generate带model参数(effModel=前端所选>设置默认), 后端加ALLOWED_MODELS白名单, 未知模型400
- 实测点选Pollinations动漫出图返回model=pollinations-flux-anime; 白名单拦截bogus-model
- 版本号4处升至1.4.11, CHANGELOG补条目
2026-11-19 14:38:18 +08:00

628 lines
30 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, useEffect, useRef, useCallback } from 'react';
import {
X, Wand2, Loader2, Download, Save, RefreshCw, Sparkles,
ChevronDown, FolderOpen, CheckCircle2, AlertTriangle,
Image as ImageIcon, Search, Plus, Trash2
} from 'lucide-react';
import { aigenAPI, fileAPI, imageAPI } from '../api';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { PROMPT_CATEGORIES } from '../constants/promptPresets';
/**
* AI 生图弹窗
* - 热门提示词分类(点击填入/追加)
* - 弹窗内点选生图模型(列表来自设置配置的模型分组),KEY/通道仍在「设置 → AI 生图」
* - 生成 → 预览 → 保存到素材库 / 下载 / 重新生成
*/
function flattenFolders(folders) {
// 节点自带完整 path(FolderModel.getTree)
const out = [{ path: '', label: '(根目录)' }];
const walk = (list) => {
for (const f of list || []) {
if (f.path) out.push({ path: f.path, label: f.path });
if (f.children && f.children.length) walk(f.children);
}
};
walk(folders);
return out;
}
export default function AIGenModal({ open, onClose, onSaved }) {
const { currentLibraryId } = useLibraryStore();
const { folders, setFolders, setImages, selectedFolder } = useImageStore();
const [prompt, setPrompt] = useState('');
const [cat, setCat] = useState('hot');
const [sizes, setSizes] = useState([]);
const [providerInfo, setProviderInfo] = useState(null);
const [modelGroups, setModelGroups] = useState([]); // 可选生图模型分组
const [selModel, setSelModel] = useState(''); // 用户点选的模型 id(空=设置默认)
const [size, setSize] = useState('1024x1024');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [result, setResult] = useState(null); // { b64, revisedPrompt, ms, model }
const [saveTarget, setSaveTarget] = useState('');
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [showFolderPick, setShowFolderPick] = useState(false);
const [advanced, setAdvanced] = useState(false);
// 参考图(以图生图)
const [refs, setRefs] = useState([]); // [{ path, filename, thumbnailPath }]
const [showRefPicker, setShowRefPicker] = useState(false);
const [refList, setRefList] = useState([]);
const [refQuery, setRefQuery] = useState('');
const [refLoading, setRefLoading] = useState(false);
const imgRef = useRef(null);
// 打开时拉模型列表 + 当前配置
useEffect(() => {
if (!open) return;
setError('');
setResult(null);
setSaved(false);
setRefs([]);
setShowRefPicker(false);
setRefQuery('');
aigenAPI.getModels()
.then((d) => {
setSizes(d.sizes || []);
setProviderInfo(d.provider || null);
const groups = d.groups || [];
setModelGroups(groups);
const all = groups.flatMap((g) => (g.models || []).map((m) => m.id));
const p = d.provider || {};
// 自定义提供商:只有设置里填的那个模型可用
if (p.type === 'custom') { setSelModel(p.customModel || ''); return; }
const def = p.builtinModel || 'flux-schnell';
const saved = localStorage.getItem('flypic_aigen_model');
setSelModel(all.includes(saved) ? saved : (all.includes(def) ? def : (all[0] || def)));
})
.catch((e) => setError('读取模型列表失败: ' + (e.data?.error || e.message)));
}, [open]);
/** 素材库缩略图地址 */
const thumbUrl = (img) => {
if (!img || !currentLibraryId) return '';
const raw = img.thumbnailPath || img.path || img.filename || '';
const fn = String(raw).replace(/\\/g, '/').split('/').pop();
return `/api/image/thumbnail/${currentLibraryId}/${encodeURIComponent(fn)}`;
};
/** 打开素材库选图:读当前库的图片(只图片,不含视频) */
const openRefPicker = async () => {
setShowRefPicker(true);
setRefLoading(true);
setRefList([]);
try {
const resp = await imageAPI.search(currentLibraryId, { limit: 200, offset: 0, q: refQuery || undefined });
const list = (resp.images || []).filter((it) => {
const t = String(it.fileType || it.type || '').toLowerCase();
if (t === 'video') return false;
const ext = String(it.filename || it.path || '').split('.').pop().toLowerCase();
return !['mp4', 'mov', 'mkv', 'webm', 'avi', 'm4v', 'ts', 'flv'].includes(ext);
});
setRefList(list);
} catch (e) {
setError('读取素材库图片失败: ' + (e.data?.error || e.message));
} finally {
setRefLoading(false);
}
};
const isPickedRef = (img) => refs.some((r) => r.path === img.path);
const toggleRef = (img) => {
setError('');
if (isPickedRef(img)) {
setRefs((prev) => prev.filter((r) => r.path !== img.path));
return;
}
if (refs.length >= 4) { setError('最多选 4 张参考图'); return; }
setRefs((prev) => [...prev, img]);
};
const handleGenerate = async () => {
if (!prompt.trim()) { setError('请先输入提示词,或点一个热门提示词'); return; }
setLoading(true);
setError('');
setSaved(false);
try {
const d = await aigenAPI.generate({
prompt: prompt.trim(),
model: selModel || undefined,
size,
libraryId: currentLibraryId,
refImages: refs.map((r) => ({ path: r.path, filename: r.filename })),
});
const img = d.images && d.images[0];
if (!img || !img.b64) throw new Error('未返回图片数据');
const ext = d.ext || img.ext || 'png';
setResult({ b64: img.b64, ext, mime: ext === 'jpg' ? 'jpeg' : ext, revisedPrompt: d.revisedPrompt, ms: d.ms, model: d.model });
// 生成成功后刷新一次文件夹(可能有别处新入库)
if (currentLibraryId) {
imageAPI.getFolders(currentLibraryId).then((r) => setFolders(r.folders)).catch(() => {});
}
} catch (e) {
setError(e.data?.error || e.message || '生成失败');
} finally {
setLoading(false);
}
};
const b64ToFile = () => {
const bin = atob(result.b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
const ts = new Date();
const pad = (n) => String(n).padStart(2, '0');
const ext = result.ext || 'png';
const name = `AI_${ts.getFullYear()}${pad(ts.getMonth() + 1)}${pad(ts.getDate())}_${pad(ts.getHours())}${pad(ts.getMinutes())}${pad(ts.getSeconds())}.${ext}`;
return new File([arr], name, { type: `image/${result.mime || ext}` });
};
const handleSave = async () => {
if (!currentLibraryId) { setError('请先选择素材库'); return; }
setSaving(true);
setError('');
try {
const file = b64ToFile();
await fileAPI.upload(currentLibraryId, saveTarget, [file], undefined, 'rename');
setSaved(true);
// 刷新文件夹与当前视图
const r = await imageAPI.getFolders(currentLibraryId);
setFolders(r.folders);
const params = { folder: selectedFolder || '' };
const resp = await imageAPI.search(currentLibraryId, params);
setImages(resp.images);
onSaved && onSaved();
} catch (e) {
setError('保存失败: ' + (e.data?.error || e.message));
} finally {
setSaving(false);
}
};
const handleDownload = () => {
const a = document.createElement('a');
a.href = `data:image/${result.mime || 'png'};base64,${result.b64}`;
a.download = b64ToFile().name;
a.click();
};
const appendPrompt = (p) => {
setPrompt(p);
setError('');
};
if (!open) return null;
const activeCat = PROMPT_CATEGORIES.find((c) => c.key === cat) || PROMPT_CATEGORIES[0];
const noKey = providerInfo && !providerInfo.hasKey && providerInfo.type !== 'custom';
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-[98vw] h-[98vh] max-w-none max-h-none overflow-hidden flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* 头部 */}
<div className="flex items-center justify-between px-5 py-3.5 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<div className="p-1.5 rounded-lg bg-gradient-to-br from-purple-500 to-pink-500">
<Wand2 className="w-4 h-4 text-white" />
</div>
<h2 className="text-base font-semibold text-gray-900 dark:text-white">AI 生图</h2>
<span className="text-xs text-gray-400 dark:text-gray-500">热门提示词 · 一键生成 · 入库</span>
</div>
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-5">
<div className="grid grid-cols-1 lg:grid-cols-5 gap-5">
{/* 左:提示词 + 热门词库 */}
<div className="lg:col-span-3 space-y-4">
<div>
<div className="flex items-center justify-between mb-1.5">
<label className="text-xs font-medium text-gray-500 dark:text-gray-400">提示词</label>
<span className="text-[11px] text-gray-400">{prompt.length} 字</span>
</div>
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
placeholder="描述你想要的画面,例如:一只戴墨镜的柴犬在海边冲浪,卡通风格"
className="w-full px-3 py-2.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 resize-none focus:ring-2 focus:ring-purple-400 focus:border-transparent"
/>
</div>
{/* 热门提示词 */}
<div>
<div className="flex items-center gap-1.5 mb-2">
<Sparkles className="w-3.5 h-3.5 text-amber-500" />
<span className="text-xs font-medium text-gray-500 dark:text-gray-400">常用热门提示词</span>
</div>
<div className="flex flex-wrap gap-1.5 mb-2.5">
{PROMPT_CATEGORIES.map((c) => (
<button
key={c.key}
onClick={() => setCat(c.key)}
className={`px-2.5 py-1 rounded-full text-xs transition-colors ${
cat === c.key
? 'bg-purple-600 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
}`}
>
{c.label}
</button>
))}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5 max-h-56 overflow-y-auto pr-1">
{activeCat.prompts.map((p) => (
<button
key={p.name}
onClick={() => appendPrompt(p.promptCn)}
title={p.promptCn}
className="text-left px-2.5 py-2 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-purple-400 dark:hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-500/10 transition-colors group"
>
<div className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate group-hover:text-purple-700 dark:group-hover:text-purple-300">
{p.name}
</div>
<div className="mt-0.5 text-[10px] leading-4 text-gray-400 dark:text-gray-500 line-clamp-2 group-hover:text-gray-500 dark:group-hover:text-gray-400">
{p.promptCn}
</div>
</button>
))}
</div>
</div>
</div>
{/* 右:参数 + 生成 */}
<div className="lg:col-span-2 space-y-3.5">
{/* 生图模型:列出可点选的模型 */}
<div className="px-3 py-2.5 rounded-lg bg-gray-50 dark:bg-gray-900/40 border border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between mb-2">
<span className="text-xs font-medium text-gray-500 dark:text-gray-400">生图模型</span>
<button
onClick={() => window.dispatchEvent(new CustomEvent('open:settings', { detail: { tab: 'aigen' } }))}
className="text-[11px] text-purple-600 dark:text-purple-400 hover:underline"
>
通道设置
</button>
</div>
{providerInfo && providerInfo.type === 'custom' ? (
<div className="flex flex-wrap gap-1.5">
<span className="px-2.5 py-1 rounded-full text-[11px] bg-purple-600 text-white border border-purple-600">
{providerInfo.customModel || '自定义模型'}
</span>
<span className="px-1 py-1 text-[11px] text-gray-400 dark:text-gray-500 self-center">
自定义提供商的模型在设置里配置
</span>
</div>
) : (
<div className="space-y-1.5">
{modelGroups.map((g) => (
<div key={g.key} className="flex items-start gap-2">
<span className="text-[10px] text-gray-400 dark:text-gray-500 w-[76px] flex-shrink-0 pt-1 leading-4">{g.label}</span>
<div className="flex flex-wrap gap-1.5">
{(g.models || []).map((m) => (
<button
key={m.id}
type="button"
title={m.id}
onClick={() => { setSelModel(m.id); localStorage.setItem('flypic_aigen_model', m.id); }}
className={`px-2.5 py-1 rounded-full text-[11px] border transition-colors ${selModel === m.id
? 'bg-purple-600 text-white border-purple-600'
: 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-gray-600 hover:border-purple-400 hover:text-purple-600 dark:hover:text-purple-300'}`}
>
{m.name}
</button>
))}
</div>
</div>
))}
{!modelGroups.length && (
<span className="text-[11px] text-gray-400 dark:text-gray-500">读取模型列表中…</span>
)}
</div>
)}
{refs.length > 0 && (
<p className="mt-1.5 text-[11px] text-amber-600 dark:text-amber-400">
已选参考图:后端会自动切到 FLUX.2 图生图模型
</p>
)}
</div>
{noKey && (
<div className="flex items-start gap-1.5 text-[11px] text-amber-600 dark:text-amber-400">
<AlertTriangle className="w-3.5 h-3.5 flex-shrink-0 mt-px" />
<span>未配置 API Key。到「设置 → AI 生图」填写,或由服务器环境变量注入。</span>
</div>
)}
{/* 参考图:以图生图 */}
<div>
<div className="flex items-center justify-between mb-1.5">
<label className="text-xs font-medium text-gray-500 dark:text-gray-400">
参考图(以图生图){refs.length > 0 && <span className="text-purple-600 dark:text-purple-400">· 已选 {refs.length}/4</span>}
</label>
{refs.length > 0 && (
<button
onClick={() => setRefs([])}
className="text-[11px] text-gray-400 hover:text-red-500 flex items-center gap-0.5"
>
<Trash2 className="w-3 h-3" />清空
</button>
)}
</div>
<div className="flex items-center gap-1.5 flex-wrap">
{refs.map((r, i) => (
<div key={r.path || i} className="relative w-14 h-14 rounded-lg overflow-hidden border border-gray-200 dark:border-gray-600">
<img src={thumbUrl(r)} alt={r.filename || ''} className="w-full h-full object-cover" />
<button
onClick={() => toggleRef(r)}
className="absolute top-0 right-0 p-0.5 bg-black/60 text-white rounded-bl"
title="移除"
>
<X className="w-3 h-3" />
</button>
</div>
))}
{refs.length < 4 && (
<button
onClick={openRefPicker}
className="w-14 h-14 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-400 hover:border-purple-400 hover:text-purple-500 flex flex-col items-center justify-center gap-0.5"
title="从素材库选择参考图"
>
<Plus className="w-4 h-4" />
<span className="text-[9px]">选图</span>
</button>
)}
</div>
<p className="mt-1 text-[11px] text-gray-400 dark:text-gray-500">
{refs.length > 0
? '将按参考图生成(自动切到 FLUX.2 图生图模型),图片只在本机读取,不上传到第三方'
: '选 1-4 张素材库图片做参考,即可换背景、改风格、保持人物一致'}
</p>
</div>
{/* 尺寸 */}
<div>
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">尺寸</label>
<div className="grid grid-cols-3 gap-1.5">
{sizes.map((s) => (
<button
key={s}
onClick={() => setSize(s)}
className={`px-2 py-1.5 rounded-lg text-xs transition-colors ${
size === s
? 'bg-purple-600 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
}`}
>
{s.replace('x', '×')}
</button>
))}
</div>
</div>
{/* 生成按钮 */}
<button
onClick={handleGenerate}
disabled={loading || !prompt.trim()}
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
>
{loading ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
生成中…(约 10-30 秒)
</>
) : (
<>
<Wand2 className="w-4 h-4" />
生成图片
</>
)}
</button>
{loading && (
<div className="text-[11px] text-gray-400 dark:text-gray-500 text-center">
正在调用生图服务
{refs.length > 0 ? '(以图生图,约 20-60 秒)' : ',超时上限 150 秒'}
</div>
)}
</div>
</div>
{/* 错误 */}
{error && (
<div className="mt-4 flex items-start gap-2 px-3 py-2.5 rounded-lg bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/30 text-sm text-red-700 dark:text-red-300">
<AlertTriangle className="w-4 h-4 flex-shrink-0 mt-0.5" />
<span className="whitespace-pre-wrap">{error}</span>
</div>
)}
{/* 结果预览 */}
{result && (
<div className="mt-5 border border-gray-200 dark:border-gray-700 rounded-xl overflow-hidden">
<div className="flex items-center justify-between px-4 py-2 bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
<span>模型 {result.model}</span>
<span>耗时 {(result.ms / 1000).toFixed(1)}s</span>
</div>
<div className="flex items-center gap-1.5">
<button
onClick={handleGenerate}
disabled={loading}
className="flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
>
<RefreshCw className="w-3.5 h-3.5" /> 重新生成
</button>
<button
onClick={handleDownload}
className="flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
>
<Download className="w-3.5 h-3.5" /> 下载
</button>
</div>
</div>
<div className="p-4 bg-gray-100 dark:bg-gray-900 flex justify-center">
<img
ref={imgRef}
src={`data:image/${result.mime || 'png'};base64,${result.b64}`}
alt="AI 生成结果"
className="max-h-[46vh] max-w-full object-contain rounded-lg shadow"
/>
</div>
{result.revisedPrompt && (
<div className="px-4 py-2 text-[11px] text-gray-400 dark:text-gray-500 border-t border-gray-200 dark:border-gray-700 truncate" title={result.revisedPrompt}>
改写提示词:{result.revisedPrompt}
</div>
)}
{/* 入库区 */}
<div className="flex flex-wrap items-center gap-2 px-4 py-3 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
<div className="relative">
<button
onClick={() => setShowFolderPick((v) => !v)}
className="flex items-center gap-1.5 px-3 py-2 text-xs rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
>
<FolderOpen className="w-3.5 h-3.5" />
{saveTarget || '根目录'}
<ChevronDown className="w-3.5 h-3.5" />
</button>
{showFolderPick && (
<>
<div className="fixed inset-0 z-10"></div>
<div className="absolute left-0 bottom-full mb-1 z-20 w-64 max-h-64 overflow-y-auto bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl p-1">
{flattenFolders(folders).map((f) => (
<button
key={f.path}
onClick={() => { setSaveTarget(f.path); setShowFolderPick(false); }}
className={`w-full text-left px-2.5 py-1.5 rounded text-xs truncate ${
saveTarget === f.path
? 'bg-purple-50 dark:bg-purple-500/20 text-purple-700 dark:text-purple-300'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
{f.path || '(根目录)'}
</button>
))}
</div>
</>
)}
</div>
<button
onClick={handleSave}
disabled={saving || saved}
className="flex items-center gap-1.5 px-4 py-2 text-xs font-medium rounded-lg text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50"
>
{saving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : saved ? <CheckCircle2 className="w-3.5 h-3.5" /> : <Save className="w-3.5 h-3.5" />}
{saved ? '已入库' : saving ? '入库中…' : '保存到素材库'}
</button>
<span className="text-[11px] text-gray-400 dark:text-gray-500">
{currentLibraryId ? 'PNG 格式,入库后自动建索引与缩略图' : '未选择素材库'}
</span>
</div>
</div>
)}
</div>
</div>
{/* 素材库选图(以图生图) */}
{showRefPicker && (
<div
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 p-4"
onClick={() => setShowRefPicker(false)}
>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col overflow-hidden"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<ImageIcon className="w-4 h-4 text-purple-500" />
<h3 className="text-sm font-semibold text-gray-900 dark:text-white">从素材库选择参考图</h3>
<span className="text-[11px] text-gray-400">已选 {refs.length}/4</span>
</div>
<button onClick={() => setShowRefPicker(false)} className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
<X className="w-4 h-4 text-gray-500" />
</button>
</div>
<div className="px-4 py-2.5 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
<div className="relative flex-1">
<Search className="w-3.5 h-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
<input
value={refQuery}
onChange={(e) => setRefQuery(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') openRefPicker(); }}
placeholder="搜索文件名,回车查询"
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<button
onClick={openRefPicker}
className="px-3 py-1.5 text-xs rounded-lg bg-purple-600 text-white hover:bg-purple-700"
>
查询
</button>
</div>
<div className="flex-1 overflow-y-auto p-3">
{refLoading ? (
<div className="flex items-center justify-center py-16 text-xs text-gray-400 gap-2">
<Loader2 className="w-4 h-4 animate-spin" />读取图片中…
</div>
) : refList.length === 0 ? (
<div className="py-16 text-center text-xs text-gray-400">这个素材库里没有可选图片</div>
) : (
<div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 gap-2">
{refList.map((img) => {
const picked = isPickedRef(img);
const idx = refs.findIndex((r) => r.path === img.path);
return (
<button
key={img.path || img.filename}
onClick={() => toggleRef(img)}
title={img.filename || img.path}
className={`relative aspect-square rounded-lg overflow-hidden border-2 transition-all ${
picked ? 'border-purple-500 ring-2 ring-purple-300' : 'border-transparent hover:border-gray-300'
}`}
>
<img src={thumbUrl(img)} alt={img.filename || ''} className="w-full h-full object-cover" />
{picked && (
<span className="absolute top-1 left-1 w-5 h-5 rounded-full bg-purple-600 text-white text-[11px] flex items-center justify-center font-medium">
{idx + 1}
</span>
)}
</button>
);
})}
</div>
)}
</div>
<div className="flex items-center justify-between px-4 py-2.5 border-t border-gray-200 dark:border-gray-700">
<span className="text-[11px] text-gray-400">点图多选,按点选顺序作为参考顺序</span>
<button
onClick={() => setShowRefPicker(false)}
className="px-4 py-1.5 text-xs font-medium rounded-lg bg-purple-600 text-white hover:bg-purple-700"
>
完成
</button>
</div>
</div>
</div>
)}
</div>
);
}