feat(v1.3.0): 图片编辑器(裁剪/旋转/图像大小/调色) + 批量水印 + AI生图 + 收藏体系 + 图片新窗口打开按钮 + 合拼拼图 + 返回顶部

This commit is contained in:
jinghui committed 2026-11-17 23:36:32 +08:00
1 parent e345456abf
commit 94ac94436c
46 files changed
+6521 -114

No files matched your search

+14 -3
View File
@@ -12,6 +12,8 @@ import MainContent from './components/MainContent';
import RightPanel from './components/RightPanel';
import Header from './components/Header';
import LibraryMissingModal from './components/LibraryMissingModal';
import BackToTop from './components/BackToTop';
import ImageEditor from './components/ImageEditor';
import { createLogger } from './utils/logger';
const logger = createLogger('App');
@@ -124,11 +126,16 @@ function App() {
params.folder = imageState.selectedFolder;
}
// 「我的收藏」视图:按收藏过滤
if (imageState.favoritesView) {
params.favorite = 1;
}
// 并行加载文件夹、图片和统计信息
Promise.all([
imageAPI.getFolders(libraryId),
// 如果没有选中文件夹且没有搜索条件,不加载图片(保持在 Dashboard)
(imageState.selectedFolder || imageState.searchKeywords || imageState.filters.formats.length > 0)
(imageState.selectedFolder || imageState.searchKeywords || imageState.filters.formats.length > 0 || imageState.favoritesView)
? imageAPI.search(libraryId, params)
: Promise.resolve({ images: [] }),
// 扫描完成后重新获取统计信息(包含 totalSize)
@@ -493,6 +500,7 @@ function App() {
if (isMobile) {
return (
<div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
<BackToTop />
<Header />
{/* 素材库路径丢失弹窗 */}
<LibraryMissingModal
@@ -504,6 +512,7 @@ function App() {
onOpenOther={handleOpenOtherLibrary}
onCreateNew={handleCreateNewLibrary}
/>
<ImageEditor />
<div className="flex-1 overflow-hidden relative">
{/* 侧边栏视图 */}
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'sidebar' ? 'translate-x-0' : '-translate-x-full'
@@ -566,6 +575,7 @@ function App() {
// 桌面端布局
return (
<div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
<BackToTop />
<Header />
{/* 素材库路径丢失弹窗 */}
<LibraryMissingModal
@@ -576,8 +586,9 @@ function App() {
onRescan={handleRescanLibrary}
onOpenOther={handleOpenOtherLibrary}
onCreateNew={handleCreateNewLibrary}
/>
<div ref={containerRef} className="flex flex-1 overflow-hidden">
/>
<ImageEditor />
<div ref={containerRef} className="flex flex-1 overflow-hidden">
{/* 左侧边栏 */}
<div id="left-panel" style={{ width: `${leftWidth}px` }} className="flex-shrink-0 h-full bg-white dark:bg-gray-800">
<Sidebar />
+22
View File
@@ -0,0 +1,22 @@
/**
* AI 生图 API
* 注意:client 的 API_BASE 已含 /api,这里只写 /aigen 段
*/
import { api } from '../client';
/** 模型分组 + 当前配置(apiKey 掩码) */
export function getModels() {
return api.get('/aigen/models');
}
/**
* 生成图片
* @param {Object} payload { prompt, model?, size?, provider? }
* provider: 'builtin' | 'custom'
*/
export function generate(payload) {
return api.post('/aigen/generate', payload, { timeout: 180000 });
}
export const aigenAPI = { getModels, generate };
export default aigenAPI;
+21
View File
@@ -0,0 +1,21 @@
/**
* 批量水印 API(文件夹级)
*/
import { api } from '../client';
/** 启动批量任务,返回 { taskId, total } */
export async function start(payload) {
// payload: { libraryId, folder, type: 'add'|'remove', output?, options }
return api.post('/batch/start', payload);
}
/** 查询任务进度 */
export async function status(taskId) {
return api.get(`/batch/status/${taskId}`);
}
/** 取消任务 */
export async function cancel(taskId) {
return api.post(`/batch/cancel/${taskId}`);
}
+7 -4
View File
@@ -19,8 +19,9 @@ export async function search(libraryId, params = {}, options = {}) {
/**
* 获取图片总数
*/
export async function getCount(libraryId) {
return api.get(`/image/count?libraryId=${libraryId}`);
export async function getCount(libraryId, params = {}) {
const query = new URLSearchParams({ libraryId, ...params });
return api.get(`/image/count?${query}`);
}
/**
@@ -48,8 +49,10 @@ export async function getCacheMeta(libraryId) {
* 获取缩略图 URL
* 使用分片结构,不再需要 size 参数
*/
export function getThumbnailUrl(libraryId, filename) {
return `/api/image/thumbnail/${libraryId}/${filename}`;
export function getThumbnailUrl(libraryId, filename, version) {
const base = `/api/image/thumbnail/${libraryId}/${filename}`;
// version=文件 modified_at,编辑保存后变化以穿透浏览器缓存
return version ? `${base}?v=${version}` : base;
}
/**
+4 -1
View File
@@ -8,12 +8,15 @@ import * as scan from './endpoints/scan';
import { fileAPI } from './file';
import { settingsAPI } from './endpoints/settings';
import { hubAPI } from './endpoints/hub';
import * as batch from './endpoints/batch';
import { aigenAPI } from './endpoints/aigen';
export const libraryAPI = library;
export const imageAPI = image;
export const scanAPI = scan;
export { fileAPI };
export { settingsAPI, hubAPI };
export { settingsAPI, hubAPI, aigenAPI };
export const batchAPI = batch;
export { api, APIError } from './client';
+432
View File
@@ -0,0 +1,432 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import {
X, Wand2, Loader2, Download, Save, RefreshCw, Sparkles,
ChevronDown, FolderOpen, CheckCircle2, AlertTriangle
} 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 生图弹窗
* - 热门提示词分类(点击填入/追加)
* - 内置模型(NewAPI:CF Workers AI / Pollinations)+ 自定义提供商
* - 生成 → 预览 → 保存到素材库 / 下载 / 重新生成
*/
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 [groups, setGroups] = useState([]);
const [sizes, setSizes] = useState([]);
const [providerInfo, setProviderInfo] = useState(null);
const [model, setModel] = useState('flux-schnell');
const [size, setSize] = useState('1024x1024');
const [useCustom, setUseCustom] = useState(false);
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 imgRef = useRef(null);
// 打开时拉模型列表 + 当前配置
useEffect(() => {
if (!open) return;
setError('');
setResult(null);
setSaved(false);
aigenAPI.getModels()
.then((d) => {
setGroups(d.groups || []);
setSizes(d.sizes || []);
setProviderInfo(d.provider || null);
const first = (d.groups || [])[0];
if (first && first.models && first.models[0]) setModel(first.models[0].id);
if (d.provider && d.provider.type === 'custom') setUseCustom(true);
})
.catch((e) => setError('读取模型列表失败: ' + (e.data?.error || e.message)));
}, [open]);
const currentModelId = useCustom ? (providerInfo?.customModel || '') : model;
const handleGenerate = async () => {
if (!prompt.trim()) { setError('请先输入提示词,或点一个热门提示词'); return; }
setLoading(true);
setError('');
setSaved(false);
try {
const d = await aigenAPI.generate({
prompt: prompt.trim(),
model: useCustom ? undefined : model,
size,
provider: useCustom ? 'custom' : 'builtin'
});
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((prev) => (prev.trim() ? prev.replace(/[,,、\s]+$/, '') + ',' + p : p));
setError('');
};
if (!open) return null;
const activeCat = PROMPT_CATEGORIES.find((c) => c.key === cat) || PROMPT_CATEGORIES[0];
const noKey = providerInfo && !providerInfo.hasKey && !useCustom;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-5xl max-h-[90vh] 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.prompt)}
title={p.prompt}
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="text-[10px] text-gray-400 dark:text-gray-500 truncate">{p.prompt}</div>
</button>
))}
</div>
</div>
</div>
{/* 右:参数 + 生成 */}
<div className="lg:col-span-2 space-y-3.5">
{/* 提供商 */}
<div>
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">模型提供商</label>
<select
value={useCustom ? 'custom' : 'builtin'}
onChange={(e) => setUseCustom(e.target.value === 'custom')}
className="w-full px-3 py-2 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"
>
<option value="builtin">内置 NewAPI(Pollinations + CF Workers AI)</option>
<option value="custom" disabled={!providerInfo?.customModel && !providerInfo?.customUrl}>
自定义提供商{providerInfo?.customModel ? `(${providerInfo.customModel})` : '(未配置)'}
</option>
</select>
{providerInfo && !providerInfo.hasKey && !useCustom && (
<div className="mt-1.5 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>
{/* 模型 */}
{!useCustom && (
<div>
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">模型</label>
<select
value={model}
onChange={(e) => setModel(e.target.value)}
className="w-full px-3 py-2 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"
>
{groups.map((g) => (
<optgroup key={g.key} label={g.label}>
{g.models.map((m) => (
<option key={m.id} value={m.id}>{m.name}</option>
))}
</optgroup>
))}
</select>
</div>
)}
{useCustom && (
<div className="p-3 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/30 rounded-lg text-xs text-amber-700 dark:text-amber-300">
使用设置中配置的自定义提供商({providerInfo?.customUrl || '未配置地址'})。
模型:{providerInfo?.customModel || '(未配置)'}
<button
onClick={() => window.dispatchEvent(new CustomEvent('open:settings', { detail: { tab: 'aigen' } }))}
className="ml-1 underline hover:text-amber-900 dark:hover:text-amber-100"
>
去配置
</button>
</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">
正在调用 {useCustom ? '自定义提供商' : (model || '')},超时上限 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" onClick={() => setShowFolderPick(false)}></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>
</div>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { useEffect, useState, useCallback } from 'react';
import { Rocket } from 'lucide-react';
/**
* 返回顶部小火箭(右下角)
* 兼容两种滚动容器:react-window 虚拟列表(内部滚动)和普通 overflow-y-auto 容器。
*/
function findScrolledElement() {
const all = document.querySelectorAll('*');
let best = null;
let bestTop = 0;
for (const el of all) {
const style = window.getComputedStyle(el);
const scrollable = (style.overflowY === 'auto' || style.overflowY === 'scroll') && el.scrollHeight > el.clientHeight + 4;
if (scrollable && el.scrollTop > bestTop) {
bestTop = el.scrollTop;
best = el;
}
}
return bestTop > 0 ? best : null;
}
function BackToTop() {
const [visible, setVisible] = useState(false);
useEffect(() => {
const onScroll = () => {
const el = findScrolledElement();
const top = el ? el.scrollTop : (window.scrollY || document.documentElement.scrollTop || 0);
setVisible(top > 300);
};
onScroll();
window.addEventListener('scroll', onScroll, true);
window.addEventListener('resize', onScroll);
const timer = setInterval(onScroll, 1500);
return () => {
window.removeEventListener('scroll', onScroll, true);
window.removeEventListener('resize', onScroll);
clearInterval(timer);
};
}, []);
const scrollToTop = useCallback(() => {
const el = findScrolledElement();
if (el) el.scrollTo({ top: 0, behavior: 'smooth' });
window.scrollTo({ top: 0, behavior: 'smooth' });
document.documentElement.scrollTo({ top: 0, behavior: 'smooth' });
}, []);
if (!visible) return null;
return (
<button
onClick={scrollToTop}
title="返回顶部"
aria-label="返回顶部"
className="fixed bottom-20 md:bottom-6 right-4 md:right-6 z-40 w-12 h-12 rounded-full bg-blue-600 hover:bg-blue-700 text-white shadow-lg shadow-blue-600/40 hover:shadow-blue-600/60 flex items-center justify-center transition-all hover:-translate-y-0.5 active:translate-y-0"
>
<Rocket size={22} className="-rotate-45" />
</button>
);
}
export default BackToTop;
@@ -0,0 +1,556 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import {
Droplets, Eraser, Loader2, X, Play, Square, CheckCircle2,
AlertTriangle, Save, FileEdit, Eye
} from 'lucide-react';
import { batchAPI, imageAPI } from '../api';
/**
* 批量水印弹窗(文件夹级)
* mode='add' 批量加水印:文字水印(九宫格单个 / 平铺)
* mode='remove' 批量去水印:按百分比区域生成 mask → 后端 LaMa inpaint
*
* 流程:配置 → 启动任务(立即返回 taskId)→ 1s 轮询进度 → 完成/取消
*/
// 九宫格位置(与后端 makeWatermarkSvg 的 pos 规则一致)
const POSITIONS = [
['top-left', 'top-center', 'top-right'],
['middle-left', 'middle-center', 'middle-right'],
['bottom-left', 'bottom-center', 'bottom-right']
];
const POSITION_LABEL = {
'top-left': '左上', 'top-center': '顶部', 'top-right': '右上',
'middle-left': '左侧', 'middle-center': '居中', 'middle-right': '右侧',
'bottom-left': '左下', 'bottom-center': '底部', 'bottom-right': '右下'
};
// 去水印预设区域(百分比)
const REGION_PRESETS = [
{ key: 'bottom-right', label: '右下角', region: { x: 68, y: 86, w: 30, h: 11 } },
{ key: 'bottom-left', label: '左下角', region: { x: 2, y: 86, w: 30, h: 11 } },
{ key: 'top-right', label: '右上角', region: { x: 68, y: 3, w: 30, h: 11 } },
{ key: 'top-left', label: '左上角', region: { x: 2, y: 3, w: 30, h: 11 } },
{ key: 'center', label: '画面居中', region: { x: 35, y: 42, w: 30, h: 16 } },
{ key: 'bottom-bar', label: '底部横条', region: { x: 0, y: 88, w: 100, h: 11 } },
{ key: 'right-bar', label: '右侧竖条', region: { x: 85, y: 0, w: 15, h: 100 } },
{ key: 'custom', label: '自定义', region: null }
];
const clampPct = (v) => Math.max(0, Math.min(100, Number(v) || 0));
function Field({ label, children, hint }) {
return (
<div className="mb-4">
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">{label}</div>
{children}
{hint && <div className="text-[11px] text-gray-400 dark:text-gray-500 mt-1">{hint}</div>}
</div>
);
}
function Slider({ value, onChange, min, max, step = 1, suffix = '' }) {
return (
<div className="flex items-center gap-3">
<input
type="range"
className="flex-1 accent-blue-500"
value={value}
min={min}
max={max}
step={step}
onChange={(e) => onChange(Number(e.target.value))}
/>
<span className="text-xs text-gray-600 dark:text-gray-300 w-12 text-right tabular-nums">
{value}{suffix}
</span>
</div>
);
}
function BatchWatermarkModal({ isOpen, mode, folder, libraryId, onClose, onFinished }) {
const [phase, setPhase] = useState('config'); // config | running | done
const [imageCount, setImageCount] = useState(0);
const [starting, setStarting] = useState(false);
const [error, setError] = useState('');
// 加水印配置
const [text, setText] = useState('');
const [tile, setTile] = useState(false);
const [position, setPosition] = useState('bottom-right');
const [fontSizePct, setFontSizePct] = useState(4);
const [opacity, setOpacity] = useState(50);
const [color, setColor] = useState('#ffffff');
const [marginPct, setMarginPct] = useState(2);
const [rotate, setRotate] = useState(-30);
const [stroke, setStroke] = useState(true);
// 去水印配置
const [presetKey, setPresetKey] = useState('bottom-right');
const [region, setRegion] = useState({ x: 68, y: 86, w: 30, h: 11 });
// 输出方式
const [output, setOutput] = useState('overwrite');
// 任务进度
const [taskId, setTaskId] = useState(null);
const [progress, setProgress] = useState(null);
const pollRef = useRef(null);
// 打开时重置 + 取图片数
useEffect(() => {
if (!isOpen) return;
setPhase('config');
setError('');
setTaskId(null);
setProgress(null);
setStarting(false);
setOutput('overwrite');
if (mode === 'remove') {
setPresetKey('bottom-right');
setRegion({ x: 68, y: 86, w: 30, h: 11 });
}
let cancelled = false;
(async () => {
try {
const resp = await imageAPI.getCount(libraryId, { folder });
if (!cancelled) setImageCount(resp.count ?? 0);
} catch (_) {
if (!cancelled) setImageCount(0);
}
})();
return () => { cancelled = true; };
}, [isOpen, mode, folder, libraryId]);
// 停止轮询
const stopPolling = useCallback(() => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
}, []);
useEffect(() => stopPolling, [stopPolling]);
const startPolling = useCallback((id) => {
stopPolling();
pollRef.current = setInterval(async () => {
try {
const s = await batchAPI.status(id);
setProgress(s);
if (s.status !== 'running') {
stopPolling();
setPhase('done');
onFinished?.(s);
}
} catch (_) {
/* 网络抖动,继续轮询 */
}
}, 1000);
}, [stopPolling, onFinished]);
const handleStart = async () => {
setError('');
if (mode === 'add' && !text.trim()) {
setError('请输入水印文字');
return;
}
setStarting(true);
try {
const payload = { libraryId, folder, type: mode, output };
payload.options = mode === 'add'
? { text: text.trim(), tile, position, fontSizePct, opacity, color, marginPct, rotate, stroke }
: { region };
const resp = await batchAPI.start(payload);
setTaskId(resp.taskId);
setPhase('running');
setProgress({
status: 'running', total: resp.total, done: 0, failed: 0,
skipped: 0, current: '', errors: []
});
startPolling(resp.taskId);
} catch (err) {
setError(err?.message || '启动失败');
} finally {
setStarting(false);
}
};
const handleCancel = async () => {
if (!taskId) return;
try {
await batchAPI.cancel(taskId);
} catch (_) { /* 任务可能已结束 */ }
stopPolling();
setPhase('done');
};
const handleClose = () => {
stopPolling();
onClose();
};
if (!isOpen) return null;
const isAdd = mode === 'add';
const title = isAdd ? '批量加水印' : '批量去水印';
const Icon = isAdd ? Droplets : Eraser;
const accent = isAdd ? 'text-blue-500' : 'text-emerald-500';
const accentBtn = isAdd ? 'bg-blue-500 hover:bg-blue-600' : 'bg-emerald-500 hover:bg-emerald-600';
const pct = progress && progress.total > 0
? Math.round(((progress.done + progress.failed + progress.skipped) / progress.total) * 100)
: 0;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={handleClose}>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* 头部 */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2.5">
<Icon className={`w-5 h-5 ${accent}`} />
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">{title}</h2>
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 truncate max-w-[240px]">
{folder}
</span>
<span className="text-xs text-gray-400">{imageCount} 张图片</span>
</div>
<button onClick={handleClose} className="p-1 rounded 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">
{phase === 'config' && (
<>
{isAdd ? (
<>
<Field label="水印文字">
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="例如:素材室出品"
maxLength={50}
className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</Field>
<Field label="水印形式">
<div className="flex gap-2">
<button
onClick={() => setTile(false)}
className={`flex-1 px-3 py-2 rounded-lg text-sm border transition-colors ${!tile
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300'}`}
>
单个水印
</button>
<button
onClick={() => setTile(true)}
className={`flex-1 px-3 py-2 rounded-lg text-sm border transition-colors ${tile
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300'}`}
>
全屏平铺
</button>
</div>
</Field>
{!tile && (
<Field label="位置">
<div className="grid grid-cols-3 gap-1.5 w-44">
{POSITIONS.flat().map((pos) => (
<button
key={pos}
onClick={() => setPosition(pos)}
title={POSITION_LABEL[pos]}
className={`px-1 py-1.5 rounded text-xs border transition-colors ${position === pos
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 font-medium'
: 'border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-gray-400'}`}
>
{POSITION_LABEL[pos]}
</button>
))}
</div>
</Field>
)}
<div className="grid grid-cols-2 gap-x-5">
<Field label="字号(占图宽比例)">
<Slider value={fontSizePct} onChange={setFontSizePct} min={1} max={15} suffix="%" />
</Field>
<Field label="透明度">
<Slider value={opacity} onChange={setOpacity} min={5} max={100} suffix="%" />
</Field>
<Field label={tile ? '倾斜角度' : '旋转角度'}>
<Slider value={rotate} onChange={setRotate} min={-90} max={90} suffix="°" />
</Field>
<Field label="边距(占图宽比例)">
<Slider value={marginPct} onChange={setMarginPct} min={0} max={10} suffix="%" />
</Field>
</div>
<div className="grid grid-cols-2 gap-x-5">
<Field label="颜色">
<div className="flex items-center gap-2">
<input
type="color"
value={color}
onChange={(e) => setColor(e.target.value)}
className="w-9 h-9 rounded cursor-pointer border border-gray-300 dark:border-gray-600 bg-transparent"
/>
{['#ffffff', '#000000', '#ff3b30', '#ffd60a'].map((c) => (
<button
key={c}
onClick={() => setColor(c)}
title={c}
className={`w-6 h-6 rounded-full border-2 ${color === c ? 'border-blue-500' : 'border-gray-300 dark:border-gray-600'}`}
style={{ backgroundColor: c }}
/>
))}
<span className="text-xs text-gray-500 tabular-nums">{color}</span>
</div>
</Field>
<Field label="描边(浅色背景更清晰)">
<label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
<input
type="checkbox"
checked={stroke}
onChange={(e) => setStroke(e.target.checked)}
className="accent-blue-500 w-4 h-4"
/>
启用黑色描边
</label>
</Field>
</div>
</>
) : (
<>
<Field label="水印区域(占图片宽高的百分比)" hint="批量去水印按统一区域处理,请选择水印所在的固定位置">
<div className="flex flex-wrap gap-2 mb-3">
{REGION_PRESETS.map((p) => (
<button
key={p.key}
onClick={() => {
setPresetKey(p.key);
if (p.region) setRegion(p.region);
}}
className={`px-3 py-1.5 rounded-lg text-xs border transition-colors ${presetKey === p.key
? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-300 font-medium'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:border-gray-400'}`}
>
{p.label}
</button>
))}
</div>
<div className="flex items-center gap-4">
{/* 区域示意 */}
<div className="relative w-32 h-20 rounded border border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-900 shrink-0 overflow-hidden">
<div
className="absolute bg-emerald-400/50 border border-emerald-500"
style={{
left: `${clampPct(region.x)}%`,
top: `${clampPct(region.y)}%`,
width: `${Math.max(1, Math.min(100 - clampPct(region.x), region.w))}%`,
height: `${Math.max(1, Math.min(100 - clampPct(region.y), region.h))}%`
}}
/>
</div>
<div className="grid grid-cols-2 gap-x-4 gap-y-2 text-xs">
{[['x', '左边距'], ['y', '上边距'], ['w', '宽度'], ['h', '高度']].map(([k, lb]) => (
<label key={k} className="flex items-center gap-2">
<span className="text-gray-500 dark:text-gray-400 w-10">{lb}</span>
<input
type="number"
min={0}
max={100}
value={region[k]}
onChange={(e) => {
setPresetKey('custom');
setRegion((r) => ({ ...r, [k]: clampPct(e.target.value) }));
}}
className="w-16 px-2 py-1 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white tabular-nums focus:outline-none focus:ring-2 focus:ring-emerald-500"
/>
<span className="text-gray-400">%</span>
</label>
))}
</div>
</div>
</Field>
<div className="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 px-3 py-2.5 text-xs text-amber-700 dark:text-amber-300 flex gap-2">
<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
<span>
修复区域内的所有内容都会被抹除重建(包括文字、logo、图案)。水印位置在整批图片中不一致时请分批处理,或用编辑器单张涂抹。
</span>
</div>
</>
)}
{/* 输出方式 */}
<Field label="处理后">
<div className="flex gap-2">
<button
onClick={() => setOutput('overwrite')}
className={`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg text-sm border transition-colors ${output === 'overwrite'
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300'}`}
>
<FileEdit className="w-4 h-4" /> 覆盖原图
</button>
<button
onClick={() => setOutput('new')}
className={`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg text-sm border transition-colors ${output === 'new'
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300'}`}
>
<Save className="w-4 h-4" /> 另存为新图
</button>
</div>
<div className="text-[11px] text-gray-400 dark:text-gray-500 mt-1.5">
{output === 'overwrite'
? '原图将被替换(缩略图与索引同步更新)'
: isAdd ? '生成 新图名_wm.jpg 保留原图' : '生成 新图名_nowm.jpg 保留原图'}
</div>
</Field>
{error && (
<div className="rounded-lg bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 px-3 py-2 text-xs text-red-600 dark:text-red-300">
{error}
</div>
)}
</>
)}
{(phase === 'running' || phase === 'done') && progress && (
<div className="py-2">
{/* 状态 */}
<div className="flex items-center gap-3 mb-4">
{phase === 'running' ? (
<Loader2 className="w-6 h-6 text-blue-500 animate-spin shrink-0" />
) : progress.failed > 0 ? (
<AlertTriangle className="w-6 h-6 text-amber-500 shrink-0" />
) : (
<CheckCircle2 className="w-6 h-6 text-emerald-500 shrink-0" />
)}
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-gray-900 dark:text-white">
{phase === 'running'
? (isAdd ? '正在加水印…' : '正在去水印…(AI 修复较慢,请耐心等待)')
: progress.status === 'cancelled'
? '已取消'
: progress.status === 'error'
? '任务异常终止'
: '处理完成'}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 truncate">
{phase === 'running' && progress.current
? progress.current
: `成功 ${progress.done} · 失败 ${progress.failed}${progress.skipped ? ` · 跳过 ${progress.skipped}` : ''} / 共 ${progress.total}`}
</div>
</div>
<div className="text-sm tabular-nums text-gray-600 dark:text-gray-300 shrink-0">
{progress.done + progress.failed + progress.skipped}/{progress.total}
</div>
</div>
{/* 进度条 */}
<div className="h-2.5 rounded-full bg-gray-200 dark:bg-gray-700 overflow-hidden mb-4">
<div
className={`h-full transition-all duration-300 ${progress.failed > 0 && phase === 'done' ? 'bg-amber-500' : isAdd ? 'bg-blue-500' : 'bg-emerald-500'}`}
style={{ width: `${pct}%` }}
/>
</div>
{/* 统计 */}
<div className="grid grid-cols-3 gap-2 mb-4">
{[
['成功', progress.done, 'text-emerald-600 dark:text-emerald-400'],
['失败', progress.failed, progress.failed ? 'text-red-500' : 'text-gray-500'],
['跳过', progress.skipped, 'text-gray-500']
].map(([lb, v, cls]) => (
<div key={lb} className="rounded-lg bg-gray-50 dark:bg-gray-900 px-3 py-2 text-center">
<div className={`text-lg font-semibold tabular-nums ${cls}`}>{v}</div>
<div className="text-[11px] text-gray-400">{lb}</div>
</div>
))}
</div>
{/* 错误明细 */}
{progress.errors && progress.errors.length > 0 && (
<div className="rounded-lg border border-red-200 dark:border-red-800 bg-red-50/50 dark:bg-red-900/20 p-3 mb-2">
<div className="text-xs font-medium text-red-600 dark:text-red-300 mb-1.5">
失败明细(最多记录 20 条)
</div>
<div className="space-y-1 max-h-40 overflow-y-auto">
{progress.errors.map((e, i) => (
<div key={i} className="text-[11px] text-red-500 dark:text-red-400 font-mono break-all">
{e.path || '(全局)'} — {e.error}
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
{/* 底部按钮 */}
<div className="px-5 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
{phase === 'config' && (
<>
<button
onClick={handleClose}
className="px-4 py-2.5 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 text-sm"
>
取消
</button>
<button
onClick={handleStart}
disabled={starting || imageCount === 0}
className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed transition-colors ${accentBtn}`}
>
{starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
{imageCount === 0 ? '该文件夹没有图片' : `开始处理 ${imageCount} 张`}
</button>
</>
)}
{phase === 'running' && (
<button
onClick={handleCancel}
className="flex items-center gap-2 px-4 py-2.5 rounded-lg border border-red-300 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 text-sm"
>
<Square className="w-4 h-4" /> 停止任务
</button>
)}
{phase === 'done' && (
<>
<button
onClick={() => setPhase('config')}
className="px-4 py-2.5 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 text-sm"
>
再跑一批
</button>
<button
onClick={handleClose}
className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-white text-sm transition-colors ${accentBtn}`}
>
<Eye className="w-4 h-4" /> 完成,查看图片
</button>
</>
)}
</div>
</div>
</div>
);
}
export default BatchWatermarkModal;
+22 -1
View File
@@ -4,7 +4,7 @@
*/
import { useEffect, useRef } from 'react';
import { Trash2, Edit3, Move, Copy, FolderPlus } from 'lucide-react';
import { Trash2, Edit3, Move, Copy, FolderPlus, Star, Droplets, Eraser } from 'lucide-react';
function ContextMenu({ isOpen, position, onClose, options }) {
const menuRef = useRef(null);
@@ -136,6 +136,12 @@ export const menuItems = {
shortcut: 'F2',
action
}),
edit: (action) => ({
icon: <Edit3 size={16} />,
label: '编辑图片',
shortcut: 'E',
action
}),
move: (action) => ({
icon: <Move size={16} />,
label: '移动到',
@@ -147,6 +153,11 @@ export const menuItems = {
shortcut: 'Ctrl+C',
action
}),
favorite: (action, isFavorite = false) => ({
icon: <Star size={16} className={isFavorite ? 'fill-current text-amber-400' : ''} />,
label: isFavorite ? '取消收藏' : '收藏',
action
}),
newSiblingFolder: (action) => ({
icon: <FolderPlus size={16} />,
label: '新建同级文件夹',
@@ -157,6 +168,16 @@ export const menuItems = {
label: '新建子文件夹',
action
}),
batchAddWatermark: (action) => ({
icon: <Droplets size={16} />,
label: '批量加水印…',
action
}),
batchRemoveWatermark: (action) => ({
icon: <Eraser size={16} />,
label: '批量去水印…',
action
}),
divider: () => ({ divider: true })
};
+105 -6
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo, useRef } from 'react';
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, Star, Bell, Github, Settings, ExternalLink } from 'lucide-react';
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, ScanLine, Star, Bell, Github, Settings, ExternalLink, Wand2 } from 'lucide-react';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { useUIStore } from '../stores/useUIStore';
@@ -8,6 +8,7 @@ import { useTheme } from '../hooks/useTheme';
import { useHub } from '../hooks/useHub';
import { libraryAPI, scanAPI, watchAPI } from '../api';
import SettingsModal from './SettingsModal';
import AIGenModal from './AIGenModal';
import { createLogger } from '../utils/logger';
const logger = createLogger('Header');
@@ -22,17 +23,22 @@ function Header() {
const [showFilters, setShowFilters] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [isRescanning, setIsRescanning] = useState(false);
// 扫描进行中时禁用"重新扫描"按钮
const scanProgress = useScanStore((s) => s.scanProgress);
const [isMobile, setIsMobile] = useState(false);
const [showMobileSettings, setShowMobileSettings] = useState(false);
const [localSearchValue, setLocalSearchValue] = useState(searchKeywords);
const [showNotices, setShowNotices] = useState(false);
const [showSettings, setShowSettings] = useState(false);
const [settingsTab, setSettingsTab] = useState('ocr');
const [showAIGen, setShowAIGen] = useState(false);
const searchDebounceRef = useRef(null);
// 授权系统 hub:版本 / 公告 / 在线人数
const hub = useHub();
const announcements = hub.announcements || [];
const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.2.0';
const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.3.0';
// 从全局 store 获取筛选状态
const selectedFormats = filters.formats || [];
@@ -40,6 +46,16 @@ function Header() {
const selectedOrientations = filters.orientations || [];
const selectedRatings = filters.ratings || [];
// 从 AI 生图弹窗跳设置(open:settings 事件,detail = 菜单 tab)
useEffect(() => {
const handler = (e) => {
setSettingsTab((e.detail && e.detail.tab) || 'ocr');
setShowSettings(true);
};
window.addEventListener('open:settings', handler);
return () => window.removeEventListener('open:settings', handler);
}, []);
// 检测移动端
useEffect(() => {
const checkMobile = () => {
@@ -262,9 +278,12 @@ function Header() {
setFilters({ ratings: newRatings });
};
const favoriteOnly = !!filters.favoriteOnly;
const toggleFavoriteOnly = () => setFilters({ favoriteOnly: !favoriteOnly });
// 清除筛选
const clearFilters = () => {
setFilters({ formats: [], sizes: [], orientations: [], ratings: [] });
setFilters({ formats: [], sizes: [], orientations: [], ratings: [], favoriteOnly: false });
};
const handleThumbnailHeightChange = async (height) => {
@@ -291,6 +310,26 @@ function Header() {
}
};
// 重新扫描:重新索引全部文件,并为缺少文字索引的旧图片补跑 OCR
const handleRescan = async () => {
if (!currentLibraryId || isRescanning || scanProgress) return;
if (!window.confirm('重新扫描将重新索引全部文件,并为缺少文字索引的图片补跑 OCR 识别。库越大耗时越长(进度会在页面上方显示),确认开始?')) {
return;
}
setIsRescanning(true);
try {
await scanAPI.fullScan(currentLibraryId);
// 扫描进度通过 Socket.IO 的 scanProgress 推送
} catch (error) {
console.error('Error rescan:', error);
alert('重新扫描失败: ' + error.message);
} finally {
setIsRescanning(false);
}
};
// 从 filterOptions 中提取可用选项
const availableFormats = filterOptions.formats;
const availableSizes = filterOptions.sizes.map(size => ({ label: size }));
@@ -371,6 +410,14 @@ function Header() {
)}
</div>
<button
onClick={() => setShowAIGen(true)}
title="AI 生图"
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
<Wand2 className="w-5 h-5 text-purple-600 dark:text-purple-400" />
</button>
<button
onClick={() => setShowSettings(true)}
title="设置"
@@ -383,7 +430,8 @@ function Header() {
{appVersion}
</span>
<SettingsModal open={showSettings} onClose={() => setShowSettings(false)} versionLabel={appVersion} />
<SettingsModal open={showSettings} onClose={() => setShowSettings(false)} versionLabel={appVersion} initialTab={settingsTab} />
<AIGenModal open={showAIGen} onClose={() => setShowAIGen(false)} />
</>
);
@@ -396,7 +444,7 @@ function Header() {
<header className="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
{/* 顶部栏 */}
<div className="h-14 flex items-center justify-between px-4">
<h1 className="text-lg font-bold text-gray-900 dark:text-white">FlyPic</h1>
<h1 className="text-lg font-bold text-gray-900 dark:text-white">牛图</h1>
<div className="flex items-center gap-2">
<button
@@ -406,6 +454,15 @@ function Header() {
>
<RefreshCw className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRefreshing ? 'animate-spin' : ''}`} />
</button>
<button
onClick={handleRescan}
disabled={!currentLibraryId || isRescanning || !!scanProgress}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
title="重新扫描:重新索引全部文件并补跑 OCR 文字识别"
>
<ScanLine className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRescanning || scanProgress ? 'animate-pulse' : ''}`} />
</button>
<button
onClick={() => setShowMobileSettings(!showMobileSettings)}
@@ -586,6 +643,22 @@ function Header() {
</div>
</div>
)}
{/* 收藏筛选 */}
<div>
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">收藏</div>
<div className="flex flex-wrap gap-2">
<button
onClick={toggleFavoriteOnly}
className={`px-2 py-1 text-xs rounded-full flex items-center gap-1 ${
favoriteOnly
? 'bg-amber-500 text-white'
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
}`}
>
<Star size={12} className={favoriteOnly ? 'fill-current' : ''} /> 只看收藏
</button>
</div>
</div>
</div>
)}
</header>
@@ -597,7 +670,7 @@ function Header() {
<header className="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
<div className="h-14 flex items-center justify-between px-6">
<div className="flex-shrink-0">
<h1 className="text-xl font-bold text-gray-900 dark:text-white">FlyPic</h1>
<h1 className="text-xl font-bold text-gray-900 dark:text-white">牛图</h1>
<p className="text-xs text-gray-500 dark:text-gray-400">轻量快速的图片素材库管理</p>
</div>
@@ -661,6 +734,15 @@ function Header() {
>
<RefreshCw className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRefreshing ? 'animate-spin' : ''}`} />
</button>
<button
onClick={handleRescan}
disabled={!currentLibraryId || isRescanning || !!scanProgress}
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
title="重新扫描:重新索引全部文件并补跑 OCR 文字识别"
>
<ScanLine className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRescanning || scanProgress ? 'animate-pulse' : ''}`} />
</button>
<button
onClick={toggleTheme}
@@ -798,6 +880,23 @@ function Header() {
)}
</div>
</div>
{/* 收藏筛选 */}
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">收藏</label>
<div className="flex flex-col gap-1.5">
<button
onClick={toggleFavoriteOnly}
className={`px-3 py-1.5 text-xs rounded transition-colors text-left flex items-center gap-1.5 ${
favoriteOnly
? 'bg-amber-500 text-white'
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
}`}
>
<Star size={14} className={favoriteOnly ? 'fill-current' : ''} /> 只看收藏
</button>
</div>
</div>
</div>
</div>
</div>
+31 -3
View File
@@ -2,7 +2,7 @@
* 图片单元格组件
*/
import { Play, FileText, Palette, Music, File } from 'lucide-react';
import { Play, FileText, Palette, Music, File, Star, ExternalLink } from 'lucide-react';
const ImageCell = ({
image,
@@ -12,8 +12,10 @@ const ImageCell = ({
editingFilename,
editInputRef,
getThumbnailUrl,
getOriginalUrl,
onImageClick,
onImageDoubleClick,
onToggleFavorite,
onContextMenu,
onDragStart,
onEditingChange,
@@ -72,9 +74,9 @@ const ImageCell = ({
}}
/>
{/* 文件类型标识 */}
{/* 文件类型标识(右让位给「新窗口打开」按钮) */}
{image.fileType && image.fileType !== 'image' && (
<div className={`absolute top-2 right-2 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${
<div className={`absolute top-2 right-11 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${
image.fileType === 'video' ? 'bg-blue-500 bg-opacity-90' :
image.fileType === 'audio' ? 'bg-pink-500 bg-opacity-90' :
image.fileType === 'document' ? 'bg-green-500 bg-opacity-90' :
@@ -92,6 +94,32 @@ const ImageCell = ({
</div>
)}
{/* 在新窗口打开原图(右上角) */}
<a
href={getOriginalUrl ? getOriginalUrl(image) : ''}
target="_blank"
rel="noopener noreferrer"
title="在新窗口打开"
onClick={(e) => e.stopPropagation()}
onDoubleClick={(e) => e.stopPropagation()}
className="absolute top-2 right-2 z-10 p-1 rounded-full backdrop-blur-sm bg-black/40 hover:bg-black/70 transition-all opacity-0 group-hover:opacity-100"
>
<ExternalLink size={14} className="text-white" />
</a>
{/* 收藏标记 / 收藏按钮 */}
<button
type="button"
onClick={(e) => { e.stopPropagation(); onToggleFavorite?.(image); }}
title={image.favorite ? '取消收藏' : '收藏'}
className={`absolute top-2 left-2 z-10 p-1 rounded-full backdrop-blur-sm transition-all ${
image.favorite
? 'opacity-100 bg-amber-400/80'
: 'opacity-0 group-hover:opacity-100 bg-black/40'
}`}
>
<Star size={14} className={image.favorite ? 'fill-white text-white' : 'text-white'} />
</button>
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all pointer-events-none" />
</div>
File diff suppressed because it is too large. Load diff
+76 -4
View File
@@ -11,6 +11,7 @@ import { VariableSizeList as List } from 'react-window';
// Stores
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { useUIStore } from '../stores/useUIStore';
// Custom Hooks
import { useWaterfallLayout } from '../hooks/useWaterfallLayout';
@@ -26,7 +27,7 @@ import { useInfiniteScroll } from '../hooks/useInfiniteScroll';
// Utils
import { filterImages } from '../utils/imageFilters';
import { imageAPI } from '../api';
import { imageAPI, fileAPI } from '../api';
// Components
import ImageCell from './ImageCell';
@@ -53,8 +54,9 @@ function ImageWaterfall() {
const {
images, selectedImage, setSelectedImage, selectedImages, setSelectedImages,
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder,
searchKeywords, filters, folders, setSelectedFolderItem
searchKeywords, filters, folders, setSelectedFolderItem, updateImage
} = useImageStore();
const { setEditingImage, setMergeImages } = useUIStore();
// 状态
const [photoIndex, setPhotoIndex] = useState(-1);
@@ -184,7 +186,7 @@ function ImageWaterfall() {
const getThumbnailUrl = useCallback((image) => {
if (!currentLibraryId || !image.thumbnailPath) return '';
const filename = image.thumbnailPath.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(currentLibraryId, filename);
return imageAPI.getThumbnailUrl(currentLibraryId, filename, image.modifiedAt);
}, [currentLibraryId]);
const getOriginalUrl = useCallback((image) => {
@@ -276,6 +278,20 @@ function ImageWaterfall() {
e.dataTransfer.effectAllowed = 'move';
}, [selectedImages]);
const handleToggleFavorite = useCallback(async (image) => {
const targets = (selectedImages && selectedImages.length > 1 && selectedImages.includes(image))
? selectedImages : [image];
const newVal = image.favorite ? 0 : 1;
try {
for (const img of targets) {
await fileAPI.updateMetadata(currentLibraryId, img.path, { favorite: newVal });
updateImage(img.path, { favorite: newVal });
}
} catch (e) {
alert('收藏操作失败: ' + (e?.message || '未知错误'));
}
}, [currentLibraryId, selectedImages, updateImage]);
// 准备移动文件(用于右键菜单)
const handlePrepareMove = useCallback(() => {
const itemsToMove = selectedImages.length > 0
@@ -342,6 +358,10 @@ function ImageWaterfall() {
if (!isMultiSelection) {
menuOptions.push(
menuItems.edit(() => {
setContextMenu({ isOpen: false, position: null, image: null });
setEditingImage(image);
}),
menuItems.rename(() => {
setContextMenu({ isOpen: false, position: null, image: null });
handleStartRename(image);
@@ -351,6 +371,10 @@ function ImageWaterfall() {
menuOptions.push(
menuItems.move(handlePrepareMove),
menuItems.favorite(() => {
setContextMenu({ isOpen: false, position: null, image: null });
handleToggleFavorite(image);
}, image?.favorite),
menuItems.delete(async () => {
setContextMenu({ isOpen: false, position: null, image: null });
await handleQuickDelete();
@@ -358,7 +382,7 @@ function ImageWaterfall() {
);
return menuOptions;
}, [selectedImages, handlePrepareMove, handleStartRename, handleCopy, handleQuickDelete, setUndoToast]);
}, [selectedImages, handlePrepareMove, handleStartRename, handleCopy, handleQuickDelete, setUndoToast, handleToggleFavorite, setEditingImage]);
// 渲染单行
const renderRow = useCallback(({ index, style }) => {
@@ -388,8 +412,10 @@ function ImageWaterfall() {
editingFilename={editingFilename}
editInputRef={editInputRef}
getThumbnailUrl={getThumbnailUrl}
getOriginalUrl={getOriginalUrl}
onImageClick={handleImageClick}
onImageDoubleClick={handleImageDoubleClick}
onToggleFavorite={handleToggleFavorite}
onContextMenu={handleContextMenu}
onDragStart={handleDragStart}
onEditingChange={setEditingFilename}
@@ -408,6 +434,7 @@ function ImageWaterfall() {
renamingImage,
editingFilename,
getThumbnailUrl,
getOriginalUrl,
handleImageClick,
handleImageDoubleClick,
handleContextMenu,
@@ -471,6 +498,49 @@ function ImageWaterfall() {
>
<DragDropOverlay isVisible={isDraggingOver} />
<UploadProgress progress={uploadProgress} />
{/* 多选浮动操作条:显式删除入口(计数 = selectedImages ∪ selectedImage) */}
{(() => {
const union = [...selectedImages];
if (selectedImage && !union.some(img => img.path === selectedImage.path)) {
union.push(selectedImage);
}
const unionCount = union.length;
if (unionCount <= 1) return null;
return (
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-30 flex items-center gap-3 bg-gray-900/90 dark:bg-gray-800/90 backdrop-blur text-white rounded-full pl-5 pr-2 py-2 shadow-2xl">
<span className="text-sm whitespace-nowrap">已选 {unionCount} 张图片</span>
<button
onClick={() => {
setMergeImages(union);
setEditingImage(union[0]);
clearSelection();
}}
className="flex items-center gap-1.5 px-4 py-1.5 rounded-full bg-blue-600 hover:bg-blue-700 text-sm font-medium transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1V5zm9 0a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1V5zM4 14a1 1 0 011-1h6a1 1 0 011 1v5a1 1 0 01-1 1H5a1 1 0 01-1-1v-5zm9 1a1 1 0 001 1h4a1 1 0 001-1v-4a1 1 0 00-1-1h-4a1 1 0 00-1 1v4z" />
</svg>
合拼
</button>
<button
onClick={handleQuickDelete}
className="flex items-center gap-1.5 px-4 py-1.5 rounded-full bg-red-600 hover:bg-red-700 text-sm font-medium transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
移入回收站
</button>
<button
onClick={clearSelection}
className="px-3 py-1.5 rounded-full text-sm text-gray-300 hover:text-white hover:bg-white/10 transition-colors"
>
取消选择
</button>
</div>
);
})()}
<PhotoProvider
images={providerImages}
@@ -536,8 +606,10 @@ function ImageWaterfall() {
editingFilename={editingFilename}
editInputRef={editInputRef}
getThumbnailUrl={getThumbnailUrl}
getOriginalUrl={getOriginalUrl}
onImageClick={handleImageClick}
onImageDoubleClick={handleImageDoubleClick}
onToggleFavorite={handleToggleFavorite}
onContextMenu={handleContextMenu}
onDragStart={handleDragStart}
onEditingChange={setEditingFilename}
+2 -2
View File
@@ -82,7 +82,7 @@ export default function Login() {
<div className="inline-flex items-center justify-center mb-4">
<img
src="/ICON_256.PNG"
alt="FlyPic Logo"
alt="牛图 Logo"
className="w-20 h-20 object-contain"
onError={(e) => {
// 如果 ICON_256.PNG 加载失败,尝试 favicon.png
@@ -91,7 +91,7 @@ export default function Login() {
/>
</div>
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
FlyPic 飞图
牛图
</h1>
<p className="text-gray-600 dark:text-gray-400">
{hasPassword ? '请输入密码访问' : '首次使用,请设置访问密码'}
+7 -6
View File
@@ -15,7 +15,7 @@ const logger = createLogger('MainContent');
function MainContent() {
const { currentLibraryId } = useLibraryStore();
const { searchKeywords, filters, selectedFolder, setImages, setOriginalImages, imageLoadingState, images } = useImageStore();
const { searchKeywords, filters, selectedFolder, favoritesView, setImages, setOriginalImages, imageLoadingState, images, refreshTick } = useImageStore();
const { scanProgress } = useScanStore();
// 使用 ref 跟踪最新的请求上下文
@@ -47,8 +47,8 @@ function MainContent() {
const loadImages = useCallback(async (isInitialLoad = true) => {
if (!currentLibraryId) return;
// 如果没有选中文件夹且没有搜索条件,显示 Dashboard
if (!selectedFolder && !searchKeywords && filters.formats.length === 0) {
// 如果没有选中文件夹且没有搜索条件,显示 Dashboard(「我的收藏」视图除外)
if (!selectedFolder && !searchKeywords && filters.formats.length === 0 && !favoritesView) {
setImages([]);
useImageStore.getState().setImageLoadingState({
isLoading: false,
@@ -80,6 +80,7 @@ function MainContent() {
limit: 100
};
if (selectedFolder) params.folder = selectedFolder;
if (favoritesView) params.favorite = 1;
if (searchKeywords) params.keywords = searchKeywords;
if (filters.formats?.length > 0) params.formats = filters.formats.join(',');
@@ -128,7 +129,7 @@ function MainContent() {
currentRequestContextRef.current = null;
}
}
}, [currentLibraryId, searchKeywords, selectedFolder, setImages, setOriginalImages, cancelCurrentRequest]);
}, [currentLibraryId, searchKeywords, selectedFolder, favoritesView, setImages, setOriginalImages, cancelCurrentRequest]);
// 监听文件夹/搜索变化
useEffect(() => {
@@ -161,7 +162,7 @@ function MainContent() {
clearTimeout(debounceTimerRef.current);
}
};
}, [currentLibraryId, searchKeywords, selectedFolder, loadImages, cancelCurrentRequest]);
}, [currentLibraryId, searchKeywords, selectedFolder, favoritesView, refreshTick, loadImages, cancelCurrentRequest]);
// 恢复撤销前的文件夹状态
useEffect(() => {
@@ -232,7 +233,7 @@ function MainContent() {
{/* Content */}
<div className="flex-1 overflow-hidden">
{(!selectedFolder && !searchKeywords && filters.formats.length === 0) ? (
{(!selectedFolder && !searchKeywords && filters.formats.length === 0 && !favoritesView) ? (
<Dashboard />
) : (
<ImageWaterfall />
+452
View File
@@ -0,0 +1,452 @@
/**
* MergeCollage — 多图合拼面板
* - 常见合拼布局模板(横排/竖排/品字/宫格/一大N小)
* - 槽位从图库选图(搜索 + 分页)
* - 填了模型 KEY 后可 AI 自动从图库找相似图并自动合拼
* - 合成结果通过 onMerge(blob) 交还编辑器替换底图
*/
import { useState, useEffect, useCallback } from 'react';
import { X, Loader2, Sparkles } from 'lucide-react';
import { imageAPI, settingsAPI } from '../api';
import { getToken } from '../api/client';
import { useUIStore } from '../stores/useUIStore';
/** 布局模板:cells 为归一化矩形 [x, y, w, h],aspect 为输出画布宽高比 */
const LAYOUTS = [
{ id: '2h', name: '两图横排', aspect: 2, cells: [[0, 0, 0.5, 1], [0.5, 0, 0.5, 1]] },
{ id: '2v', name: '两图竖排', aspect: 0.5, cells: [[0, 0, 1, 0.5], [0, 0.5, 1, 0.5]] },
{ id: '3h', name: '三图横排', aspect: 3, cells: [[0, 0, 1/3, 1], [1/3, 0, 1/3, 1], [2/3, 0, 1/3, 1]] },
{ id: '3v', name: '三图竖排', aspect: 1/3, cells: [[0, 0, 1, 1/3], [0, 1/3, 1, 1/3], [0, 2/3, 1, 1/3]] },
{ id: '1+2', name: '一大两小', aspect: 1.5, cells: [[0, 0, 0.6, 1], [0.6, 0, 0.4, 0.5], [0.6, 0.5, 0.4, 0.5]] },
{ id: '2+1', name: '两小一大', aspect: 1.5, cells: [[0, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0, 0.5, 1, 0.5]] },
{ id: '2x2', name: '四宫格', aspect: 1, cells: [[0, 0, 0.5, 0.5], [0.5, 0, 0.5, 0.5], [0, 0.5, 0.5, 0.5], [0.5, 0.5, 0.5, 0.5]] },
{ id: '1+3', name: '一大三小', aspect: 1, cells: [[0, 0, 0.5, 1], [0.5, 0, 0.5, 1/3], [0.5, 1/3, 0.5, 1/3], [0.5, 2/3, 0.5, 1/3]] },
{ id: '3x2', name: '六宫格', aspect: 1.5, cells: [[0, 0, 1/3, 0.5], [1/3, 0, 1/3, 0.5], [2/3, 0, 1/3, 0.5], [0, 0.5, 1/3, 0.5], [1/3, 0.5, 1/3, 0.5], [2/3, 0.5, 1/3, 0.5]] },
{ id: '3x3', name: '九宫格', aspect: 1, cells: Array.from({ length: 9 }, (_, i) => [(i % 3) / 3, Math.floor(i / 3) / 3, 1/3, 1/3]) }
];
/** 按图片数量选默认布局:先找槽位数完全一致的,否则取能容纳的最小布局 */
function layoutForCount(n) {
if (n <= 1) return '2h';
const exact = LAYOUTS.find((l) => l.cells.length === n);
if (exact) return exact.id;
const bigger = LAYOUTS
.filter((l) => l.cells.length > n)
.sort((a, b) => a.cells.length - b.cells.length);
return bigger[0] ? bigger[0].id : '3x3';
}
const GAP_OPTIONS = [
{ value: 0, label: '无' },
{ value: 16, label: '细' },
{ value: 32, label: '粗' }
];
/** 缩略图 URL(无缩略图时回退原图) */
function thumbUrl(libId, rec) {
if (!rec) return '';
if (rec.thumbnailPath) {
const fn = rec.thumbnailPath.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(libId, fn, rec.modifiedAt);
}
return imageAPI.getOriginalUrl(libId, rec.path);
}
function loadImg(src) {
return new Promise((resolve, reject) => {
const im = new Image();
im.onload = () => resolve(im);
im.onerror = () => reject(new Error('图片加载失败: ' + src));
im.src = src;
});
}
export default function MergeCollage({ image, libraryId, onMerge, setStatus, setBusy }) {
const [layoutId, setLayoutId] = useState('2h');
const [slots, setSlots] = useState([image, null]);
const [gap, setGap] = useState(16);
const [keyReady, setKeyReady] = useState(null); // null=未检查
const [pickerFor, setPickerFor] = useState(null); // 正在选图的槽位下标
const [pickQuery, setPickQuery] = useState('');
const [pickImages, setPickImages] = useState([]);
const [pickOffset, setPickOffset] = useState(0);
const [pickHasMore, setPickHasMore] = useState(false);
const [pickLoading, setPickLoading] = useState(false);
const layout = LAYOUTS.find((l) => l.id === layoutId) || LAYOUTS[0];
const filled = slots.filter(Boolean).length;
// 打开时:有多选种子图则自动填槽 + 选布局;否则当前图为第 1 格
useEffect(() => {
const st = useUIStore.getState();
const seeds = st.mergeImages;
if (seeds && seeds.length >= 1) {
const lid = layoutForCount(seeds.length);
const L = LAYOUTS.find((l) => l.id === lid);
setLayoutId(lid);
setSlots(L.cells.map((_, i) => seeds[i] || null));
st.setMergeImages(null);
} else {
setLayoutId('2h');
setSlots([image, null]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [image && image.path]);
// 检查模型 KEY 是否已配置
useEffect(() => {
settingsAPI.getSettings()
.then((d) => setKeyReady(!!(d.online && d.online.configured)))
.catch(() => setKeyReady(null));
}, []);
// 退出时清掉未消费的种子,避免下次误触发
useEffect(() => () => useUIStore.getState().setMergeImages(null), []);
const changeLayout = useCallback((id) => {
setLayoutId(id);
const L = LAYOUTS.find((l) => l.id === id);
setSlots((prev) => L.cells.map((_, i) => prev[i] || null));
}, []);
// ---------- 图库选择器 ----------
const loadPicker = useCallback(async (offset, kw) => {
setPickLoading(true);
try {
const params = { offset, limit: 48 };
if (kw && kw.trim()) params.keywords = kw.trim();
const r = await imageAPI.search(libraryId, params);
setPickImages((prev) => (offset === 0 ? r.images : [...prev, ...r.images]));
setPickOffset(offset + (r.images ? r.images.length : 0));
setPickHasMore(!!r.hasMore);
} catch (e) {
setStatus('加载图库失败: ' + (e.message || ''));
} finally {
setPickLoading(false);
}
}, [libraryId, setStatus]);
const openPicker = (idx) => {
setPickerFor(idx);
setPickQuery('');
setPickImages([]);
setPickOffset(0);
loadPicker(0, '');
};
const pickSearch = () => {
setPickImages([]);
loadPicker(0, pickQuery);
};
const assignSlot = (rec) => {
setSlots((prev) => {
const next = [...prev];
next[pickerFor] = rec;
return next;
});
setPickerFor(null);
};
// ---------- 合成渲染 ----------
const doRender = useCallback(async (slotList) => {
const cells = layout.cells;
const list = slotList || slots;
const usable = list.filter(Boolean);
if (usable.length < 2) {
setStatus('至少需要 2 张图片才能合拼');
return;
}
let W, H;
if (layout.aspect >= 1) { W = 2000; H = Math.round(2000 / layout.aspect); }
else { H = 2000; W = Math.round(2000 * layout.aspect); }
const off = document.createElement('canvas');
off.width = W;
off.height = H;
const ctx = off.getContext('2d');
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, W, H);
const g = gap;
try {
let done = 0;
for (let i = 0; i < cells.length; i++) {
const rec = list[i];
if (!rec) continue;
done += 1;
setBusy(`合拼生成中 ${done}/${usable.length}`);
const [cx, cy, cw, ch] = cells[i];
const x = cx * W + g / 2;
const y = cy * H + g / 2;
const w = cw * W - g;
const h = ch * H - g;
const im = await loadImg(imageAPI.getOriginalUrl(libraryId, rec.path));
const s = Math.max(w / im.width, h / im.height);
const dw = im.width * s;
const dh = im.height * s;
ctx.save();
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.clip();
ctx.drawImage(im, x + (w - dw) / 2, y + (h - dh) / 2, dw, dh);
ctx.restore();
im.onload = null;
im.src = '';
}
const blob = await new Promise((res, rej) =>
off.toBlob((b) => (b ? res(b) : rej(new Error('画布导出失败'))), 'image/png')
);
await onMerge(blob);
setStatus(`合拼完成(${usable.length} 张 · ${W}×${H}),可继续编辑后保存`);
} catch (e) {
setStatus('合拼失败: ' + (e.message || ''));
} finally {
setBusy('');
}
}, [layout, slots, gap, libraryId, onMerge, setStatus, setBusy]);
// ---------- AI 自动找相似图并合拼 ----------
const aiAutoMerge = async () => {
const emptyIdx = slots.map((s, i) => (s ? null : i)).filter((i) => i !== null);
if (!emptyIdx.length) {
return doRender(slots);
}
const seedRec = slots.find(Boolean) || image;
if (keyReady === false) {
setStatus('未配置模型 KEY:请到 设置 → OCR 识别 填写线上模型接口和 KEY');
return;
}
setBusy('AI 正在图库中找相似图');
try {
const resp = await fetch('/api/edit/find-similar', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `*** ${getToken()}`
},
body: JSON.stringify({
libraryId,
seedPath: seedRec.path,
count: emptyIdx.length,
excludePaths: slots.filter(Boolean).map((s) => s.path)
})
});
const j = await resp.json().catch(() => ({}));
if (!resp.ok) {
throw new Error((j.error && j.error.message) || `请求失败 (${resp.status})`);
}
const next = [...slots];
(j.images || []).forEach((img, k) => {
if (k < emptyIdx.length) next[emptyIdx[k]] = img;
});
setSlots(next);
setStatus(`AI 找到 ${(j.images || []).length} 张相似图,正在合拼…`);
await doRender(next);
} catch (e) {
setStatus('AI 合拼失败: ' + (e.message || ''));
setBusy('');
}
};
return (
<div className="space-y-3">
{/* 布局模板 */}
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300">合拼布局</div>
<div className="grid grid-cols-2 gap-1.5">
{LAYOUTS.map((L) => {
const active = L.id === layoutId;
return (
<button
key={L.id}
onClick={() => changeLayout(L.id)}
className={`p-1.5 rounded-lg border transition-colors ${
active
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/30'
: 'border-gray-200 dark:border-gray-600 hover:border-blue-300'
}`}
>
<div
className="relative w-full bg-gray-100 dark:bg-gray-700 rounded overflow-hidden"
style={{ paddingBottom: `${(1 / L.aspect) * 100}%` }}
>
{L.cells.map((c, i) => (
<span
key={i}
className={`absolute ${active ? 'bg-blue-400' : 'bg-gray-300 dark:bg-gray-500'}`}
style={{
left: `${c[0] * 100}%`,
top: `${c[1] * 100}%`,
width: `${c[2] * 100}%`,
height: `${c[3] * 100}%`,
border: '1px solid rgba(255,255,255,0.85)',
boxSizing: 'border-box'
}}
/>
))}
</div>
<div className={`text-[10px] text-center mt-1 ${active ? 'text-blue-600 dark:text-blue-400' : 'text-gray-500'}`}>
{L.name} · {L.cells.length}图
</div>
</button>
);
})}
</div>
{/* 槽位 */}
<div className="flex items-center justify-between">
<div className="text-xs font-semibold text-gray-600 dark:text-gray-300">图片槽位</div>
<div className="text-[10px] text-gray-400">{filled}/{layout.cells.length} 已选</div>
</div>
<div className="grid grid-cols-3 gap-1.5">
{layout.cells.map((_, i) => {
const rec = slots[i];
return (
<div key={i} className="relative group aspect-square">
<button
onClick={() => openPicker(i)}
className="w-full h-full rounded border border-dashed border-gray-300 dark:border-gray-600 overflow-hidden hover:border-blue-400 transition-colors flex items-center justify-center bg-gray-50 dark:bg-gray-700/50"
title={rec ? '点击换图' : '点击从图库选图'}
>
{rec ? (
<img src={thumbUrl(libraryId, rec)} alt="" className="w-full h-full object-cover" />
) : (
<span className="text-gray-400 text-lg">+</span>
)}
</button>
{rec && (
<button
onClick={() => setSlots((prev) => { const n = [...prev]; n[i] = null; return n; })}
className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-red-500 text-white items-center justify-center hidden group-hover:flex leading-none text-[10px]"
title="清空此槽"
>
<X className="w-3 h-3" />
</button>
)}
</div>
);
})}
</div>
{/* 间距 */}
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 dark:text-gray-400">图片间距</span>
<div className="flex gap-1">
{GAP_OPTIONS.map((o) => (
<button
key={o.value}
onClick={() => setGap(o.value)}
className={`px-2 py-0.5 rounded text-[11px] border transition-colors ${
gap === o.value
? 'border-blue-500 text-blue-600 bg-blue-50 dark:bg-blue-900/30'
: 'border-gray-200 dark:border-gray-600 text-gray-500'
}`}
>
{o.label}
</button>
))}
</div>
</div>
{/* AI 自动合拼 */}
<button
onClick={aiAutoMerge}
disabled={filled < 1}
className="w-full py-2 rounded-lg bg-gradient-to-r from-violet-500 to-fuchsia-500 text-white text-sm hover:opacity-90 disabled:opacity-50 transition-opacity flex items-center justify-center gap-1.5"
>
<Sparkles className="w-4 h-4" />
AI 自动找相似图并合拼
</button>
{keyReady === false && (
<p className="text-[11px] text-amber-600 dark:text-amber-400 leading-relaxed">
未配置模型 KEY:到 设置 → OCR 识别 填写线上模型接口和 API Key 后,AI 可自动从图库找相似图。
</p>
)}
<p className="text-[11px] text-gray-400 leading-relaxed">
「AI 自动合拼」以第 1 张为参考,从图库找相似图填满空槽并直接生成;也可手动点槽选图后点下方按钮生成。
</p>
<button
onClick={() => doRender(slots)}
disabled={filled < 2}
className="w-full py-2 rounded-lg bg-blue-600 text-white text-sm hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
生成合拼({filled} 张)
</button>
{/* 图库选择器 */}
{pickerFor !== null && (
<div
className="fixed inset-0 z-[60] bg-black/60 flex items-center justify-center p-4"
onClick={() => setPickerFor(null)}
>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[80vh] flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center gap-2 px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<span className="text-sm font-medium text-gray-700 dark:text-gray-200 flex-shrink-0">
选择图片(第 {pickerFor + 1} 格)
</span>
<input
value={pickQuery}
onChange={(e) => setPickQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && pickSearch()}
placeholder="搜索文件名…"
className="flex-1 min-w-0 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-2 py-1.5 outline-none focus:border-blue-400"
/>
<button
onClick={pickSearch}
className="px-3 py-1.5 text-sm rounded bg-blue-600 text-white hover:bg-blue-700 flex-shrink-0"
>
搜索
</button>
<button
onClick={() => setPickerFor(null)}
className="p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 flex-shrink-0"
>
<X className="w-4 h-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-3">
<div className="grid grid-cols-4 sm:grid-cols-6 gap-2">
{pickImages.map((img) => (
<button
key={img.path}
onClick={() => assignSlot(img)}
className="aspect-square rounded overflow-hidden border border-gray-200 dark:border-gray-600 hover:border-blue-500 hover:ring-1 hover:ring-blue-500 transition-all"
title={img.filename}
>
<img
src={thumbUrl(libraryId, img)}
alt={img.filename}
loading="lazy"
className="w-full h-full object-cover"
/>
</button>
))}
{!pickImages.length && !pickLoading && (
<div className="col-span-full text-center text-sm text-gray-400 py-8">没有找到图片</div>
)}
{pickLoading && (
<div className="col-span-full flex items-center justify-center gap-2 text-sm text-gray-400 py-8">
<Loader2 className="w-4 h-4 animate-spin" /> 加载中…
</div>
)}
</div>
</div>
{pickHasMore && (
<div className="px-4 py-2.5 border-t border-gray-200 dark:border-gray-700 text-center">
<button
onClick={() => loadPicker(pickOffset, pickQuery)}
disabled={pickLoading}
className="px-4 py-1.5 text-sm rounded border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50"
>
加载更多(已 {pickImages.length} 张)
</button>
</div>
)}
</div>
</div>
)}
</div>
);
}
+15 -3
View File
@@ -15,7 +15,7 @@ const logger = createLogger('RightPanel');
function RightPanel() {
const { currentLibraryId } = useLibraryStore();
const { selectedImage, selectedImages, selectedFolder, selectedFolderItem, images, setSelectedImage, setSelectedImages, updateImage } = useImageStore();
const { setMobileView, isResizingPanels, resizingSide } = useUIStore();
const { setMobileView, isResizingPanels, resizingSide, setEditingImage } = useUIStore();
const { copyToClipboard } = useClipboardStore();
const [isMobile, setIsMobile] = useState(false);
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
@@ -423,7 +423,7 @@ function RightPanel() {
}
// Handle both forward and backslash
const filename = thumbnailPath.replace(/\\/g, '/').split('/').pop();
return imageAPI.getThumbnailUrl(currentLibraryId, filename);
return imageAPI.getThumbnailUrl(currentLibraryId, filename, selectedImage?.modifiedAt);
};
const getOriginalUrl = () => {
@@ -920,7 +920,7 @@ function RightPanel() {
setExportProgress(100);
const link = document.createElement('a');
link.href = URL.createObjectURL(zipBlob);
link.download = `FlyPic_导出_${imagesToExport.length}张_${Date.now()}.zip`;
link.download = `牛图_导出_${imagesToExport.length}张_${Date.now()}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
@@ -1563,6 +1563,18 @@ function RightPanel() {
{/* Actions - 仅桌面端显示 */}
{!isMobile && (
<div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2 flex-shrink-0">
{/* 编辑图片(单选时) */}
{!isMultiSelect && selectedImage && (
<button
onClick={() => setEditingImage(selectedImage)}
className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
编辑图片
</button>
)}
{/* 复制按钮 */}
<button
onClick={copyMultipleImages}
+174 -9
View File
@@ -1,8 +1,8 @@
import { useState, useEffect } from 'react';
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink } from 'lucide-react';
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink, Wand2 } from 'lucide-react';
import { settingsAPI } from '../api';
const APP_VERSION = 'v1.2.0';
const APP_VERSION = 'v1.3.0';
const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
/**
@@ -10,20 +10,26 @@ const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
* - OCR 识别:本地 tesseract / 线上接口切换、线上参数、测试
* - 关于:版本号 / 开源地址
*/
export default function SettingsModal({ open, onClose, versionLabel }) {
export default function SettingsModal({ open, onClose, versionLabel, initialTab }) {
const [active, setActive] = useState('ocr');
const [cfg, setCfg] = useState(null); // { provider, online:{url,model,apiKeyMasked} }
const [apiKeyInput, setApiKeyInput] = useState(''); // 新密钥(留空=保持原密钥)
const [ig, setIg] = useState(null); // imagegen 配置
const [igNewKey, setIgNewKey] = useState(''); // NewAPI 新密钥
const [igCustomKey, setIgCustomKey] = useState(''); // 自定义提供商新密钥
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [msg, setMsg] = useState(null); // { type, text }
useEffect(() => {
if (!open) return;
if (initialTab) setActive(initialTab);
setMsg(null);
setApiKeyInput('');
setIgNewKey('');
setIgCustomKey('');
settingsAPI.getSettings()
.then((d) => setCfg({
.then((d) => { setCfg({
provider: d?.provider || 'local',
online: {
url: d?.online?.url || 'https://ai.88531.cn/v1',
@@ -31,7 +37,21 @@ export default function SettingsModal({ open, onClose, versionLabel }) {
apiKeyMasked: d?.online?.apiKeyMasked || ''
},
telemetry: d?.telemetry !== false
}))
});
setIg({
provider: d?.imagegen?.provider || 'newapi',
newapi: {
url: d?.imagegen?.newapi?.url || 'http://192.168.68.19:3099/v1',
apiKeyMasked: d?.imagegen?.newapi?.apiKeyMasked || '',
hasKey: !!d?.imagegen?.newapi?.hasKey
},
custom: {
url: d?.imagegen?.custom?.url || '',
model: d?.imagegen?.custom?.model || '',
apiKeyMasked: d?.imagegen?.custom?.apiKeyMasked || ''
}
});
})
.catch((e) => setMsg({ type: 'error', text: '读取设置失败: ' + (e.data?.message || e.message) }));
}, [open]);
@@ -51,11 +71,42 @@ export default function SettingsModal({ open, onClose, versionLabel }) {
model: cfg.online.model,
apiKey: apiKeyInput // 空字符串 = 保留原密钥
}
}
},
...(ig ? {
imagegen: {
provider: ig.provider,
newapi: {
url: ig.newapi.url,
apiKey: igNewKey || '' // 空 = 保持原密钥
},
custom: {
url: ig.custom.url,
model: ig.custom.model,
apiKey: igCustomKey || ''
}
}
} : {})
};
const data = await settingsAPI.updateSettings(payload);
setCfg((c) => ({ ...(c || {}), ...data, online: { ...(c?.online || {}), ...(data?.online || {}) } }));
if (data?.imagegen) {
setIg({
provider: data.imagegen.provider || 'newapi',
newapi: {
url: data.imagegen.newapi?.url || '',
apiKeyMasked: data.imagegen.newapi?.apiKeyMasked || '',
hasKey: !!data.imagegen.newapi?.hasKey
},
custom: {
url: data.imagegen.custom?.url || '',
model: data.imagegen.custom?.model || '',
apiKeyMasked: data.imagegen.custom?.apiKeyMasked || ''
}
});
}
setApiKeyInput('');
setIgNewKey('');
setIgCustomKey('');
setMsg({ type: 'ok', text: '已保存,新配置立即生效' });
} catch (e) {
setMsg({ type: 'error', text: '保存失败: ' + (e.data?.message || e.message) });
@@ -90,6 +141,7 @@ export default function SettingsModal({ open, onClose, versionLabel }) {
const menus = [
{ key: 'ocr', label: 'OCR 识别', icon: ScanText },
{ key: 'aigen', label: 'AI 生图', icon: Wand2 },
{ key: 'about', label: '关于', icon: Info }
];
@@ -122,7 +174,7 @@ export default function SettingsModal({ open, onClose, versionLabel }) {
<div className="flex-1 p-6 overflow-y-auto">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
{active === 'ocr' ? 'OCR 识别设置' : '关于'}
{active === 'ocr' ? 'OCR 识别设置' : active === 'aigen' ? 'AI 生图设置' : '关于'}
</h2>
<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" />
@@ -230,6 +282,119 @@ export default function SettingsModal({ open, onClose, versionLabel }) {
</div>
)}
{active === 'aigen' && cfg && ig && (
<div className="space-y-5">
<p className="text-xs text-gray-500 dark:text-gray-400">
AI 生图默认走内置 NewAPI(Pollinations + CF Workers AI 两个生图渠道);也可以切换到自己的 OpenAI 兼容提供商。密钥只保存在本机,不出服务器。
</p>
<div>
<div className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">生图通道</div>
<div className="space-y-2">
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
<input
type="radio"
className="mt-0.5"
checked={ig.provider === 'newapi'}
onChange={() => setIg((v) => ({ ...v, provider: 'newapi' }))}
/>
<span>
<span className="block text-sm font-medium text-gray-900 dark:text-white">内置 NewAPI(推荐)</span>
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">
Pollinations / CF Workers AI 两大生图模型,开箱即用
{ig.newapi.hasKey ? ',Key 已配置' : ',未配置 Key'}
</span>
</span>
</label>
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
<input
type="radio"
className="mt-0.5"
checked={ig.provider === 'custom'}
onChange={() => setIg((v) => ({ ...v, provider: 'custom' }))}
/>
<span>
<span className="block text-sm font-medium text-gray-900 dark:text-white">自定义提供商</span>
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">任意 OpenAI 兼容 /v1/images/generations 接口(OpenAI、Stability、中转站等)</span>
</span>
</label>
</div>
</div>
{ig.provider === 'newapi' && (
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址</label>
<input
type="text"
value={ig.newapi.url}
onChange={(e) => setIg((v) => ({ ...v, newapi: { ...v.newapi, url: e.target.value } }))}
placeholder="http://192.168.68.19:3099/v1(默认)"
className="w-full px-3 py-2 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"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">API Key</label>
<input
type="password"
value={igNewKey}
onChange={(e) => setIgNewKey(e.target.value)}
placeholder={ig.newapi.apiKeyMasked ? `已配置(${ig.newapi.apiKeyMasked}),留空保持不变` : 'NewAPI 令牌(留空则用服务器环境变量)'}
className="w-full px-3 py-2 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"
/>
</div>
</div>
)}
{ig.provider === 'custom' && (
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址</label>
<input
type="text"
value={ig.custom.url}
onChange={(e) => setIg((v) => ({ ...v, custom: { ...v.custom, url: e.target.value } }))}
placeholder="https://api.openai.com/v1"
className="w-full px-3 py-2 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"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">模型名称</label>
<input
type="text"
value={ig.custom.model}
onChange={(e) => setIg((v) => ({ ...v, custom: { ...v.custom, model: e.target.value } }))}
placeholder="gpt-image-1 / flux-dev / stable-diffusion-xl ..."
className="w-full px-3 py-2 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"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">API Key</label>
<input
type="password"
value={igCustomKey}
onChange={(e) => setIgCustomKey(e.target.value)}
placeholder={ig.custom.apiKeyMasked ? `已配置(${ig.custom.apiKeyMasked}),留空保持不变` : 'sk-...'}
className="w-full px-3 py-2 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"
/>
</div>
</div>
)}
<div className="flex items-center gap-3">
<button
onClick={handleSave}
disabled={saving}
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50"
>
<Save className="w-4 h-4" />
{saving ? '保存中...' : '保存'}
</button>
<span className="text-xs text-gray-400 dark:text-gray-500">保存后立即生效,无需重启</span>
</div>
</div>
)}
{active === 'about' && (
<div className="space-y-4 text-sm">
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">
@@ -238,7 +403,7 @@ export default function SettingsModal({ open, onClose, versionLabel }) {
</div>
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">
<span className="text-gray-500 dark:text-gray-400">项目名称</span>
<span className="font-medium text-gray-900 dark:text-white">FlyPic 素材库</span>
<span className="font-medium text-gray-900 dark:text-white">牛图 素材库</span>
</div>
<div className="flex items-center justify-between py-2">
<span className="text-gray-500 dark:text-gray-400">开源地址</span>
@@ -254,7 +419,7 @@ export default function SettingsModal({ open, onClose, versionLabel }) {
</a>
</div>
<p className="text-xs text-gray-400 dark:text-gray-500 pt-2">
FlyPic 基于 ZangXincz/FlyPic 二次开发,修复多项问题并新增 OCR 图内文字搜索、线上 OCR、授权系统接入等能力。
牛图(FlyPic)基于 ZangXincz/FlyPic 二次开发,修复多项问题并新增 OCR 图内文字搜索、线上 OCR、授权系统接入等能力。
</p>
</div>
)}
+148 -6
View File
@@ -1,5 +1,5 @@
import { useState, useMemo, useEffect, useRef, useCallback } from 'react';
import { Folder, Search, ChevronRight, ChevronDown, X, Trash2, ChevronsRight, ChevronsDown } from 'lucide-react';
import { Folder, Search, ChevronRight, ChevronDown, X, Trash2, ChevronsRight, ChevronsDown, FolderPlus, Star } from 'lucide-react';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { useScanStore } from '../stores/useScanStore';
@@ -11,6 +11,7 @@ import ContextMenu, { menuItems } from './ContextMenu';
import UndoToast from './UndoToast';
import FolderSelector from './FolderSelector';
import ConflictDialog from './ConflictDialog';
import BatchWatermarkModal from './BatchWatermarkModal';
import { createLogger } from '../utils/logger';
const logger = createLogger('Sidebar');
@@ -37,7 +38,7 @@ function Sidebar() {
expandLibrarySelector,
resetExpandLibrarySelector
} = useLibraryStore();
const { folders, selectedFolder, totalImageCount, setSelectedFolder, setSelectedFolderItem } = useImageStore();
const { folders, selectedFolder, totalImageCount, favoritesView, setFavoritesView, favoriteTick, setSelectedFolder, setSelectedFolderItem, bumpRefresh } = useImageStore();
const { isScanning } = useScanStore();
const [showAddLibrary, setShowAddLibrary] = useState(false);
@@ -51,6 +52,8 @@ function Sidebar() {
const [missingLibrary, setMissingLibrary] = useState(null); // 切换时发现的丢失素材库
const [isLibrarySelectorOpen, setIsLibrarySelectorOpen] = useState(false); // 素材库选择器展开状态
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, folder: null });
// 批量水印弹窗 { mode: 'add'|'remove', folder }
const [batchWatermark, setBatchWatermark] = useState(null);
const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
const [dragOverFolder, setDragOverFolder] = useState(null); // 拖拽悬停的文件夹
@@ -95,6 +98,28 @@ function Sidebar() {
setUndoToast({ isVisible: false, message: '', count: 0 });
}, [selectedFolder]);
// 收藏数量角标(素材库切换、收藏状态变化时刷新)
const [favoriteCount, setFavoriteCount] = useState(0);
useEffect(() => {
if (!currentLibraryId) return;
let alive = true;
imageAPI.getCount(currentLibraryId, { favorite: 1 })
.then(res => { if (alive) setFavoriteCount(res?.count ?? 0); })
.catch(() => { /* 角标失败不影响主功能 */ });
return () => { alive = false; };
}, [currentLibraryId, favoriteTick]);
// 点击「我的收藏」:进入收藏视图(不选中任何文件夹)
const handleFavoritesClick = () => {
onUserActionStart();
setSelectedFolder(null);
setSelectedFolderItem(null);
const { clearSelection } = useImageStore.getState();
clearSelection();
setFavoritesView(true);
logger.user('打开我的收藏');
};
// 响应全局状态:显示新建素材库表单
useEffect(() => {
if (showAddLibraryForm) {
@@ -825,6 +850,45 @@ function Sidebar() {
}, 50);
};
// 完成创建文件夹(回车/失焦提交)
const handleFinishCreateFolder = async () => {
if (!creatingFolder) return;
const name = (newFolderName || '').trim();
if (!name) {
handleCancelCreateFolder();
return;
}
if (!currentLibraryId) {
handleCancelCreateFolder();
return;
}
// 拼接完整相对路径
const parent = creatingFolder.parentPath || '';
const fullPath = parent ? `${parent}/${name}` : name;
try {
await fileAPI.createFolder(currentLibraryId, fullPath);
logger.file(`✅ 创建文件夹: ${fullPath}`);
// 刷新文件夹树
const foldersRes = await imageAPI.getFolders(currentLibraryId);
const { setFolders } = useImageStore.getState();
setFolders(foldersRes.folders);
} catch (error) {
logger.error('❌ 创建文件夹失败:', error);
alert(error?.data?.error || error?.message || '创建文件夹失败');
} finally {
setCreatingFolder(null);
setNewFolderName('');
}
};
// 取消创建文件夹(Esc)
const handleCancelCreateFolder = useCallback(() => {
setCreatingFolder(null);
setNewFolderName('');
}, []);
const handleAddLibrary = async () => {
// 扫描期间禁止添加素材库
if (isScanning()) {
@@ -930,9 +994,9 @@ function Sidebar() {
'⚠️ 文件夹权限不足\n\n' +
errorMessage + '\n\n' +
'操作步骤:\n' +
'1. 应用中心找到 FlyPic 应用\n' +
'1. 应用中心找到 牛图 应用\n' +
'2. 点击 应用设置\n' +
'3. 将该文件夹添加到 FlyPic 应用的读写权限'
'3. 将该文件夹添加到 牛图 应用的读写权限'
);
} else {
alert('添加素材库失败: ' + errorMessage);
@@ -1436,6 +1500,19 @@ function Sidebar() {
onOpenOther={handleMissingOpenOther}
onCreateNew={handleMissingCreateNew}
/>
{/* 批量水印弹窗(加水印 / 去水印) */}
<BatchWatermarkModal
isOpen={!!batchWatermark}
mode={batchWatermark?.mode}
folder={batchWatermark?.folder}
libraryId={currentLibraryId}
onClose={() => setBatchWatermark(null)}
onFinished={(result) => {
logger.file(`批量水印任务完成: ${batchWatermark?.folder}`, result);
bumpRefresh(); // 让图片区重新加载(覆盖模式下缩略图已更新)
}}
/>
{/* Library Management */}
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
@@ -1593,17 +1670,50 @@ function Sidebar() {
<ChevronsDown className="w-4 h-4" />
)}
</button>
<button
onClick={() => handleStartCreateFolder('child', selectedFolder || '')}
className="px-2 py-1.5 border border-gray-300 dark:border-gray-600 rounded hover:bg-green-100 dark:hover:bg-green-900 text-green-600 dark:text-green-400 transition-colors"
title="新建文件夹(在当前文件夹下)"
>
<FolderPlus className="w-4 h-4" />
</button>
</div>
{/* 根级新建文件夹输入框(当前未选中文件夹时挂在树顶) */}
{creatingFolder && creatingFolder.type === 'child' && !creatingFolder.basePath && (
<div className="flex items-center py-1.5 rounded bg-green-50 dark:bg-green-900/30 px-1">
<div className="w-5 mr-1" />
<Folder className="w-4 h-4 mr-2 text-green-500 flex-shrink-0" />
<input
ref={newFolderInputRef}
type="text"
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleFinishCreateFolder();
} else if (e.key === 'Escape') {
e.preventDefault();
handleCancelCreateFolder();
}
}}
onBlur={handleFinishCreateFolder}
onClick={(e) => e.stopPropagation()}
autoFocus
className="flex-1 text-sm text-gray-700 dark:text-gray-300 bg-transparent border-none outline-none focus:outline-none underline decoration-2 decoration-green-500 underline-offset-2"
/>
</div>
)}
</div>
<div className="space-y-1">
{/* 全部图片选项 */}
<div
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${selectedFolder === null
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${selectedFolder === null && !favoritesView
? 'bg-blue-50 dark:bg-blue-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
onClick={() => setSelectedFolder(null)}
onClick={() => { setFavoritesView(false); setSelectedFolder(null); }}
>
<div className="w-5 mr-1" />
<Folder className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
@@ -1615,6 +1725,28 @@ function Sidebar() {
</span>
</div>
{/* 我的收藏 */}
<div
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${favoritesView
? 'bg-amber-50 dark:bg-amber-900/30'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
onClick={handleFavoritesClick}
title="查看我收藏的图片"
>
<div className="w-5 mr-1" />
<Star
size={16}
className={`mr-2 flex-shrink-0 ${favoritesView ? 'text-amber-500 fill-amber-500' : 'text-amber-500'}`}
/>
<span className={`text-sm font-medium flex-1 ${favoritesView ? 'text-amber-700 dark:text-amber-300' : 'text-gray-700 dark:text-gray-200'}`}>
我的收藏
</span>
<span className="text-xs text-gray-500 dark:text-gray-300 ml-2">
{favoriteCount}
</span>
</div>
{/* 分隔线 */}
{(filteredFolders.length > 0 || folders.length > 0) && (
<div className="h-px bg-gray-200 dark:bg-gray-700 my-2" />
@@ -1646,6 +1778,16 @@ function Sidebar() {
menuItems.divider(),
menuItems.rename(() => handleStartRenameFolder(contextMenu.folder)),
menuItems.move(() => handleMoveFolderClick(contextMenu.folder.path)),
menuItems.divider(),
menuItems.batchAddWatermark(() => {
setContextMenu({ isOpen: false, position: null, folder: null });
setBatchWatermark({ mode: 'add', folder: contextMenu.folder.path });
}),
menuItems.batchRemoveWatermark(() => {
setContextMenu({ isOpen: false, position: null, folder: null });
setBatchWatermark({ mode: 'remove', folder: contextMenu.folder.path });
}),
menuItems.divider(),
menuItems.delete(async () => {
setContextMenu({ isOpen: false, position: null, folder: null });
await handleDeleteFolder(contextMenu.folder.path);
+98
View File
@@ -0,0 +1,98 @@
/**
* AI 生图 · 常用热门提示词库
* 分类 + 预设提示词(中英混合,flux 系模型对英文提示词效果更稳)
* 点击条目 = 追加/替换输入框内容
*/
export const PROMPT_CATEGORIES = [
{
key: 'hot',
label: '🔥 热门',
prompts: [
{ name: '赛博朋克城市夜景', prompt: 'cyberpunk city at night, neon lights, rain reflections, flying cars, ultra detailed, cinematic lighting' },
{ name: '治愈系猫咪', prompt: 'a fluffy cat sitting on windowsill, warm afternoon sunlight, soft focus, cozy atmosphere, photorealistic' },
{ name: '水晶球微缩世界', prompt: 'miniature world inside a glass snow globe on wooden table, macro photography, dreamy bokeh, studio lighting' },
{ name: '复古胶片人像', prompt: 'vintage film portrait, kodak portra 400, soft natural light, nostalgic mood, grain texture' },
{ name: '极简几何壁纸', prompt: 'minimalist geometric wallpaper, pastel gradient colors, clean shapes, flat design, 4k' }
]
},
{
key: 'portrait',
label: '👤 头像人像',
prompts: [
{ name: '动漫男头', prompt: 'anime boy avatar, short black hair, hoodie, city background at dusk, detailed illustration, vibrant colors' },
{ name: '动漫女头', prompt: 'anime girl avatar, long silver hair, flower crown, soft pastel colors, clean lineart, studio ghibli style' },
{ name: '3D 卡通头像', prompt: '3D cartoon avatar of a young man, Pixar style, round face, big eyes, soft studio lighting, plain background' },
{ name: '写真级人像', prompt: 'professional headshot portrait, shallow depth of field, natural window light, high detail skin texture, 85mm lens' },
{ name: '像素风头像', prompt: 'pixel art avatar, 64x64, retro game style, bold outlines, limited palette, cute expression' }
]
},
{
key: 'wallpaper',
label: '🖼 壁纸风景',
prompts: [
{ name: '雪山日出', prompt: 'snow mountain range at sunrise, golden alpenglow, crystal clear lake reflection, ultra wide angle, 8k landscape' },
{ name: '海上星河', prompt: 'milky way over calm ocean, starry night, long exposure photography, deep blue tones, tranquil scene' },
{ name: '梯田晨雾', prompt: 'terraced rice fields with morning mist, layered mountains, traditional chinese landscape painting mood, aerial view' },
{ name: '梦幻森林', prompt: 'enchanted forest with glowing mushrooms and fireflies, volumetric light rays, fantasy atmosphere, highly detailed' },
{ name: '沙漠驼队', prompt: 'camel caravan crossing golden sand dunes at sunset, long shadows, warm tones, national geographic style' }
]
},
{
key: 'anime',
label: '✨ 动漫插画',
prompts: [
{ name: '樱花下的少女', prompt: 'anime girl under cherry blossom tree, petals falling, spring breeze, pastel colors, detailed anime illustration' },
{ name: '机甲战士', prompt: 'giant mecha robot standing in ruined city, dramatic angle, sci-fi anime style, detailed mechanical parts, dynamic lighting' },
{ name: '魔法使', prompt: 'young wizard casting spell, glowing runes, dark library background, fantasy anime illustration, vibrant magic effects' },
{ name: '校园日常', prompt: 'anime scene of students walking home at sunset, warm orange sky, slice of life, clean lineart, makoto shinkai style' },
{ name: '和风少女', prompt: 'girl in kimono holding wagashi, traditional japanese room, tatami, soft light, detailed anime art' }
]
},
{
key: 'commerce',
label: '🛍 电商海报',
prompts: [
{ name: '产品主图', prompt: 'product photography of a perfume bottle on marble pedestal, soft gradient background, studio lighting, luxury feel, high-end commercial shot' },
{ name: '美食海报', prompt: 'gourmet burger with melted cheese, steam rising, dark moody background, commercial food photography, appetizing, sharp detail' },
{ name: '双十一促销', prompt: 'e-commerce sale banner, red and gold color scheme, floating gift boxes and confetti, modern 3d render, festive atmosphere' },
{ name: '化妆品展示', prompt: 'cosmetic serum bottle surrounded by fresh flowers and water drops, clean white background, fresh and natural, commercial photo' },
{ name: '数码新品', prompt: 'smartphone floating above glowing platform, tech product render, blue and purple neon accents, futuristic commercial style' }
]
},
{
key: 'icon3d',
label: '🧊 图标3D',
prompts: [
{ name: '3D 立体图标', prompt: '3d icon of a treasure chest, glossy material, soft shadows, pastel gradient background, clay render style, cute and round' },
{ name: '玻璃质感', prompt: 'glassmorphism 3d icon of cloud storage, translucent frosted glass, floating, soft studio light, clean background' },
{ name: '卡通食物', prompt: 'cute 3d icon of a ramen bowl, kawaii style, thick outlines, vibrant colors, glossy plastic material' },
{ name: '徽章印章', prompt: '3d golden badge icon with star, metallic material, embossed, dark blue background, premium look' },
{ emoji: '🎮', name: '游戏手柄', prompt: '3d gamepad icon, retro controller, matte plastic material, playful colors, soft ambient occlusion, icon design' }
]
},
{
key: 'art',
label: '🎨 艺术风格',
prompts: [
{ name: '浮世绘海浪', prompt: 'great wave in ukiyo-e style, hokusai inspired, woodblock print texture, indigo blue palette, traditional japanese art' },
{ name: '梵高星空', prompt: 'starry night style painting, swirling sky, thick brushstrokes, post-impressionism, oil painting texture' },
{ name: '水彩花卉', prompt: 'delicate watercolor flowers, loose brushstrokes, soft edges, white background, botanical illustration style' },
{ name: '低多边形', prompt: 'low poly landscape with pine forest and mountains, faceted geometry, vibrant sunset colors, digital art' },
{ name: '水墨仙鹤', prompt: 'chinese ink wash painting of crane flying over lotus, minimal brush strokes, elegant, rice paper texture' }
]
},
{
key: 'scene',
label: '🏠 室内场景',
prompts: [
{ name: '温馨书房', prompt: 'cozy home library with floor to ceiling bookshelves, leather armchair, warm lamp light, rainy window, photorealistic' },
{ name: '北欧客厅', prompt: 'scandinavian living room, white walls, light wood furniture, large plants, natural daylight, interior design photo' },
{ name: '咖啡角落', prompt: 'small cafe corner with espresso machine, pastries display, morning light through glass, hygge atmosphere' },
{ name: '阁楼卧室', prompt: 'attic bedroom with slanted window, fairy lights, linen bedding, plants, soft morning light, aesthetic photo' },
{ name: '赛博房间', prompt: 'futuristic bedroom with holographic screens, neon strip lights, minimalist furniture, cyberpunk interior' }
]
}
];
export default PROMPT_CATEGORIES;
+7 -5
View File
@@ -28,11 +28,13 @@ export const useImageDelete = () => {
* 快速删除(乐观更新,立即响应)
*/
const handleQuickDelete = useCallback(async () => {
const items = selectedImages.length > 0
? selectedImages.map(img => ({ type: 'file', path: img.path }))
: selectedImage
? [{ type: 'file', path: selectedImage.path }]
: [];
// 并集:selectedImages(ctrl/shift 多选)∪ selectedImage(普通单击)
// 否则「先单击一张再 ctrl 多选」时会漏删单击那张
const union = [...selectedImages];
if (selectedImage && !union.some(img => img.path === selectedImage.path)) {
union.push(selectedImage);
}
const items = union.map(img => ({ type: 'file', path: img.path }));
if (items.length === 0) return;
+1
View File
@@ -50,6 +50,7 @@ export const useInfiniteScroll = () => {
limit: LOAD_CONFIG.pageSize
};
if (selectedFolder) params.folder = selectedFolder;
if (useImageStore.getState().favoritesView) params.favorite = 1;
if (searchKeywords) params.keywords = searchKeywords;
if (filters.formats?.length > 0) params.formats = filters.formats.join(',');
+27 -7
View File
@@ -28,6 +28,7 @@ export const useWaterfallLayout = (images, options = {}) => {
// 使用 ref 记录上次宽度,避免频繁 setState
const lastWidthRef = { current: 0 };
let debounceTimer = null;
let fallbackTimer = null;
const emitSize = (width, height) => {
// 仅当差异超过阈值时更新,减少重算次数
@@ -57,21 +58,37 @@ export const useWaterfallLayout = (images, options = {}) => {
return false;
};
const attachObserver = () => {
if (resizeObserver || !containerRef.current) return;
resizeObserver = new ResizeObserver(() => {
// 拖动时跳过更新,避免频繁重算布局
if (useUIStore.getState().isResizingPanels) return;
measureAndEmit();
});
resizeObserver.observe(containerRef.current);
};
const tryInit = () => {
if (measureAndEmit()) {
// 成功获取宽度,设置 ResizeObserver
if (containerRef.current) {
resizeObserver = new ResizeObserver(() => {
// 拖动时跳过更新,避免频繁重算布局
if (useUIStore.getState().isResizingPanels) return;
measureAndEmit();
});
resizeObserver.observe(containerRef.current);
attachObserver();
if (fallbackTimer) {
clearInterval(fallbackTimer);
fallbackTimer = null;
}
} else if (retryCount < maxRetries) {
// 重试
retryCount++;
requestAnimationFrame(tryInit);
} else if (!fallbackTimer) {
// rAF 重试耗尽后低频轮询兜底,避免 containerWidth 永久卡 0 导致网格空白
fallbackTimer = setInterval(() => {
if (measureAndEmit()) {
attachObserver();
clearInterval(fallbackTimer);
fallbackTimer = null;
}
}, 500);
}
};
@@ -85,6 +102,9 @@ export const useWaterfallLayout = (images, options = {}) => {
if (debounceTimer) {
clearTimeout(debounceTimer);
}
if (fallbackTimer) {
clearInterval(fallbackTimer);
}
};
}, []);
+21 -11
View File
@@ -107,40 +107,50 @@ body {
color: #7a7a7a; /* 占位符颜色调亮 */
}
/* Custom scrollbar */
/* Custom scrollbar(加粗:16px,便于拖动) */
::-webkit-scrollbar {
width: 8px;
height: 8px;
width: 16px;
height: 16px;
}
::-webkit-scrollbar-track {
background: transparent;
background: rgba(0, 0, 0, 0.04);
border-radius: 8px;
}
/* 亮色主题滚动条 */
::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.15); /* 降低不透明度,更柔和 */
border-radius: 4px;
background: rgba(0, 0, 0, 0.3); /* 整条 16px 都是可拖动块 */
border-radius: 8px;
transition: background 0.2s ease;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 0, 0, 0.25); /* 悬停时稍微明显 */
background: rgba(0, 0, 0, 0.5); /* 悬停更明显 */
}
/* Firefox 滚动条 */
* {
scrollbar-width: auto;
scrollbar-color: rgba(0, 0, 0, 0.28) rgba(0, 0, 0, 0.04);
}
/* 暗色主题滚动条 - 护眼优化 */
.dark ::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.03); /* 极淡背景 */
background: rgba(255, 255, 255, 0.05); /* 极淡背景 */
}
.dark ::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15); /* 降低亮度,减少刺激 */
border-radius: 4px;
background: rgba(255, 255, 255, 0.35); /* 提高可见度 */
transition: background 0.2s ease;
}
.dark ::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.25); /* 悬停时更明显 */
background: rgba(255, 255, 255, 0.55); /* 悬停更明显 */
}
.dark * {
scrollbar-color: rgba(255, 255, 255, 0.32) rgba(255, 255, 255, 0.05);
}
/* Toast 滑入动画 */
+23 -4
View File
@@ -20,15 +20,25 @@ export const useImageStore = create((set, get) => ({
// 搜索和过滤
searchKeywords: '',
// 左侧导航「我的收藏」视图(独立于文件夹浏览)
favoritesView: false,
setFavoritesView: (v) => set({ favoritesView: v }),
// 收藏数量变化信号(收藏/取消收藏后 +1,侧栏角标据此刷新)
favoriteTick: 0,
filters: {
formats: [],
sizes: [], // 文件大小范围筛选
orientations: [], // 图片方向筛选(多选): ['horizontal', 'vertical', 'square']
ratings: [], // 评分筛选(多选): [0, 1, 2, 3, 4, 5]
favoriteOnly: false, // 仅看收藏
},
// 原始图片列表(用于生成筛选选项,不受筛选影响)
originalImages: [],
// 列表刷新信号(编辑器另存新图后 +1,MainContent 监听后重新拉取)
refreshTick: 0,
bumpRefresh: () => set((state) => ({ refreshTick: state.refreshTick + 1 })),
// 加载状态
imageLoadingState: {
@@ -74,7 +84,11 @@ export const useImageStore = create((set, get) => ({
// 文件夹操作
setFolders: (folders) => set({ folders }),
setSelectedFolder: (folder) => set({ selectedFolder: folder }),
setSelectedFolder: (folder) => set((state) => ({
selectedFolder: folder,
// 进入任何文件夹即退出「我的收藏」视图;置空(回全部图片)由调用方自行清 favoritesView
favoritesView: folder ? false : state.favoritesView
})),
setSelectedFolderItem: (folderItem) => set({ selectedFolderItem: folderItem }),
@@ -91,7 +105,8 @@ export const useImageStore = create((set, get) => ({
formats: [],
sizes: [],
orientations: [],
ratings: []
ratings: [],
favoriteOnly: false
}
}),
@@ -112,11 +127,15 @@ export const useImageStore = create((set, get) => ({
images: state.images.map(img =>
img.path === oldPath ? { ...img, ...newData } : img
),
originalImages: state.originalImages.map(img =>
originalImages: state.originalImages.map(img =>
img.path === oldPath ? { ...img, ...newData } : img
),
selectedImage: state.selectedImage?.path === oldPath
? { ...state.selectedImage, ...newData }
: state.selectedImage
: state.selectedImage,
// 收藏状态变化 → 通知侧栏刷新收藏角标
favoriteTick: newData && newData.favorite !== undefined
? state.favoriteTick + 1
: state.favoriteTick
}))
}));
+9 -1
View File
@@ -17,7 +17,15 @@ export const useUIStore = create((set) => ({
// 面板调整状态
isResizingPanels: false,
resizingSide: null, // 'left' | 'right' | null
// 图片编辑器(打开的图片记录,null=关闭)
editingImage: null,
setEditingImage: (image) => set({ editingImage: image }),
// 合拼种子图(多选后点「合拼」带入编辑器,null=无)
mergeImages: null,
setMergeImages: (images) => set({ mergeImages: images }),
// 主题操作
setTheme: (theme) => set({ theme }),
+8 -2
View File
@@ -48,13 +48,14 @@ export const matchSizeRange = (sizeKB, range) => {
* @returns {Array} 筛选后的图片列表
*/
export const filterImages = (images, filters) => {
const { formats, sizes, orientations, ratings } = filters;
const { formats, sizes, orientations, ratings, favoriteOnly } = filters;
// 如果没有任何筛选条件,直接返回原始图片
if ((!formats || formats.length === 0) &&
(!sizes || sizes.length === 0) &&
(!orientations || orientations.length === 0) &&
(!ratings || ratings.length === 0)) {
(!ratings || ratings.length === 0) &&
!favoriteOnly) {
return images;
}
@@ -66,6 +67,11 @@ export const filterImages = (images, filters) => {
}
}
// 收藏筛选
if (favoriteOnly) {
if (!img.favorite) return false;
}
// 文件大小筛选
if (sizes && sizes.length > 0) {
const sizeKB = img.size / 1024;
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* FlyPic 前端日志系统
* 牛图(FlyPic)前端日志系统
* 专注于用户操作和UI交互日志
*
* 日志分类: