9 Commits
Author SHA1 Message Date
jinghui 6e086d629d feat(v1.4.8): 搜索结果批量重命名 + 关键词替换模式
- 搜索结果工具条新增「批量重命名搜索结果…」入口(scope=search)
- 后端 rename-preview/start 支持 scope=search:与列表同款模糊匹配(关键词空格分词 AND,filename/OCR LIKE),可选 folder 递归限定
- 新增关键词替换模式:find 关键词 + replace 替换成(留空=删除关键词),不含关键词的文件自动跳过并报告
- 弹窗模式选择改 2x2 网格,搜索范围显示「搜索:关键词」徽标
- 关键词模式隐藏「包含子目录」(搜索范围已含子目录)
2026-11-18 22:57:46 +08:00
jinghui c59791f994 v1.4.7: 类型文案全面去「张」——注册表驱动 countLabel/typeCountsOf,补 design/other 类型行,统计图例按注册表顺序展示 2026-11-18 22:30:57 +08:00
jinghui 58900d0d45 feat(v1.4.6): 文件夹右键批量重命名文件(前缀/后缀/全替换+子目录+实时预览) 2026-11-18 20:57:08 +08:00
jinghui 7d0023949b feat(v1.4.5): 侧栏文件夹按日期倒序,最新文件夹排最前
- FolderModel.getTree() 按文件夹名解析日期倒序排序(兼容 YYYY-MM-DD 与
  YYYYMMDD 混排;纯字符串倒序会把 20261016 压过 2026-11-18,_归档 排最前)
- 解析不出日期的文件夹(_归档、纯数字名)排最后,组内名称倒序
- 子文件夹同样倒序;侧栏与 Dashboard 共用接口同步生效
- 版本 1.4.4 -> 1.4.5
2026-11-18 19:33:29 +08:00
jinghui 9c7c72e3e7 fix: 视频文件右侧面板显示图片信息 — RightPanel 增加视频判定(v1.4.4) 2026-11-18 18:56:30 +08:00
jinghui e17b78cd19 fix(v1.4.3): 视频编辑/AI视频补鉴权头修复[object Object] + 侧栏「全部图片」改「全部」
- VideoEditModal /api/video/edit、AIVideoModal /api/video/aigenerate+task轮询均裸fetch未带Authorization,后端/api全组401 → 补token头
- 错误信息经errText()解析(对象取message兜底状态码),不再显示[object Object]
- MergeCollage拼图找相似接口同样缺token,一并修复
- Sidebar首项文案「全部图片」→「全部」
- 版本4处升v1.4.3
2026-11-18 17:37:06 +08:00
jinghui f07cf7a266 docs: docker run 示例补齐我的文档目录挂载(与compose三挂载对齐) 2026-11-18 16:25:04 +08:00
jinghui 0bbf14f194 fix(v1.4.2): 挂载发布归档目录并中文化路径报错 — compose补挂/vol2视频目录;LibraryService两处Path does not exist改为中文可操作提示(指路volumes挂载);版本4处升v1.4.2 2026-11-18 16:20:52 +08:00
jinghui 87cc9c00a5 fix(v1.4.1): 页面标题改为「牛仔库 - 素材库管理」(去掉『图片』) 2026-11-18 14:16:31 +08:00
28 changed files with 1138 additions and 83 deletions

No files matched your search

+71 -1
View File
@@ -1,8 +1,78 @@
# 更新日志
## 2026-11-18 → v1.4.8
**搜索结果批量改名 + 关键词替换**——搜索出一批文件后直接对命中结果批量改名,支持把文件名中的关键词替换掉:
- ✨ **搜索结果入口**:任意搜索(Header 搜索框,模糊匹配文件名+OCR 文本)后,结果区顶部出现「批量重命名搜索结果…」按钮;打开弹窗头部徽标显示当前搜索词,范围与搜索列表完全一致(选中文件夹时含其子目录,未选中则全库)
- ✨ **新重命名模式「关键词替换」**:找什么→替换成(文件名中所有出现处全部替换);**替换成留空 = 删除该关键词**;不含关键词的文件自动跳过并在结果中报告;预览实时显示替换前后对照
- ✨ 搜索范围与列表同款 `LIKE` 模糊匹配(多关键词 AND、filename+ocr_text),后端 `POST /api/batch/rename-preview` 与 `/start` 新增 `scope='search'` + `keywords` 参数(folder 可不传,传了则按文件夹递归限定范围)
- ✨ 弹窗模式改 2×2 布局(4 种模式);关键词模式下隐藏「包含子目录」开关(搜索范围本身就含子目录);文件夹右键入口的原有三种模式行为不变
- 🛡️ 关键词与替换文本同样走文件名非法字符 `\ / : * ? " < > |` 前后端校验;预览与执行共用同一计划(命中数、跳过原因一致)
- 端到端实测:preview/scope=search 预览命中数、keyword 执行改名+DB path 同步、搜索态按钮与弹窗渲染
## 2026-11-18 → v1.4.7
**文件类型自动识别(通用机制)**——原先统计卡、文件夹卡、多选条等多处硬编码「图片/N 张图片」,库里实际有图片/视频/文档三种类型(356 个文件被显示成「356 图片总数」)。现改为类型注册表驱动,**以后新增文件类型只需在注册表加一行,全站文案与统计自动识别**:
- ✨ 新建 `frontend/src/utils/fileTypes.js` 类型注册表:image→图片/张、video→视频/个、document→文档/个、audio→音频/个,未知类型一律兜底「文件/个」;提供 `typeMeta`(单文件元信息)、`countLabel`(集合计数文案:单一类型→「102 张图片」,混合→「356 个文件」)、`typeLabelOf`(动词名词:复制图片/复制视频/复制文件自动切换)、`typeCountsOf`(从选中项聚合类型计数)
- ✨ 统计卡自动识别:图标与标题按库内实际类型显示(纯图库「图片总数」、混合库「文件总数」),下方分类型图例「图片 102 · 视频 181 · 文档 73」由注册表自动渲染,新类型自动出现
- ✨ 文件夹卡与仪表盘提示句:「X 张图片」→ 按该文件夹实际内容显示(`countLabel`,含子目录分类型聚合,后端 `FolderModel.getTree()` 新增 `_attachTypeCounts`)
- ✨ 后端 `GET /api/image/stats` 新增 `typeCounts` 字段(按 file_type 分组计数)
- ✨ 右侧面板全部计数与动词文案通用化:已选择/基本信息/共同父路径/已复制/复制按钮/导出按钮 —— 消除 v1.4.4 的 `selectionHasVideo ? ... : ...` 硬编码分支(该变量已删除,零引用),选中集合含视频→「个文件/复制视频」、纯图→「张图片/复制图片」、文档→「复制文档」全自动
- ✨ 多选工具条「已选 X 张图片」→ 按选中项类型自动(混合「个文件」);批量加水印「X 张图片」→「X 个文件」;扫描进度「X/Y 张图片」→「X/Y 个文件」;评分日志、双击查看 title 同步通用化
- 🔍 搜索框 placeholder「搜索图片...」→「搜索文件...」(搜索本就覆盖全类型,OCR 说明保留)
- ✨ **右侧面板文件夹信息区(原截图问题点)**:「包含图片: X 张(含子文件夹)」→「包含: X 个视频/张图片/个文件(含子文件夹)」(由该文件夹实际类型自动);「导出文件夹 (X 张)」同步按类型
- ✨ 加载进度「已加载 X/Y 张」→「已加载 X/Y 个文件」;评分 toast「(N 张)」→「(N 个)」;批量水印按钮「开始处理 N 张/该文件夹没有图片」→「开始处理 N 个文件/该文件夹没有可处理的文件」(与弹窗头部计数口径一致)
- ✨ 合拼入口过滤:多选点「合拼」只把图片送进画布(与 AI 生成视频入口同模式),视频/文档不参与,进入后由「至少需要 2 张图片」校验提示
- 保留(功能输入校验,非数据展示):AI 生成视频「请至少选择 2 张图片」、合拼「至少需要 2 张图片」——这两个功能的输入确实限图片,且入口均已有类型过滤
- ✨ 注册表与后端分类器完全对齐(backend thumbnail.js getFileType 共 6 类):补 design「设计」(psd/ai/sketch/fig…) 与 other「其他」两行——此前这两个类型在统计卡图例都兜底成「文件」导致出现两个重复的「文件 N」(如「我的素材」库 文件5/文件8);图例改按注册表固定顺序展示(orderedTypeEntries)
- 端到端实测:stats.typeCounts 正确、统计卡图例/文件夹卡「5 个视频」/右侧面板文件夹信息区/多选条浏览器核验
## 2026-11-18 → v1.4.6
- ✨ **文件夹右键新增「批量重命名文件」**:三种模式 —— 前面加(前缀)、后面加(后缀)、全部改名(原文件名整体替换,扩展名始终保留)
- ✨ 支持**包含子目录**开关,递归处理所有层级文件(默认开启,可只改当前文件夹)
- ✨ 弹窗**实时预览**改名效果(输入文本后即时显示每个文件的新旧文件名对照与总数)
- 🛡️ 全部改名模式同目录多个文件**自动编号**(文本-001、文本-002…,每个子目录独立编号;单文件不编号),避免撞名
- 🛡️ 冲突保护:目标文件名已存在(含本次内重复)自动跳过并在结果中报告;文本含文件名非法字符 `\ / : * ? " < > |` 前后端双重校验
- ⚡️ 复用批量水印异步任务体系:进度条、可停止(已完成的保留)、完成统计(已重命名/已跳过/失败 + 失败明细)
- 🔒 重命名后同步更新数据库记录(path/filename);缩略图按内容 hash 存储、与文件名无关,无需重建;旧路径零残留
- 后端新增 `POST /api/batch/rename-preview` 预览接口;`POST /api/batch/start` 的 type 扩展 `rename`
- 端到端实测:preview 三模式(含子目录/不含子目录/自动编号)、非法字符 400、suffix/prefix 实际执行 FS+DB 一致、浏览器 UI 右键菜单→弹窗→预览→执行→完成全流程
## 2026-11-18 → v1.4.5
**优化:侧栏文件夹按日期倒序,最新的文件夹排最前**——原先侧栏/仪表盘文件夹顺序来自后端 `SELECT ... ORDER BY path`(名称字典序升序),最旧的文件夹排最前,最新日期沉底。现改为在 `FolderModel.getTree()` 按文件夹名解析出的真实日期倒序排序:
- 兼容两种命名格式混排:`YYYY-MM-DD` 与 `YYYYMMDD`(原纯字符串倒序会把 `20261016` 压过 `2026-11-18`,日期顺序错乱;`_归档` 还会因首字符 `_` 排到最前)
- 无法解析为日期的文件夹(如 `_归档`、`1217`)排在所有日期文件夹之后,组内按名称倒序
- 子文件夹同样按日期倒序
- 侧栏与仪表盘(Dashboard)共用同一接口数据,同步生效
## 2026-11-18 → v1.4.4
**修复:选中视频文件,右侧详情面板仍显示图片信息**——根因是 `RightPanel.jsx` 全组件没有任何视频判定(`fileType === 'video'`),预览区把视频当图片渲染缩略图、底部按钮硬编码「编辑图片 / 复制图片 / 导出图片」,点「编辑图片」还会把视频塞进图片编辑器。修复:
- **预览区**:视频改为直接播放原文件(`<video controls>`,缩略图作 poster),不再以图片形式展示
- **按钮按类型分流**:单选视频显示「编辑视频 / 复制视频 / 导出视频」——「编辑视频」打开视频编辑弹窗(水印/字幕声音),「复制视频」只写应用内剪贴板(视频无法转成图片写系统剪贴板,原先会走失败兜底弹 alert)
- **新增时长字段**:视频详情显示「时长: m:ss」(取 `duration` 字段,与瀑布流角标同格式)
- **多选文案**:选中集合含视频时,「已选择 N 张图片 / 数量 N 张图片 / 复制图片 / 导出图片」等改为「个文件 / 复制文件 / 导出文件」,计数单位「张」→「个」
- **弹窗状态提升**:视频编辑弹窗状态从 `ImageWaterfall` 局部 state 提升到 `useUIStore`,弹窗渲染移到 App 层——原先只挂在 `ImageWaterfall` 内,而该组件在 Dashboard 视图下不渲染,某些页面点编辑视频弹窗不会出现;右侧面板与右键菜单现共用同一入口,不再重复挂载
## 2026-11-18 → v1.4.3
**优化**:侧栏首项文案「全部图片」改为「全部」(`Sidebar.jsx`)。
**修复:视频编辑/AI 生成视频点「开始处理」报 `[object Object]`、功能完全不可用**——根因是两处裸 `fetch` 调用没带登录态:`VideoEditModal.jsx`(`/api/video/edit`)与 `AIVideoModal.jsx`(`/api/video/aigenerate`、`/api/video/task/:id`)均未附 `Authorization` 头,而后端 `/api` 全组走认证中间件,一律 401 拒绝;前端又把 `{code, message}` 错误对象直接 `new Error()`,对象转字符串就成了 `[object Object]`。修复:三处请求补 `Authorization: `Bearer ${getToken()}`(与图片编辑器等既有调用一致),错误信息统一经 `errText()` 解析(对象取 `message`,再兜底状态码),不再出现 `[object Object]`。另修复 `MergeCollage.jsx` 拼图找相似接口同样的缺 token 问题(历史遗留)。
## 2026-11-18 → v1.4.2
**修复:添加素材库报 `Path does not exist`(视频目录)**——根因是该目录未挂载进容器(容器里看不到宿主机目录)。`docker-compose.yml` 已补挂载 `/vol2/1000/HD2/发布到平台的图片和视频`,README 使用注意新增排查方法(volumes 加一行同路径挂载后 `docker compose up -d`)。后端报错同步中文化:`素材库路径不存在: <路径>(如为宿主机目录,需先在 docker-compose.yml 的 volumes 里挂载进容器再重试)`(创建与更新两处)。
## 2026-11-18 → v1.4.1
**品牌更名**:应用正式更名为「牛仔库」(原名:牛图 / FlyPic 飞图)——页面标题、登录页、顶栏、设置-关于、导出文件名、后端提示与启动日志全部同步;仓库地址、镜像名、数据目录 `.flypic` 保持不变,README 标题附更名说明。
**品牌更名**:应用正式更名为「牛仔库」(原名:牛图 / FlyPic 飞图)——页面标题(定为「牛仔库 - 素材库管理」)、登录页、顶栏、设置-关于、导出文件名、后端提示与启动日志全部同步;仓库地址、镜像名、数据目录 `.flypic` 保持不变,README 标题附更名说明。
**修复**:平铺库(无子文件夹)无法浏览图片——误显「素材库似乎是空的」且无法进入瀑布视图。新增 `foldersLoaded` 标记区分「文件夹加载中」与「确认无子文件夹」,无子文件夹的库直接加载全部图片;扫描完成不再清空已显示图片;Dashboard 空文案按 `totalImageCount` 分流(有图时不再误报空库)。
+4
View File
@@ -102,6 +102,7 @@ services:
# 素材库目录(容器内路径与宿主机一致,中文路径直接填,按需增减)
- /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸
- /vol2/1000/HD2/我的文档:/vol2/1000/HD2/我的文档
- /vol2/1000/HD2/发布到平台的图片和视频:/vol2/1000/HD2/发布到平台的图片和视频
# 持久化配置(素材库列表、管理员密码,不用改)
- /vol3/1000/HD3/docker/flypic/config:/root/.flypic
environment:
@@ -142,6 +143,8 @@ docker run -d --name flypic --restart unless-stopped \
-e NODE_ENV=production \
-v /vol3/1000/HD3/docker/flypic/config:/root/.flypic \
-v /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸 \
-v "/vol2/1000/HD2/我的文档:/vol2/1000/HD2/我的文档" \
-v "/vol2/1000/HD2/发布到平台的图片和视频:/vol2/1000/HD2/发布到平台的图片和视频" \
jpccr.ccs.tencentyun.com/jinghui/flypic:latest
```
@@ -152,6 +155,7 @@ docker run -d --name flypic --restart unless-stopped \
## 📝 使用注意
- **添加/更新素材库后需重新扫描**,图片内 OCR 文字才可被搜索到(旧索引无文字数据)——点击右上角**「重新扫描」图标**即可,扫描时会自动补齐历史图片的 OCR 文字索引
- **添加素材库提示 `Path does not exist`** = 该目录没有挂载进容器(容器里看不到宿主机目录)——在 `docker-compose.yml` 的 `volumes` 下加一行 `- /宿主机路径:/宿主机路径`(两边写一样的路径),再 `docker compose up -d`,然后重新添加即可
- 素材库全量 OCR 扫描逐张识别、耗时较长,建议在不用的时候执行
- 数据存储:素材目录下 `.flypic/`(缩略图 + SQLite 索引,含 `ocr_text` 列);应用配置在 `config/`(已 gitignore)
- 删除素材目录下的 `.flypic` 即可清除该库索引,重新扫描重建
+62 -1
View File
@@ -28,7 +28,68 @@ class FolderModel extends BaseModel {
*/
getTree() {
const folders = this.findAll();
return this._buildTree(folders);
// 最新文件夹排最前:按文件夹名解析出的日期倒序(兼容 YYYY-MM-DD 与 YYYYMMDD 两种命名),
// 无法解析为日期的(如 _归档、纯数字名)排在日期文件夹之后
folders.sort((a, b) => {
const diff = this._dateKey(b.name) - this._dateKey(a.name);
if (diff !== 0) return diff;
return String(b.name).localeCompare(String(a.name));
});
return this._attachTypeCounts(this._buildTree(folders));
}
/**
* 给树中每个节点附着 typeCounts(按文件类型分组计数,含子目录)
* { image: 102, video: 181, document: 73 }
* 聚合范围与 updateImageCount 一致:本文件夹 + 所有子目录前缀
* 供前端类型注册表自动识别渲染(新增类型无需改代码)
*/
_attachTypeCounts(tree) {
let rows = [];
try {
rows = this.db.prepare(`
SELECT folder, file_type, COUNT(*) as c
FROM images
GROUP BY folder, file_type
`).all();
} catch {
return tree; // 查询失败时保持无 typeCounts,前端兜底"个文件"
}
const byFolder = new Map();
for (const r of rows) {
if (!byFolder.has(r.folder)) byFolder.set(r.folder, {});
const m = byFolder.get(r.folder);
const t = r.file_type || 'image';
m[t] = (m[t] || 0) + r.c;
}
const walk = (nodes) => {
for (const n of nodes) {
const counts = {};
for (const [f, m] of byFolder) {
if (f === n.path || f.startsWith(n.path + '/')) {
for (const [t, c] of Object.entries(m)) {
counts[t] = (counts[t] || 0) + c;
}
}
}
n.typeCounts = counts;
if (n.children && n.children.length) walk(n.children);
}
};
walk(tree);
return tree;
}
/**
* 将文件夹名解析为日期键(YYYYMMDD 整数),解析不出返回 0
*/
_dateKey(name) {
const m = String(name || '').match(/(\d{4})-?(\d{2})-?(\d{2})/);
if (!m) return 0;
const month = Number(m[2]);
const day = Number(m[3]);
if (month < 1 || month > 12 || day < 1 || day > 31) return 0;
return Number(m[1] + m[2] + m[3]);
}
/**
+242 -10
View File
@@ -1,6 +1,7 @@
/**
* 文件夹批量水印路由
* - POST /api/batch/start 启动批量任务(加水印 / 去水印),返回 taskId 立即返回
* 文件夹批量水印/重命名路由
* - POST /api/batch/start 启动批量任务(加水印 / 去水印 / 重命名),返回 taskId 立即返回
* - POST /api/batch/rename-preview 批量重命名预览(不执行)
* - GET /api/batch/status/:id 查询任务进度
* - POST /api/batch/cancel/:id 取消任务
*
@@ -194,6 +195,15 @@ async function callInpaint(imageBuffer, maskBuffer) {
/** 收集文件夹内图片(含子文件夹) */
function collectImages(req, libraryId, folder) {
return collectRenameTargets(req, { libraryId, folder, scope: 'folder' });
}
/**
* 收集重命名目标
* scope=folder(默认):文件夹递归(沿用 collectImages 语义)
* scope=search:按关键词模糊匹配整个库(filename/ocr_text LIKE,跨文件夹)
*/
function collectRenameTargets(req, { libraryId, folder, scope, keywords }) {
const configManager = req.app.get('configManager');
const dbPool = req.app.get('dbPool');
if (!configManager || !dbPool) throw new ValidationError('服务未初始化');
@@ -205,6 +215,13 @@ function collectImages(req, libraryId, folder) {
const db = dbPool.acquire(library.path);
try {
const model = new ImageModel(db.db);
if (scope === 'search') {
const kw = String(keywords || '').trim();
if (!kw) throw new ValidationError('搜索关键词不能为空');
// folder 与搜索列表同款过滤(含子目录):选中文件夹时范围一致,未选中则全库
const { images } = model.search({ keywords: kw, folder: folder || undefined }, null);
return { library, images };
}
const { images } = model.search({ folder }, null);
return { library, images };
} finally {
@@ -312,8 +329,193 @@ async function runRemoveWatermark(req, task) {
});
}
// ---------- 批量重命名 ----------
/** 文件系统非法文件名字符(Windows 兼容) */
const ILLEGAL_NAME_RE = /[\\/:*?"<>|]/;
/**
* 计算重命名计划(preview 与执行共用,保证一致)
* @param {object} opts { images, folder, mode: 'prefix'|'suffix'|'replace'|'keyword', text, find?, includeSubdirs }
* keyword 模式:把文件名中的 find 全部替换为 text(text 可为空 = 删除关键词),
* 不含 find 的文件标记 skipReason='不含关键词'
* @returns {Array<{img, newFilename, newPath, absNew, skipReason?}>}
*/
function computeRenamePlan({ images, folder, mode, text, find, includeSubdirs }) {
const cleanText = String(text || '').trim();
const cleanFind = String(find || '').trim();
let list = images;
if (!includeSubdirs) {
// 只重命名该文件夹直接子项,排除子目录内文件
list = images.filter((img) => img.folder === folder);
}
// 按目录分组 + 原文件名升序,保证序号顺序稳定
const sorted = [...list].sort(
(a, b) => a.folder.localeCompare(b.folder) || a.filename.localeCompare(b.filename)
);
const dirGroups = new Map();
for (const img of sorted) {
if (!dirGroups.has(img.folder)) dirGroups.set(img.folder, []);
dirGroups.get(img.folder).push(img);
}
const used = new Set(); // 已分配的目标路径(小写归一,防大小写不敏感 FS 撞名)
const plan = [];
for (const [, group] of dirGroups) {
const width = Math.max(3, String(group.length).length);
for (let i = 0; i < group.length; i++) {
const img = group[i];
const ext = path.extname(img.filename); // 含点,保留原样
const base = img.filename.slice(0, img.filename.length - ext.length);
let newBase;
if (mode === 'prefix') newBase = cleanText + base;
else if (mode === 'suffix') newBase = base + cleanText;
else if (mode === 'replace') {
// 全部改名:整段替换原文件名,同目录多个文件自动编号避免撞名
newBase = group.length > 1
? `${cleanText}-${String(i + 1).padStart(width, '0')}`
: cleanText;
} else if (mode === 'keyword') {
// 关键词替换:文件名中所有出现的 find 换成 text;不含 find 跳过
newBase = base.includes(cleanFind) ? base.split(cleanFind).join(cleanText) : base;
} else newBase = base;
const newFilename = `${newBase}${ext}`;
const newPath = `${img.folder ? img.folder + '/' : ''}${newFilename}`;
const absNew = newPath; // 相对库根,执行时再 join
const entry = { img, newFilename, newPath, skipReason: null };
if (mode === 'keyword' && !base.includes(cleanFind)) {
entry.skipReason = '不含关键词';
} else if (newFilename === img.filename) {
entry.skipReason = '文件名未变化';
} else if (used.has(newPath.toLowerCase())) {
entry.skipReason = '目标文件名冲突(本次内)';
}
used.add(newPath.toLowerCase());
plan.push(entry);
}
}
return plan;
}
async function runRename(req, task) {
const p = task.payload;
const { library, images } = collectRenameTargets(req, {
libraryId: p.libraryId,
folder: p.folder,
scope: p.scope,
keywords: p.keywords
});
const opts = task.payload.options;
const isSearch = p.scope === 'search';
const plan = computeRenamePlan({
images,
folder: task.payload.folder,
mode: opts.mode,
text: opts.text,
find: opts.find,
includeSubdirs: isSearch ? true : opts.includeSubdirs !== false
});
task.total = plan.length;
const dbPool = req.app.get('dbPool');
const dbUpdates = [];
for (const entry of plan) {
if (task.cancelled) break;
const { img, newFilename, newPath, skipReason } = entry;
task.current = img.path;
if (skipReason) {
task.skipped++;
continue;
}
const absOld = path.join(library.path, img.path);
const absNew = path.join(library.path, newPath);
try {
if (!fs.existsSync(absOld)) {
task.skipped++;
if (task.errors.length < 20) task.errors.push({ path: img.path, error: '源文件不存在' });
continue;
}
if (absOld !== absNew && fs.existsSync(absNew)) {
task.skipped++;
if (task.errors.length < 20) task.errors.push({ path: img.path, error: `目标已存在: ${newFilename}` });
continue;
}
if (absOld !== absNew) await fs.promises.rename(absOld, absNew);
dbUpdates.push({ oldPath: img.path, newPath, newFilename });
task.done++;
} catch (err) {
task.failed++;
if (task.errors.length < 20) task.errors.push({ path: img.path, error: err.message });
logger.warn(`⚠️ 批量重命名失败 ${img.path}: ${err.message}`);
}
}
// 统一更新 DB(缩略图按内容 hash 存储,与文件名无关,无需重建)
if (dbUpdates.length > 0) {
const db = dbPool.acquire(library.path);
try {
const stmt = db.db.prepare('UPDATE images SET path = ?, filename = ? WHERE path = ?');
for (const u of dbUpdates) stmt.run(u.newPath, u.newFilename, u.oldPath);
} finally {
dbPool.release(library.path);
}
}
}
// ---------- 路由 ----------
/**
* POST /api/batch/rename-preview
* body: { libraryId, folder?, scope?: 'folder'|'search', keywords?, options: { mode, text, find?, includeSubdirs } }
* scope=search 时按 keywords 模糊匹配全库(跨文件夹),folder 可不传
* 返回重命名预览(不执行)
*/
router.post(
'/rename-preview',
asyncHandler(async (req, res) => {
const { libraryId, folder, scope, options } = req.body || {};
if (!libraryId) throw new ValidationError('缺少 libraryId');
const isSearch = scope === 'search';
if (!isSearch && !folder) throw new ValidationError('缺少 libraryId 或 folder');
const mode = options && options.mode;
if (!['prefix', 'suffix', 'replace', 'keyword'].includes(mode)) {
throw new ValidationError('mode 必须是 prefix / suffix / replace / keyword');
}
const text = String((options && options.text) || '').trim();
const find = String((options && options.find) || '').trim();
if (mode === 'keyword') {
if (!find) throw new ValidationError('请填写要查找的关键词');
if (ILLEGAL_NAME_RE.test(find)) throw new ValidationError('关键词包含文件名非法字符 \\ / : * ? " < > |');
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('替换文本包含文件名非法字符 \\ / : * ? " < > |');
} else {
if (!text) throw new ValidationError('重命名文本不能为空');
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('文本包含文件名非法字符 \\ / : * ? " < > |');
}
const targets = collectRenameTargets(req, {
libraryId, folder, scope, keywords: options && options.keywords
});
const plan = computeRenamePlan({
images: targets.images,
folder: isSearch ? null : folder,
mode, text, find,
includeSubdirs: isSearch ? true : options.includeSubdirs !== false
});
const effective = plan.filter((p) => !p.skipReason);
res.json({
count: effective.length,
total: plan.length,
samples: plan.slice(0, 6).map((p) => ({ from: p.img.filename, to: p.newFilename })),
skipped: plan.filter((p) => p.skipReason).length
});
})
);
/**
* POST /api/batch/start
* body: { libraryId, folder, type: 'add'|'remove', output?: 'overwrite'|'new', options }
@@ -323,12 +525,29 @@ async function runRemoveWatermark(req, task) {
router.post(
'/start',
asyncHandler(async (req, res) => {
const { libraryId, folder, type, output, options } = req.body || {};
if (!libraryId || !folder) throw new ValidationError('缺少 libraryId 或 folder');
if (type !== 'add' && type !== 'remove') throw new ValidationError('type 必须是 add 或 remove');
const { libraryId, folder, type, output, options, scope } = req.body || {};
if (!libraryId) throw new ValidationError('缺少 libraryId');
const isSearch = type === 'rename' && scope === 'search';
if (!folder && !isSearch) throw new ValidationError('缺少 libraryId 或 folder');
if (!['add', 'remove', 'rename'].includes(type)) throw new ValidationError('type 必须是 add / remove / rename');
if (type === 'add') {
if (!options || !String(options.text || '').trim()) throw new ValidationError('水印文字不能为空');
} else if (type === 'rename') {
const mode = options && options.mode;
if (!['prefix', 'suffix', 'replace', 'keyword'].includes(mode)) {
throw new ValidationError('mode 必须是 prefix / suffix / replace / keyword');
}
const text = String((options && options.text) || '').trim();
const find = String((options && options.find) || '').trim();
if (mode === 'keyword') {
if (!find) throw new ValidationError('请填写要查找的关键词');
if (ILLEGAL_NAME_RE.test(find)) throw new ValidationError('关键词包含文件名非法字符 \\ / : * ? " < > |');
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('替换文本包含文件名非法字符 \\ / : * ? " < > |');
} else {
if (!text) throw new ValidationError('重命名文本不能为空');
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('文本包含文件名非法字符 \\ / : * ? " < > |');
}
} else {
const r = options && options.region;
if (!r || [r.x, r.y, r.w, r.h].some((v) => typeof v !== 'number' || v < 0)) {
@@ -337,15 +556,28 @@ router.post(
if (r.w <= 0 || r.h <= 0) throw new ValidationError('水印区域宽高必须大于 0');
}
const { images } = collectImages(req, libraryId, folder);
if (images.length === 0) throw new ValidationError('该文件夹下没有图片');
const { images } = collectRenameTargets(req, {
libraryId, folder, scope, keywords: options && options.keywords
});
if (images.length === 0) {
throw new ValidationError(
scope === 'search' ? '搜索没有匹配到文件' : (type === 'rename' ? '该文件夹下没有文件' : '该文件夹下没有图片')
);
}
const task = newTask(type, { libraryId, folder, output, options });
const task = newTask(type, {
libraryId,
folder: folder || null,
scope: scope || 'folder',
keywords: scope === 'search' ? String(options?.keywords || '').trim() : null,
output,
options
});
task.total = images.length;
logger.info(`▶️ 批量${type === 'add' ? '加水印' : '去水印'}启动: ${folder} (${images.length} 张)`);
logger.info(`▶️ 批量${type === 'add' ? '加水印' : type === 'remove' ? '去水印' : '重命名'}启动: ${folder} (${images.length} 张)`);
// 立即返回,后台执行
const runner = type === 'add' ? runAddWatermark : runRemoveWatermark;
const runner = type === 'add' ? runAddWatermark : type === 'remove' ? runRemoveWatermark : runRename;
runner(req, task)
.then(() => {
task.status = task.cancelled ? 'cancelled' : 'done';
+13 -1
View File
@@ -112,9 +112,21 @@ class ImageService {
ORDER BY count DESC
`).all();
// 按文件类型分组计数(image/video/document/...),供前端类型注册表自动识别渲染
const typeCountsList = db.db.prepare(`
SELECT file_type, COUNT(*) as count
FROM images
GROUP BY file_type
`).all();
const typeCounts = {};
for (const row of typeCountsList) {
typeCounts[row.file_type || 'image'] = row.count;
}
return {
...stats,
formats: formatStats
formats: formatStats,
typeCounts
};
} finally {
this.dbPool.release(library.path);
+2 -2
View File
@@ -46,7 +46,7 @@ class LibraryService {
if (!fs.existsSync(normalizedPath)) {
logger.warn(`路径不存在: ${normalizedPath}`);
throw new ValidationError('Path does not exist', 'path');
throw new ValidationError(`素材库路径不存在: ${normalizedPath}(如为宿主机目录,需先在 docker-compose.yml 的 volumes 里挂载进容器再重试)`, 'path');
}
// 检查文件夹访问权限
@@ -105,7 +105,7 @@ class LibraryService {
// 验证更新的路径是否存在
if (updates.path && !fs.existsSync(updates.path)) {
throw new ValidationError('Path does not exist', 'path');
throw new ValidationError(`素材库路径不存在: ${updates.path}(如为宿主机目录,需先在 docker-compose.yml 的 volumes 里挂载进容器再重试)`, 'path');
}
const success = this.configManager.updateLibrary(id, updates);
+1 -1
View File
@@ -16,7 +16,7 @@ const { getSettings } = require('./settings');
const HUB_URL = (process.env.HUB_URL || 'https://auth.88531.cn/api').replace(/\/+$/, '');
const HUB_PROJECT_ID = process.env.HUB_PROJECT_ID || '';
const HUB_API_KEY = process.env.HUB_API_KEY || '';
const SITE_VERSION = process.env.SITE_VERSION || '1.4.1';
const SITE_VERSION = process.env.SITE_VERSION || '1.4.8';
const TIMEOUT_MS = 8000;
const state = {
+2 -1
View File
@@ -13,6 +13,7 @@ services:
# 素材库目录(容器内路径与飞牛一致,直接填实际路径即可)
- /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸
- /vol2/1000/HD2/我的文档:/vol2/1000/HD2/我的文档
- /vol2/1000/HD2/发布到平台的图片和视频:/vol2/1000/HD2/发布到平台的图片和视频
# 持久化配置(config.json 存储素材库路径、密码等,不用改)
- /vol3/1000/HD3/docker/flypic/config:/root/.flypic
environment:
@@ -27,7 +28,7 @@ services:
- HUB_API_KEY=${HUB_API_KEY:-}
- NEWAPI_KEY=${NEWAPI_KEY:-}
# 当前站点版本(与 frontend/package.json、CHANGELOG 保持一致,界面版本徽标来源)
- SITE_VERSION=1.4.1
- SITE_VERSION=1.4.8
# 让容器经 host.docker.internal 访问宿主机的 AI 侧车
extra_hosts:
- "host.docker.internal:host-gateway"
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>牛仔库 - 图片素材库管理</title>
<title>牛仔库 - 素材库管理</title>
</head>
<body>
<div id="root"></div>
+27 -5
View File
@@ -14,6 +14,7 @@ import Header from './components/Header';
import LibraryMissingModal from './components/LibraryMissingModal';
import BackToTop from './components/BackToTop';
import ImageEditor from './components/ImageEditor';
import VideoEditModal from './components/VideoEditModal';
import { createLogger } from './utils/logger';
const logger = createLogger('App');
@@ -22,13 +23,14 @@ function App() {
// 使用统一的主题管理 Hook
useTheme();
const { mobileView, setMobileView } = useUIStore();
const {
setLibraries,
setCurrentLibrary,
const { mobileView, setMobileView, videoEditFile, setVideoEditFile } = useUIStore();
const {
setLibraries,
setCurrentLibrary,
removeLibrary,
setShowAddLibraryForm,
triggerExpandLibrarySelector
triggerExpandLibrarySelector,
currentLibraryId
} = useLibraryStore();
const { selectedImage } = useImageStore();
const { setScanProgress } = useScanStore();
@@ -147,6 +149,7 @@ function App() {
}
useImageStore.getState().setTotalImageCount(statsRes.total || 0);
useImageStore.getState().setTotalSize(statsRes.totalSize || 0);
useImageStore.getState().setTypeCounts(statsRes.typeCounts);
}).catch(err => {
logger.error('扫描完成后加载数据失败:', err.message);
}).finally(() => {
@@ -186,6 +189,7 @@ function App() {
// 注意:后端返回的字段是 total 和 totalSize
useImageStore.getState().setTotalImageCount(statsResponse.total || 0);
useImageStore.getState().setTotalSize(statsResponse.totalSize || 0);
useImageStore.getState().setTypeCounts(statsResponse.typeCounts);
} catch (error) {
logger.error('加载文件夹失败:', error.message);
}
@@ -515,6 +519,15 @@ function App() {
onCreateNew={handleCreateNewLibrary}
/>
<ImageEditor />
{/* 视频编辑弹窗(store 全局状态,右侧面板/瀑布流均可触发) */}
{videoEditFile && (
<VideoEditModal
file={videoEditFile}
libraryId={currentLibraryId}
onClose={() => setVideoEditFile(null)}
onDone={() => { setVideoEditFile(null); window.location.reload(); }}
/>
)}
<div className="flex-1 overflow-hidden relative">
{/* 侧边栏视图 */}
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'sidebar' ? 'translate-x-0' : '-translate-x-full'
@@ -590,6 +603,15 @@ function App() {
onCreateNew={handleCreateNewLibrary}
/>
<ImageEditor />
{/* 视频编辑弹窗(store 全局状态,右侧面板/瀑布流均可触发) */}
{videoEditFile && (
<VideoEditModal
file={videoEditFile}
libraryId={currentLibraryId}
onClose={() => setVideoEditFile(null)}
onDone={() => { setVideoEditFile(null); window.location.reload(); }}
/>
)}
<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">
+6
View File
@@ -19,3 +19,9 @@ export async function status(taskId) {
export async function cancel(taskId) {
return api.post(`/batch/cancel/${taskId}`);
}
/** 批量重命名预览(不执行),返回 { count, total, samples: [{from,to}], skipped } */
export async function renamePreview(payload) {
// payload: { libraryId, folder, options: { mode, text, includeSubdirs } }
return api.post('/batch/rename-preview', payload);
}
+16 -3
View File
@@ -6,6 +6,14 @@
import { useEffect, useRef, useState } from 'react';
import { X, Loader2, Film, CheckCircle2, AlertCircle, KeyRound } from 'lucide-react';
import { imageAPI } from '../api';
import { getToken } from '../api/client';
// 后端错误可能为字符串或 {code,message} 对象,统一取可读文本
const errText = (e, fallback) => {
if (!e) return fallback;
if (typeof e === 'string') return e;
return e.message || JSON.stringify(e);
};
const VOICES = [
{ key: 'zh-CN-XiaoxiaoNeural', label: '晓晓(女声·自然)' },
@@ -51,7 +59,9 @@ function AIVideoModal({ libraryId, images, onClose, onDone }) {
if (!taskId) return;
timerRef.current = setInterval(async () => {
try {
const res = await fetch(`/api/video/task/${taskId}`);
const res = await fetch(`/api/video/task/${taskId}`, {
headers: { Authorization: `Bearer ${getToken()}` }
});
if (!res.ok) return;
const data = await res.json();
setTask(data);
@@ -74,7 +84,10 @@ function AIVideoModal({ libraryId, images, onClose, onDone }) {
try {
const res = await fetch('/api/video/aigenerate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`
},
body: JSON.stringify({
libraryId,
images: list.map((img) => ({ path: img.path })),
@@ -86,7 +99,7 @@ function AIVideoModal({ libraryId, images, onClose, onDone }) {
})
});
const data = await res.json().catch(() => ({}));
if (!res.ok || data.error) throw new Error(data.error || `启动失败 (${res.status})`);
if (!res.ok || data.error) throw new Error(errText(data.error, `启动失败 (${res.status})`));
setTaskId(data.taskId);
} catch (e) {
setError(e.message || '启动失败');
@@ -0,0 +1,430 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { Replace, Loader2, X, Play, Square, CheckCircle2, AlertTriangle, ArrowRight } from 'lucide-react';
import { batchAPI } from '../api';
/**
* 批量重命名弹窗(文件夹级)
* 模式:
* prefix 前缀添加 —— 在原文件名前加文本
* suffix 后缀添加 —— 在原文件名后加文本
* replace 全部改名 —— 原文件名整体替换为文本(同目录多个文件自动加序号 -001)
*
* 流程:配置(实时预览)→ 启动任务(立即返回 taskId)→ 1s 轮询进度 → 完成/取消
*/
const MODES = [
{ key: 'prefix', label: '前面加', desc: '在原文件名前加文本', hint: '文本 + 原文件名 + 扩展名' },
{ key: 'suffix', label: '后面加', desc: '在原文件名后加文本', hint: '原文件名 + 文本 + 扩展名' },
{ key: 'replace', label: '全部改名', desc: '原文件名替换为文本', hint: '同目录多个文件自动编号:文本-001、文本-002…' },
{ key: 'keyword', label: '关键词替换', desc: '替换文件名中的关键词', hint: '把文件名中的「找什么」全部换成「替换成」,替换成留空 = 删除该关键词' }
];
const ILLEGAL_RE = /[\\/:*?"<>|]/;
function BatchRenameModal({ isOpen, folder, libraryId, scope, keywords, onClose, onFinished }) {
const [phase, setPhase] = useState('config'); // config | running | done
const [mode, setMode] = useState('prefix');
const [text, setText] = useState('');
const [find, setFind] = useState('');
const [includeSubdirs, setIncludeSubdirs] = useState(true);
const [preview, setPreview] = useState(null); // { count, total, samples, skipped }
const [previewErr, setPreviewErr] = useState('');
const [starting, setStarting] = useState(false);
const [error, setError] = useState('');
const [taskId, setTaskId] = useState(null);
const [progress, setProgress] = useState(null);
const pollRef = useRef(null);
const previewTimerRef = useRef(null);
const stopPolling = useCallback(() => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
}, []);
// 打开时重置
useEffect(() => {
if (!isOpen) return;
setPhase('config');
setMode('prefix');
setText('');
setFind('');
setIncludeSubdirs(true);
setPreview(null);
setPreviewErr('');
setError('');
setTaskId(null);
setProgress(null);
setStarting(false);
return () => stopPolling();
}, [isOpen, stopPolling]);
// 实时预览(防抖 300ms)
const needInput = mode === 'keyword' ? find.trim() : text.trim();
useEffect(() => {
if (!isOpen || phase !== 'config') return;
if (previewTimerRef.current) clearTimeout(previewTimerRef.current);
if (!needInput) {
setPreview(null);
setPreviewErr('');
return;
}
previewTimerRef.current = setTimeout(async () => {
try {
const resp = await batchAPI.renamePreview({
libraryId, folder, scope, keywords,
options: { mode, text: text.trim(), find: find.trim(), keywords: keywords || undefined, includeSubdirs }
});
setPreview(resp);
setPreviewErr('');
} catch (err) {
setPreview(null);
setPreviewErr(err?.message || '预览失败');
}
}, 300);
return () => { if (previewTimerRef.current) clearTimeout(previewTimerRef.current); };
}, [isOpen, phase, mode, text, find, includeSubdirs, libraryId, folder, scope, keywords, needInput]);
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('');
const t = text.trim();
const f = find.trim();
if (mode === 'keyword') {
if (!f) {
setError('请填写要查找的关键词');
return;
}
if (ILLEGAL_RE.test(f)) {
setError('关键词包含文件名非法字符 \\ / : * ? " < > |');
return;
}
if (ILLEGAL_RE.test(t)) {
setError('替换文本包含文件名非法字符 \\ / : * ? " < > |');
return;
}
} else {
if (!t) {
setError('请输入重命名文本');
return;
}
if (ILLEGAL_RE.test(t)) {
setError('文本包含文件名非法字符 \\ / : * ? " < > |');
return;
}
}
setStarting(true);
try {
const resp = await batchAPI.start({
libraryId, folder, scope, keywords, type: 'rename',
options: { mode, text: t, find: f, keywords: keywords || undefined, includeSubdirs }
});
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 pct = progress && progress.total > 0
? Math.round(((progress.done + progress.failed + progress.skipped) / progress.total) * 100)
: 0;
const modeInfo = MODES.find((m) => m.key === mode);
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-xl 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">
<Replace className="w-5 h-5 text-violet-500" />
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">批量重命名文件</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]">
{scope === 'search' ? `搜索:${keywords}` : folder}
</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' && (
<>
{/* 重命名模式 */}
<div className="mb-4">
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">重命名方式</div>
<div className="grid grid-cols-2 gap-2">
{MODES.map((m) => (
<button
key={m.key}
onClick={() => setMode(m.key)}
className={`px-3 py-2.5 rounded-lg text-sm border transition-colors ${mode === m.key
? 'border-violet-500 bg-violet-50 dark:bg-violet-900/40 text-violet-600 dark:text-violet-300 font-medium'
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:border-gray-400'}`}
>
<div>{m.label}</div>
<div className="text-[10px] font-normal opacity-70 mt-0.5">{m.desc}</div>
</button>
))}
</div>
<div className="text-[11px] text-gray-400 dark:text-gray-500 mt-1.5">
规则:{modeInfo.hint}(扩展名始终保留)
</div>
</div>
{/* 文本输入 */}
{mode === 'keyword' ? (
<div className="mb-4">
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">关键词</div>
<input
type="text"
value={find}
onChange={(e) => setFind(e.target.value)}
placeholder="找什么:要被替换的文件名关键词,例如:素材"
maxLength={100}
autoFocus
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-violet-500"
/>
{ILLEGAL_RE.test(find) && (
<div className="text-[11px] text-red-500 mt-1">关键词包含文件名非法字符 \ / : * ? " &lt; &gt; |</div>
)}
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5 mt-3">替换成</div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="替换成:留空 = 直接删除该关键词,例如:视频"
maxLength={100}
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-violet-500"
/>
{ILLEGAL_RE.test(text) && (
<div className="text-[11px] text-red-500 mt-1">替换文本包含文件名非法字符 \ / : * ? " &lt; &gt; |</div>
)}
</div>
) : (
<div className="mb-4">
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">文本内容</div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={mode === 'replace' ? '例如:风景素材(全部文件改为 风景素材-001.jpg …)' : '例如:2026_'}
maxLength={100}
autoFocus
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-violet-500"
/>
{ILLEGAL_RE.test(text) && (
<div className="text-[11px] text-red-500 mt-1">包含文件名非法字符 \ / : * ? " &lt; &gt; |</div>
)}
</div>
)}
{/* 包含子目录(搜索范围时全库命中,无需此开关) */}
{scope !== 'search' && (
<label className="flex items-center gap-2 mb-4 cursor-pointer select-none">
<input
type="checkbox"
checked={includeSubdirs}
onChange={(e) => setIncludeSubdirs(e.target.checked)}
className="w-4 h-4 rounded accent-violet-500"
/>
<span className="text-sm text-gray-700 dark:text-gray-300">包含子目录(递归处理所有层级文件)</span>
</label>
)}
{/* 实时预览 */}
<div className="rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50 p-3">
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">预览</div>
{!needInput && (
<div className="text-[11px] text-gray-400">{mode === 'keyword' ? '输入关键词后显示改名效果' : '输入文本后显示改名效果'}</div>
)}
{needInput && previewErr && (
<div className="text-[11px] text-red-500">{previewErr}</div>
)}
{needInput && !previewErr && !preview && (
<div className="text-[11px] text-gray-400 flex items-center gap-1.5">
<Loader2 className="w-3 h-3 animate-spin" /> 计算中…
</div>
)}
{preview && (
<>
<div className="text-[11px] text-gray-600 dark:text-gray-300 mb-2">
将重命名 <b className="text-violet-500">{preview.count}</b> 个文件
{preview.skipped > 0 && <span className="text-gray-400">({preview.skipped} 个跳过)</span>}
{!includeSubdirs && <span className="text-gray-400">,仅当前文件夹</span>}
</div>
<div className="space-y-1">
{preview.samples.map((s, i) => (
<div key={i} className="flex items-center gap-2 text-[11px] font-mono">
<span className="text-gray-500 dark:text-gray-400 truncate max-w-[45%]">{s.from}</span>
<ArrowRight className="w-3 h-3 text-violet-400 flex-shrink-0" />
<span className="text-violet-500 truncate">{s.to}</span>
</div>
))}
{preview.total > preview.samples.length && (
<div className="text-[10px] text-gray-400 pt-0.5">
…共 {preview.total} 条
</div>
)}
</div>
</>
)}
</div>
{error && (
<div className="mt-3 flex items-center gap-2 text-sm text-red-500">
<AlertTriangle className="w-4 h-4" /> {error}
</div>
)}
</>
)}
{phase === 'running' && (
<div className="py-4">
<div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-300 mb-2">
<span className="flex items-center gap-2">
<Loader2 className="w-4 h-4 animate-spin text-violet-500" />
重命名中 {progress ? `${progress.done + progress.failed + progress.skipped}/${progress.total}` : ''}
</span>
<span className="tabular-nums">{pct}%</span>
</div>
<div className="h-2 rounded-full bg-gray-200 dark:bg-gray-700 overflow-hidden">
<div className="h-full bg-violet-500 transition-all" style={{ width: `${pct}%` }} />
</div>
{progress?.current && (
<div className="mt-2 text-[11px] text-gray-400 truncate">{progress.current}</div>
)}
<div className="flex justify-center mt-5">
<button
onClick={handleCancel}
className="px-4 py-2 rounded-lg text-sm border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
>
<Square className="w-3.5 h-3.5" /> 停止(已完成的保留)
</button>
</div>
</div>
)}
{phase === 'done' && (
<div className="py-4">
<div className="flex items-center gap-2 mb-4">
<CheckCircle2 className="w-5 h-5 text-emerald-500" />
<span className="text-sm font-medium text-gray-900 dark:text-white">
{progress?.status === 'cancelled' ? '已停止' : '重命名完成'}
</span>
</div>
<div className="grid grid-cols-3 gap-3 text-center">
<div className="rounded-lg bg-emerald-50 dark:bg-emerald-900/30 p-3">
<div className="text-xl font-semibold text-emerald-600 dark:text-emerald-300 tabular-nums">{progress?.done ?? 0}</div>
<div className="text-[11px] text-gray-500 dark:text-gray-400">已重命名</div>
</div>
<div className="rounded-lg bg-gray-100 dark:bg-gray-700/60 p-3">
<div className="text-xl font-semibold text-gray-600 dark:text-gray-300 tabular-nums">{progress?.skipped ?? 0}</div>
<div className="text-[11px] text-gray-500 dark:text-gray-400">已跳过</div>
</div>
<div className="rounded-lg bg-red-50 dark:bg-red-900/30 p-3">
<div className="text-xl font-semibold text-red-600 dark:text-red-300 tabular-nums">{progress?.failed ?? 0}</div>
<div className="text-[11px] text-gray-500 dark:text-gray-400">失败</div>
</div>
</div>
{progress?.errors?.length > 0 && (
<div className="mt-4 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 p-3">
<div className="text-xs font-medium text-red-600 dark:text-red-300 mb-1.5">失败明细</div>
<div className="space-y-1">
{progress.errors.slice(0, 8).map((e, i) => (
<div key={i} className="text-[11px] text-red-500 dark:text-red-400 font-mono truncate">
{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-2.5">
{phase === 'config' && (
<>
<button
onClick={handleClose}
className="px-4 py-2 rounded-lg text-sm border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
>
取消
</button>
<button
onClick={handleStart}
disabled={starting || !text.trim() || ILLEGAL_RE.test(text)}
className="px-4 py-2 rounded-lg text-sm bg-violet-500 hover:bg-violet-600 text-white flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
开始重命名{preview ? `(${preview.count} 个)` : ''}
</button>
</>
)}
{phase === 'running' && (
<button
onClick={handleCancel}
className="px-4 py-2 rounded-lg text-sm border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
>
停止
</button>
)}
{phase === 'done' && (
<button
onClick={handleClose}
className="px-4 py-2 rounded-lg text-sm bg-violet-500 hover:bg-violet-600 text-white"
>
完成
</button>
)}
</div>
</div>
</div>
);
}
export default BatchRenameModal;
@@ -216,7 +216,7 @@ function BatchWatermarkModal({ isOpen, mode, folder, libraryId, onClose, onFinis
<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>
<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" />
@@ -517,7 +517,7 @@ function BatchWatermarkModal({ isOpen, mode, folder, libraryId, onClose, onFinis
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} 张`}
{imageCount === 0 ? '该文件夹没有可处理的文件' : `开始处理 ${imageCount} 个文件`}
</button>
</>
)}
+6 -1
View File
@@ -4,7 +4,7 @@
*/
import { useEffect, useRef } from 'react';
import { Trash2, Edit3, Move, Copy, FolderPlus, Star, Droplets, Eraser, Scissors, Film } from 'lucide-react';
import { Trash2, Edit3, Move, Copy, FolderPlus, Star, Droplets, Eraser, Scissors, Film, Replace } from 'lucide-react';
function ContextMenu({ isOpen, position, onClose, options }) {
const menuRef = useRef(null);
@@ -173,6 +173,11 @@ export const menuItems = {
label: '批量加水印…',
action
}),
batchRename: (action) => ({
icon: <Replace size={16} />,
label: '批量重命名文件…',
action
}),
batchRemoveWatermark: (action) => ({
icon: <Eraser size={16} />,
label: '批量去水印…',
+18 -6
View File
@@ -1,11 +1,12 @@
import React from 'react';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { Folder, Image as ImageIcon, HardDrive } from 'lucide-react';
import { Folder, Image as ImageIcon, HardDrive, File as FileIcon } from 'lucide-react';
import { countLabel, typeMeta, typeLabelOf, orderedTypeEntries } from '../utils/fileTypes';
function Dashboard() {
const { currentLibraryId, getCurrentLibrary } = useLibraryStore();
const { totalImageCount, totalSize, folders } = useImageStore();
const { totalImageCount, totalSize, folders, typeCounts } = useImageStore();
const currentLibrary = getCurrentLibrary();
const folderCount = folders.length;
@@ -35,11 +36,22 @@ function Dashboard() {
<div className="bg-secondary rounded-xl p-6 shadow-sm border">
<div className="flex items-center gap-4">
<div className="p-3 bg-blue-100 rounded-lg text-accent">
<ImageIcon className="w-6 h-6" />
{(() => {
const types = orderedTypeEntries(typeCounts);
const StatIcon = types.length === 1 ? typeMeta(types[0][0]).icon : FileIcon;
return <StatIcon className="w-6 h-6" />;
})()}
</div>
<div>
<div className="text-2xl font-bold text-primary">{totalImageCount.toLocaleString()}</div>
<div className="text-sm text-tertiary">图片总数</div>
<div className="text-sm text-tertiary">{typeLabelOf(typeCounts)}总数</div>
{/* 分类型图例:由类型注册表自动渲染,新类型无需改代码 */}
<div className="text-xs text-tertiary mt-0.5 flex gap-2 flex-wrap">
{orderedTypeEntries(typeCounts)
.map(([t, n]) => (
<span key={t}>{typeMeta(t).label} {n.toLocaleString()}</span>
))}
</div>
</div>
</div>
</div>
@@ -87,7 +99,7 @@ function Dashboard() {
</div>
</div>
</div>
<div className="text-xs text-tertiary">{folder.imageCount || 0} 张图片</div>
<div className="text-xs text-tertiary">{countLabel(folder.imageCount || 0, folder.typeCounts)}</div>
</div>
))}
</div>
@@ -100,7 +112,7 @@ function Dashboard() {
<h3 className="text-lg font-medium text-primary mb-2">暂无文件夹</h3>
<p className="text-tertiary max-w-sm mx-auto">
{totalImageCount > 0
? `此素材库的 ${totalImageCount} 张图片没有子文件夹,已在下方瀑布视图中直接显示。`
? `此素材库的 ${countLabel(totalImageCount, typeCounts)} 没有子文件夹,已在下方瀑布视图中直接显示。`
: '您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。'}
</p>
</div>
+3 -3
View File
@@ -38,7 +38,7 @@ function Header() {
// 授权系统 hub:版本 / 公告 / 在线人数
const hub = useHub();
const announcements = hub.announcements || [];
const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.4.1';
const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.4.8';
// 从全局 store 获取筛选状态
const selectedFormats = filters.formats || [];
@@ -494,7 +494,7 @@ function Header() {
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
<input
type="text"
placeholder="搜索图片...(支持 OCR 图内文字)"
placeholder="搜索文件...(支持 OCR 图内文字)"
value={searchKeywords}
onChange={(e) => handleSearchChange(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"
@@ -680,7 +680,7 @@ function Header() {
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
<input
type="text"
placeholder="搜索图片...(支持 OCR 图内文字,多个关键词用空格分隔)"
placeholder="搜索文件...(支持 OCR 图内文字,多个关键词用空格分隔)"
value={localSearchValue}
onChange={(e) => handleSearchChange(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
+8 -16
View File
@@ -27,6 +27,7 @@ import { useInfiniteScroll } from '../hooks/useInfiniteScroll';
// Utils
import { filterImages } from '../utils/imageFilters';
import { typeCountsOf, countLabel } from '../utils/fileTypes';
import { imageAPI, fileAPI } from '../api';
// Components
@@ -40,7 +41,6 @@ import UndoToast from './UndoToast';
import RatingToast from './RatingToast';
import FolderSelector from './FolderSelector';
import ConflictDialog from './ConflictDialog';
import VideoEditModal from './VideoEditModal';
import AIVideoModal from './AIVideoModal';
// 虚拟滚动阈值
@@ -58,13 +58,12 @@ function ImageWaterfall() {
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder,
searchKeywords, filters, folders, setSelectedFolderItem, updateImage
} = useImageStore();
const { setEditingImage, setMergeImages } = useUIStore();
const { setEditingImage, setMergeImages, setVideoEditFile } = useUIStore();
// 状态
const [photoIndex, setPhotoIndex] = useState(-1);
const [lastSelectedIndex, setLastSelectedIndex] = useState(null);
const [viewerFile, setViewerFile] = useState(null);
const [videoEditFile, setVideoEditFile] = useState(null); // 视频编辑弹窗
const [aiVideoOpen, setAiVideoOpen] = useState(false); // AI 生成视频弹窗
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, image: null });
// 统一图片移动/删除撤销顺序的栈:按操作时间顺序记录 'move' | 'delete'
@@ -538,13 +537,16 @@ onToggleFavorite={handleToggleFavorite}
}
const unionCount = union.length;
if (unionCount <= 1) return null;
const unionTypeCounts = typeCountsOf(union);
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>
<span className="text-sm whitespace-nowrap">已选 {countLabel(unionCount, unionTypeCounts)}</span>
<button
onClick={() => {
setMergeImages(union);
setEditingImage(union[0]);
// 合拼是图片功能:过滤出图片(与 AI 生成视频入口一致),视频/文档不进画布
const imgOnly = union.filter((img) => (img.fileType || 'image') === 'image');
setMergeImages(imgOnly);
setEditingImage(imgOnly[0] || 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"
@@ -667,16 +669,6 @@ onToggleFavorite={handleToggleFavorite}
/>
)}
{/* 视频编辑弹窗 */}
{videoEditFile && (
<VideoEditModal
file={videoEditFile}
libraryId={currentLibraryId}
onClose={() => setVideoEditFile(null)}
onDone={() => { setVideoEditFile(null); window.location.reload(); }}
/>
)}
{/* AI 生成视频弹窗 */}
{aiVideoOpen && (
<AIVideoModal
+40 -3
View File
@@ -9,6 +9,8 @@ import requestManager, { RequestType } from '../services/requestManager';
import domCleanup from '../utils/domCleanup';
import ImageWaterfall from './ImageWaterfall';
import Dashboard from './Dashboard';
import BatchRenameModal from './BatchRenameModal';
import { PencilLine } from 'lucide-react';
import { createLogger } from '../utils/logger';
const logger = createLogger('MainContent');
@@ -18,6 +20,9 @@ function MainContent() {
const { searchKeywords, filters, selectedFolder, favoritesView, setImages, setOriginalImages, imageLoadingState, images, refreshTick, folders, foldersLoaded } = useImageStore();
const { scanProgress } = useScanStore();
// 搜索结果批量重命名弹窗
const [searchRenameOpen, setSearchRenameOpen] = useState(false);
// 使用 ref 跟踪最新的请求上下文
const currentRequestContextRef = useRef(null);
// 文件夹切换防抖
@@ -208,7 +213,7 @@ function MainContent() {
/>
</div>
<div className="text-xs text-blue-600 dark:text-blue-400">
已处理 {scanProgress?.current || 0} / {scanProgress?.total || 0} 张图片
已处理 {scanProgress.processed} / {scanProgress.total} 个文件
{getEstimatedTime() && ` · ${getEstimatedTime()}`}
</div>
</div>
@@ -219,7 +224,7 @@ function MainContent() {
<div className="px-4 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between text-sm">
<span className="text-gray-600 dark:text-gray-400">
已加载 {images.length} / {imageLoadingState.totalCount} 张
已加载 {images.length} / {imageLoadingState.totalCount} 个文件
</span>
<div className="w-32 h-1.5 bg-gray-200 rounded-full overflow-hidden">
<div
@@ -236,7 +241,39 @@ function MainContent() {
{(!selectedFolder && !searchKeywords && filters.formats.length === 0 && !favoritesView && (!foldersLoaded || folders.length > 0)) ? (
<Dashboard />
) : (
<ImageWaterfall />
<>
{/* 搜索结果工具条:对模糊命中的全部文件批量重命名 */}
{searchKeywords && (
<div className="px-3 sm:px-5 pt-3 flex items-center gap-2 flex-wrap">
<span className="text-xs text-gray-500 dark:text-gray-400">
搜索「{searchKeywords}」的模糊匹配结果
</span>
<button
onClick={() => setSearchRenameOpen(true)}
className="inline-flex items-center gap-1.5 text-xs px-2.5 py-1 rounded-lg bg-violet-500 text-white hover:bg-violet-600 transition-colors"
>
<PencilLine className="w-3.5 h-3.5" />
批量重命名搜索结果…
</button>
</div>
)}
<ImageWaterfall />
{/* 搜索结果批量重命名 */}
{searchRenameOpen && (
<BatchRenameModal
isOpen={searchRenameOpen}
folder={selectedFolder}
libraryId={currentLibraryId}
scope="search"
keywords={searchKeywords}
onClose={() => setSearchRenameOpen(false)}
onFinished={() => {
setSearchRenameOpen(false);
useImageStore.getState().bumpRefresh();
}}
/>
)}
</>
)}
</div>
</div>
+1 -1
View File
@@ -221,7 +221,7 @@ export default function MergeCollage({ image, libraryId, onMerge, setStatus, set
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `*** ${getToken()}`
Authorization: `Bearer ${getToken()}`
},
body: JSON.stringify({
libraryId,
+1 -1
View File
@@ -40,7 +40,7 @@ function RatingToast({ isVisible, rating, count, onClose, duration = 2000 }) {
</div>
<span className="text-sm font-medium">
{rating === 0 ? '已取消评分' : `已评 ${rating} 星`}
{count > 1 ? ` (${count} 张)` : ''}
{count > 1 ? ` (${count} 个)` : ''}
</span>
</div>
</div>
+61 -20
View File
@@ -9,13 +9,14 @@ import { imageAPI, fileAPI } from '../api';
import JSZip from 'jszip';
import RatingStars from './RatingStars';
import { createLogger } from '../utils/logger';
import { typeMeta, typeCountsOf, countLabel, typeLabelOf } from '../utils/fileTypes';
const logger = createLogger('RightPanel');
function RightPanel() {
const { currentLibraryId } = useLibraryStore();
const { selectedImage, selectedImages, selectedFolder, selectedFolderItem, images, setSelectedImage, setSelectedImages, updateImage } = useImageStore();
const { setMobileView, isResizingPanels, resizingSide, setEditingImage } = useUIStore();
const { setMobileView, isResizingPanels, resizingSide, setEditingImage, setVideoEditFile } = useUIStore();
const { copyToClipboard } = useClipboardStore();
const [isMobile, setIsMobile] = useState(false);
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
@@ -50,6 +51,8 @@ function RightPanel() {
// 判断是单选还是多选
const isMultiSelect = actualSelectedCount > 1;
const displayImage = selectedImages.length > 0 ? selectedImages[0] : selectedImage;
// 视频文件判定:右侧面板按文件类型展示,视频不再套用图片文案/操作
const singleIsVideo = !isMultiSelect && (displayImage?.fileType === 'video');
const { getCurrentLibrary } = useLibraryStore();
const currentLibrary = getCurrentLibrary();
@@ -319,7 +322,7 @@ function RightPanel() {
setSelectedImages(updatedSelectedImages);
}
logger.file(`已更新 ${paths.length} 张图片的评分为 ${newRating} 星`);
logger.file(`已更新 ${paths.length} 个文件的评分为 ${newRating} 星`);
} catch (error) {
logger.error('更新评分失败:', error);
alert('更新评分失败: ' + (error.message || '未知错误'));
@@ -597,7 +600,14 @@ function RightPanel() {
// 2. 获取原图URL,写入系统剪贴板
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
// 视频无法转换为图片写入系统剪贴板,仅保留应用内复制(供粘贴移动)
if (selectedImage?.fileType === 'video') {
setImageCopied(true);
setTimeout(() => setImageCopied(false), 2000);
return;
}
// 方案1:尝试现代 Clipboard API(需要 HTTPS)
if (isClipboardApiSupported()) {
try {
@@ -770,6 +780,10 @@ function RightPanel() {
return selectedImage ? [selectedImage] : [];
};
// 选中集合类型计数(由类型注册表驱动文案:图片/视频/文档…混合自动按"文件")
const selectionTypeCounts = typeCountsOf(getImagesToProcess());
const selectionTypeLabel = typeLabelOf(selectionTypeCounts);
// 批量复制图片
const copyMultipleImages = async () => {
try {
@@ -1083,15 +1097,16 @@ function RightPanel() {
const totalCount = folderImages.length;
const totalSize = folderImages.reduce((sum, img) => sum + (img.size || 0), 0);
return { totalCount, totalSize };
const folderTypeCounts = typeCountsOf(folderImages);
return { totalCount, totalSize, folderTypeCounts };
};
// ========== 文件夹详情渲染 ==========
if (isShowingFolder) {
const folderPath = selectedFolderItem.path;
const folderName = selectedFolderItem.name;
const { totalCount, totalSize } = getFolderStats(folderPath);
const { totalCount, totalSize, folderTypeCounts } = getFolderStats(folderPath);
const fullPath = currentLibrary?.path
? normalizePath(`${currentLibrary.path}${getPathSeparator()}${folderPath}`)
: folderPath;
@@ -1148,8 +1163,8 @@ function RightPanel() {
)}
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">包含图片:</span>
<p className="text-gray-900 dark:text-gray-100">{totalCount} 张(含子文件夹)</p>
<span className="text-gray-500 dark:text-gray-400">包含:</span>
<p className="text-gray-900 dark:text-gray-100">{countLabel(totalCount, folderTypeCounts)}(含子文件夹)</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">总大小:</span>
@@ -1200,7 +1215,7 @@ function RightPanel() {
<span>
{isExportingFolder
? `打包中... ${folderExportProgress}%`
: `导出文件夹 (${totalCount} 张)`
: `导出文件夹 (${countLabel(totalCount, folderTypeCounts)})`
}
</span>
</div>
@@ -1251,7 +1266,7 @@ function RightPanel() {
}
}
}}
title="双击查看第一张图片"
title="双击查看原文件"
>
{(() => {
const imagesToShow = getImagesToProcess().slice(0, 5);
@@ -1312,7 +1327,16 @@ function RightPanel() {
}}
title="双击查看原文件"
>
{imageUrl ? (
{singleIsVideo ? (
// 视频:直接播放原文件(不再以图片缩略图形式展示)
<video
src={getOriginalUrl()}
poster={imageUrl || undefined}
controls
preload="metadata"
className="w-full h-full object-contain bg-black"
/>
) : imageUrl ? (
<img
src={imageUrl}
alt={displayImage.filename}
@@ -1346,7 +1370,7 @@ function RightPanel() {
<div className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0">
<div>
<h3 className="text-xs font-semibold text-gray-700 dark:text-gray-300 mb-2">
{isMultiSelect ? `已选择 ${actualSelectedCount} 张图片` : '基本信息'}
{isMultiSelect ? `已选择 ${countLabel(actualSelectedCount, selectionTypeCounts)}` : '基本信息'}
</h3>
<div className="space-y-2 text-xs">
{isMultiSelect ? (
@@ -1359,7 +1383,7 @@ function RightPanel() {
<>
<div>
<span className="text-gray-500 dark:text-gray-400">数量:</span>
<p className="text-gray-900 dark:text-gray-100 text-xs">{stats.count} 张图片</p>
<p className="text-gray-900 dark:text-gray-100 text-xs">{countLabel(stats.count, selectionTypeCounts)}</p>
</div>
<div>
<span className="text-gray-500 dark:text-gray-400">评分:</span>
@@ -1492,6 +1516,14 @@ function RightPanel() {
<span className="text-gray-500 dark:text-gray-400">尺寸:</span>
<p className="text-gray-900 dark:text-gray-100 text-xs">{selectedImage.width} × {selectedImage.height}</p>
</div>
{singleIsVideo && selectedImage.duration > 0 && (
<div>
<span className="text-gray-500 dark:text-gray-400">时长:</span>
<p className="text-gray-900 dark:text-gray-100 text-xs font-mono tabular-nums">
{Math.floor(selectedImage.duration / 60)}:{String(Math.floor(selectedImage.duration % 60)).padStart(2, '0')}
</p>
</div>
)}
<div>
<span className="text-gray-500 dark:text-gray-400">文件大小:</span>
<p className="text-gray-900 dark:text-gray-100 text-xs">{formatFileSize(selectedImage.size)}</p>
@@ -1552,7 +1584,7 @@ function RightPanel() {
</div>
{isMultiSelect && (
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
已选择 {actualSelectedCount} 张图片的共同父路径
已选择 {countLabel(actualSelectedCount, selectionTypeCounts)}的共同父路径
</p>
)}
</div>
@@ -1563,16 +1595,23 @@ 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)}
onClick={() => {
if (singleIsVideo) {
// 视频 → 视频编辑弹窗(水印/字幕声音)
setVideoEditFile(selectedImage);
} else {
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>
编辑图片
{singleIsVideo ? '编辑视频' : '编辑图片'}
</button>
)}
{/* 复制按钮 */}
@@ -1587,12 +1626,14 @@ function RightPanel() {
{imageCopied ? (
<>
<Check className="w-4 h-4" />
<span>已复制{isMultiSelect ? ` ${actualSelectedCount} 张` : ''}</span>
<span>已复制{isMultiSelect ? ` ${countLabel(actualSelectedCount, selectionTypeCounts)}` : ''}</span>
</>
) : (
<>
<Copy className="w-4 h-4" />
<span>复制图片{isMultiSelect ? ` (${actualSelectedCount})` : ''}</span>
<span>
{`复制${singleIsVideo ? '视频' : selectionTypeLabel}${isMultiSelect ? ` (${actualSelectedCount})` : ''}`}
</span>
</>
)}
</button>
@@ -1608,7 +1649,7 @@ function RightPanel() {
<span>
{isExporting
? `打包中... ${exportProgress}%`
: `导出图片${isMultiSelect ? ` (${actualSelectedCount})` : ''}`
: `导出${singleIsVideo ? '视频' : selectionTypeLabel}${isMultiSelect ? ` (${actualSelectedCount})` : ''}`
}
</span>
</div>
+1 -1
View File
@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react';
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink, Wand2 } from 'lucide-react';
import { settingsAPI } from '../api';
const APP_VERSION = 'v1.4.1';
const APP_VERSION = 'v1.4.8';
const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
/**
+19 -1
View File
@@ -12,6 +12,7 @@ import UndoToast from './UndoToast';
import FolderSelector from './FolderSelector';
import ConflictDialog from './ConflictDialog';
import BatchWatermarkModal from './BatchWatermarkModal';
import BatchRenameModal from './BatchRenameModal';
import { createLogger } from '../utils/logger';
const logger = createLogger('Sidebar');
@@ -54,6 +55,7 @@ function Sidebar() {
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, folder: null });
// 批量水印弹窗 { mode: 'add'|'remove', folder }
const [batchWatermark, setBatchWatermark] = useState(null);
const [batchRename, setBatchRename] = useState(null);
const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
const [dragOverFolder, setDragOverFolder] = useState(null); // 拖拽悬停的文件夹
@@ -1513,6 +1515,18 @@ function Sidebar() {
bumpRefresh(); // 让图片区重新加载(覆盖模式下缩略图已更新)
}}
/>
{/* 批量重命名弹窗 */}
<BatchRenameModal
isOpen={!!batchRename}
folder={batchRename?.folder}
libraryId={currentLibraryId}
onClose={() => setBatchRename(null)}
onFinished={(result) => {
logger.file(`批量重命名完成: ${batchRename?.folder}`, result);
bumpRefresh(); // 让图片区重新加载(文件名/路径已更新)
}}
/>
{/* Library Management */}
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
@@ -1718,7 +1732,7 @@ function Sidebar() {
<div className="w-5 mr-1" />
<Folder className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
<span className="text-sm text-gray-700 dark:text-gray-200 font-medium flex-1">
全部图片
全部
</span>
<span className="text-xs text-gray-500 dark:text-gray-300 ml-2">
{totalImageCount}
@@ -1779,6 +1793,10 @@ function Sidebar() {
menuItems.rename(() => handleStartRenameFolder(contextMenu.folder)),
menuItems.move(() => handleMoveFolderClick(contextMenu.folder.path)),
menuItems.divider(),
menuItems.batchRename(() => {
setContextMenu({ isOpen: false, position: null, folder: null });
setBatchRename({ folder: contextMenu.folder.path });
}),
menuItems.batchAddWatermark(() => {
setContextMenu({ isOpen: false, position: null, folder: null });
setBatchWatermark({ mode: 'add', folder: contextMenu.folder.path });
+13 -2
View File
@@ -6,6 +6,14 @@
import { useState } from 'react';
import { X, Droplets, Eraser, Type, Scissors, Loader2 } from 'lucide-react';
import { imageAPI } from '../api';
import { getToken } from '../api/client';
// 后端错误可能为字符串或 {code,message} 对象,统一取可读文本
const errText = (e, fallback) => {
if (!e) return fallback;
if (typeof e === 'string') return e;
return e.message || JSON.stringify(e);
};
const ACTIONS = [
{ key: 'watermark-add', label: '加水印', icon: Droplets },
@@ -109,11 +117,14 @@ function VideoEditModal({ file, libraryId, onClose, onDone }) {
try {
const res = await fetch('/api/video/edit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`
},
body: JSON.stringify({ libraryId, path: file.path, action, options, output: outputMode })
});
const data = await res.json().catch(() => ({}));
if (!res.ok || data.error) throw new Error(data.error || `处理失败 (${res.status})`);
if (!res.ok || data.error) throw new Error(errText(data.error, `处理失败 (${res.status})`));
onDone && onDone(data.path);
onClose();
} catch (e) {
+2
View File
@@ -11,6 +11,7 @@ export const useImageStore = create((set, get) => ({
selectedImage: null,
selectedImages: [],
totalImageCount: 0,
typeCounts: {}, // 按文件类型计数 { image: 102, video: 181, document: 73 }
totalSize: 0, // 素材库总大小(字节)
// 文件夹
@@ -113,6 +114,7 @@ export const useImageStore = create((set, get) => ({
// 统计
setTotalImageCount: (count) => set({ totalImageCount: count }),
setTypeCounts: (counts) => set({ typeCounts: counts || {} }),
setTotalSize: (size) => set({ totalSize: size }),
// 加载状态
+4
View File
@@ -22,6 +22,10 @@ export const useUIStore = create((set) => ({
editingImage: null,
setEditingImage: (image) => set({ editingImage: image }),
// 视频编辑弹窗(打开的视频记录,null=关闭;右侧面板与瀑布流共用)
videoEditFile: null,
setVideoEditFile: (file) => set({ videoEditFile: file }),
// 合拼种子图(多选后点「合拼」带入编辑器,null=无)
mergeImages: null,
setMergeImages: (images) => set({ mergeImages: images }),
+82
View File
@@ -0,0 +1,82 @@
/**
* 文件类型注册表(单一数据源)
*
* 所有"图片/视频/文档…张/个"文案与图标都从这里取,
* 新增文件类型只需在 TABLE 加一行,全站文案与统计卡自动识别。
*/
import { Image as ImageIcon, Video, FileText, File, Music, PenTool, HelpCircle } from 'lucide-react';
const TABLE = {
image: { label: '图片', unit: '张', icon: ImageIcon },
video: { label: '视频', unit: '个', icon: Video },
audio: { label: '音频', unit: '个', icon: Music },
document: { label: '文档', unit: '个', icon: FileText },
design: { label: '设计', unit: '个', icon: PenTool },
other: { label: '其他', unit: '个', icon: HelpCircle },
};
/**
* 按注册表顺序返回类型计数条目(图例等排序稳定展示用);
* 注册表之外的未知类型键附在末尾。
* @param {Object} typeCounts - { image: 102, video: 181 }
* @returns {Array<[string, number]>}
*/
export function orderedTypeEntries(typeCounts) {
const c = typeCounts || {};
const known = Object.keys(TABLE).filter((k) => (c[k] || 0) > 0).map((k) => [k, c[k]]);
const extra = Object.entries(c).filter(([k, n]) => n > 0 && !(k in TABLE));
return [...known, ...extra];
}
/** 未知类型兜底:一律按"文件" */
const FALLBACK = { label: '文件', unit: '个', icon: File };
/**
* 单个文件的类型元信息
* @param {string} fileType - image | video | document | ...
* @returns {{label, unit, icon}}
*/
export function typeMeta(fileType) {
return TABLE[fileType] || FALLBACK;
}
/**
* 从条目列表聚合类型计数 { image: 2, video: 1 }
* @param {Array<{fileType?: string}>} items
*/
export function typeCountsOf(items) {
const counts = {};
for (const it of items || []) {
const t = it?.fileType || 'image';
counts[t] = (counts[t] || 0) + 1;
}
return counts;
}
/**
* 集合计数文案(按类型自动识别):
* - 单一已知类型:`102 张图片` / `181 个视频`
* - 多类型混合、未知类型、或没给计数:`356 个文件`
*
* @param {number} count - 总数
* @param {Object} [typeCounts] - { image: 102, video: 181, document: 73 }
*/
export function countLabel(count, typeCounts) {
const entries = Object.entries(typeCounts || {}).filter(([, n]) => n > 0);
if (entries.length === 1) {
const { label, unit } = typeMeta(entries[0][0]);
return `${count} ${unit}${label}`;
}
return `${count} 个文件`;
}
/**
* 集合的类型名词(用于"复制图片/导出视频"等动词文案):
* - 单一类型:'图片' / '视频' / '文档'
* - 多类型混合或未知:'文件'
*/
export function typeLabelOf(typeCounts) {
const entries = Object.entries(typeCounts || {}).filter(([, n]) => n > 0);
if (entries.length === 1) return typeMeta(entries[0][0]).label;
return FALLBACK.label;
}