Peach: Local-first video metadata scraper and media manager.
fix(web): 支持动态文案编辑并对齐清理提示操作
longmeidaob5dd99bf9adc
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 49be38cc4..8f07cf54f 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -486,9 +486,10 @@ Windows 托盘在取得单实例锁后启动独立监视器。监视器用 Win32页面地址加 `?edit` 开启文字编辑,悬停文字显示编辑范围,点文字在原位修改,回车或点别处保存、Esc 取消。按钮和链接的文字使用贴在文字位置的输入框。「暂停编辑」可继续操作页面。-静态文案写回 `web/index.html` 或 `frontend/src` 中选定的来源;同一文字有多个位置时需选择来源。-保存前校验源文件摘要,备份位于 `build/copy-editor/backups/`。React 文案重建前端后在普通模式生效。-修改记录可从工具栏导出。界面里的馆藏数据与动态计数没有静态文案来源,不能借此修改 Peach 数据库。+静态文案写回 `web/index.html`、`frontend/src` 或馆藏上传与处理模块中选定的来源;同一文字有多个位置时需选择来源。+馆藏处理的动态句子显示 `{problems}` 等占位符,只修改周围文字,保留每个占位符。数量随任务变化,不能借此修改馆藏数据。+保存直接写回源码并更新当前页面,无需导出。保存前校验源文件摘要,备份位于 `build/copy-editor/backups/`。React 文案重建前端后在普通模式生效,Python 文案重载服务后用于新生成的提示。+「导出修改」提供一份额外的修改记录,不承担源码保存。工具脚本位于 `scripts/dev/`,不作为网页资产分发;冻结的发布包不提供改字端点。演示站的 `?edit` 只保存当前浏览器的文案草稿,可导出,普通访问不应用草稿。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex ef08d4199..e0dffe497 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -689,8 +689,8 @@ Python 复用 MIT 许可的 [Ruff](https://docs.astral.sh/ruff/) 0.17.0,版本`scripts/dev/copy-editor.js` 复用官网本地预览的 `edit-client.js` 交互:文字范围提示、原位编辑、按钮文字就近输入、回车和失焦保存、Esc 取消。改字浮条使用多选操作条的 `data-selection-dock`、`data-glass-pane` 与 `data-batch-scope` 样式,几何、玻璃、字体和按钮共享;窄屏状态提示独占一行。-应用的 React 与动态页面使用现有静态文案定位、摘要校验和备份入口;演示站使用浏览器草稿。两者只在 `?edit` 启用,无新增依赖。-馆藏上传的动态说明与字段复用同一入口,Python 源文件仅纳入 `src/peach/library_sharing.py`,其他 Python 文件不属于改字范围。+应用的 React 与动态页面使用源码定位、摘要校验和备份入口;演示站使用浏览器草稿。两者只在 `?edit` 启用,无新增依赖。+Python 源文件纳入 `src/peach/library_sharing.py` 与 `src/peach/library_processing.py`。动态句子复用标准库 `ast`、`string.Formatter` 定位 f-string 与相邻字符串,编辑时显示命名占位符,保存时校验占位符齐全且各出现一次。求值表达式与格式保留在 AST 中,当前数量只用于显示;其他 Python 文件不属于改字范围。## 馆藏处理控制与耗时预估diff --git a/frontend/e2e/copy-editor.test.ts b/frontend/e2e/copy-editor.test.tsindex 1dfbfbc9c..3e019eaec 100644--- a/frontend/e2e/copy-editor.test.ts+++ b/frontend/e2e/copy-editor.test.ts@@ -9,6 +9,65 @@ describe('原位改字', () => {before(async () => { browser = await launch(); });after(async () => { await browser?.close(); });for (const viewport of VIEWPORTS) {+ it(`连续改字记录显示最终文案并终止循环(${viewport.name})`, async () => {+ const context = await browser.newContext({ viewport });+ try {+ const page = await context.newPage();+ await page.route('https://copy.example/**', route => route.fulfill({+ contentType: 'text/html; charset=utf-8', body: '<meta charset="utf-8"><body><p id="copy">说明</p><p id="cycle">循环甲</p></body>',+ }));+ await page.goto('https://copy.example/?edit');+ await page.evaluate(() => localStorage.setItem('peach.copy-edits.v1', JSON.stringify({+ 说明: '中间文案', 中间文案: '最终文案', 循环甲: '循环乙', 循环乙: '循环甲',+ })));+ await page.addScriptTag({ content: await readFile(new URL('../../scripts/dev/copy-editor.js', import.meta.url), 'utf8') });+ assert.equal(await page.locator('#copy').innerText(), '最终文案');+ assert.equal(await page.locator('#cycle').innerText(), '循环甲');+ } finally { await context.close(); }+ });++ it(`源码模板保存与占位符失败反馈(${viewport.name})`, async () => {+ const context = await browser.newContext({ viewport });+ try {+ const page = await context.newPage();+ const original = '768 项需要处理,其中 533 项是来源限流;其余可重试。';+ const template = '{problems} 项需要处理,其中 {paused} 项是来源限流;其余可重试。';+ const candidate = { file: 'src/peach/library_processing.py', line: 1, template };+ const saves: unknown[] = [];+ await page.route('https://copy.example/**', async route => {+ const path = new URL(route.request().url()).pathname;+ if (path === '/dev/copy-edits') return route.fulfill({ json: {} });+ if (path === '/dev/copy-candidates') return route.fulfill({ json: [candidate] });+ if (path === '/dev/copy-save') {+ const body = route.request().postDataJSON(); saves.push(body);+ return body.replacement.includes('{paused}')+ ? route.fulfill({ json: { ok: true, text: '待处理 768 项,限流 533 项。' } })+ : route.fulfill({ status: 409, json: { error: '请保留全部占位符,各出现一次' } });+ }+ return route.fulfill({ contentType: 'text/html; charset=utf-8',+ body: `<meta charset="utf-8"><body data-peach-copy-mode="source"><p id="copy" style="margin:60px 20px">${original}</p></body>` });+ });+ await page.goto('https://copy.example/?edit');+ await page.addScriptTag({ content: await readFile(new URL('../../scripts/dev/copy-editor.js', import.meta.url), 'utf8') });+ await page.locator('#copy').click({ position: { x: 5, y: 8 } });+ const inline = page.locator('#copy [contenteditable]');+ await inline.waitFor();+ assert.equal(await inline.innerText(), template);+ await inline.fill('处理 {problems} 项');+ await inline.press('Enter');+ await page.getByRole('status').filter({ hasText: '没保存:请保留全部占位符' }).waitFor();+ assert.equal(await page.locator('#copy').innerText(), original);+ assert.equal(await page.evaluate(() => localStorage.getItem('peach.copy-edits.v1')), null);+ await page.locator('#copy').click({ position: { x: 5, y: 8 } });+ await inline.fill('待处理 {problems} 项,限流 {paused} 项。');+ await inline.press('Enter');+ await page.getByRole('status').filter({ hasText: '已保存修改' }).waitFor();+ assert.equal(await page.locator('#copy').innerText(), '待处理 768 项,限流 533 项。');+ assert.deepEqual(saves[1], { original, replacement: '待处理 {problems} 项,限流 {paused} 项。', candidate });+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);+ } finally { await context.close(); }+ });+it(`改字浮条与多选操作条共享玻璃、排版与按钮(${viewport.name})`, async () => {const opened = await visit(browser, '/settings/library?section=' + encodeURIComponent('应用与维护') + '&edit', viewport);try {diff --git a/frontend/e2e/design-activity.test.ts b/frontend/e2e/design-activity.test.tsindex cee84c264..2b43eafdd 100644--- a/frontend/e2e/design-activity.test.ts+++ b/frontend/e2e/design-activity.test.ts@@ -26,6 +26,15 @@ describe('任务页云下载布局', () => {const page = opened.page;await page.locator('[data-download-id="1"]').waitFor();await settle(page);+ await page.waitForFunction(async () => {+ const images = document.querySelectorAll<HTMLImageElement>(+ '[data-download-id="1"] [data-download-cover] img, [data-download-id="1"] [data-media-avatar] img');+ if (images.length !== 2) return false;+ try {+ await Promise.all([...images].map(image => image.decode()));+ return [...images].every(image => image.complete && image.naturalWidth > 0);+ } catch { return false; }+ });const geometry = await page.locator('[data-download-id="1"]').evaluate((card) => {const heading = card.querySelector('strong')!;const titleContent = heading.querySelector('a') || heading;diff --git a/frontend/e2e/resource-cleanup-note.test.ts b/frontend/e2e/resource-cleanup-note.test.tsnew file mode 100644index 000000000..962cd5367--- /dev/null+++ b/frontend/e2e/resource-cleanup-note.test.ts@@ -0,0 +1,44 @@+import assert from 'node:assert/strict';+import { after, before, describe, it } from 'node:test';+import type { Browser } from 'playwright-core';+import { launch, layout, settle, visit, VIEWPORTS } from './harness.ts';++describe('资源清理提示与操作', () => {+ let browser: Browser;+ before(async () => { browser = await launch(); });+ after(async () => { await browser?.close(); });+ for (const viewport of VIEWPORTS) {+ it(`清理操作位于提示内并适应容器(${viewport.name})`, async () => {+ const opened = await visit(browser, '/resource-sync', viewport, async page => {+ await page.route('**/api/resource-sync/scan', route => route.fulfill({ json: {+ status: 'complete', scan_id: 'layout-fixture', missing: 1, purge: 1, vanish: 0, empty: 203,+ cache: { files: 1858, bytes: 232783872 },+ sources: [{ location: 'local', online: true, total: 2553, missing: 1, empty: 203, unreadable: 0 }],+ } }));+ await page.route('**/api/resource-sync/apply', route => route.fulfill({ json: { status: 'idle' } }));+ });+ try {+ const { page } = opened;+ await page.locator('#resource-sync').waitFor();+ await page.getByRole('button', { name: '清理失效条目', exact: true }).waitFor();+ await settle(page);+ const note = page.locator('#resource-sync [role="note"]').filter({ hasText: '清理内容' });+ assert.equal(await note.getByRole('button', { name: '清理失效条目', exact: true }).count(), 1);+ const boxes = await note.evaluate(node => {+ const box = (element: Element) => {+ const rect = element.getBoundingClientRect();+ return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom };+ };+ return { note: box(node), text: box(node.querySelector('[data-note-layout] > div')!),+ action: box(node.querySelector('[data-note-action]')!) };+ });+ assert.ok(boxes.action.left >= boxes.note.left && boxes.action.right <= boxes.note.right);+ assert.ok(boxes.action.bottom <= boxes.note.bottom);+ if (viewport.mobile) assert.ok(boxes.action.top >= boxes.text.bottom);+ else assert.ok(boxes.action.left >= boxes.text.right);+ assert.deepEqual((await layout(page)).offenders, []);+ assert.deepEqual(opened.problems, []);+ } finally { await opened.close(); }+ });+ }+});diff --git a/frontend/src/management.ts b/frontend/src/management.tsindex 4fa9d5f40..8b1e834bf 100644--- a/frontend/src/management.ts+++ b/frontend/src/management.ts@@ -4,8 +4,8 @@ import { islandButton, islandGlyph, islandSelect } from './island-skeleton';/* 「扫描与采集」「媒体修复」两张卡的正文。卡片本体由 React 画,骨架与遗留层的取数占位画的是同一段话:写两份的话,骨架上的那句会比真卡短一截,接管时整张卡跳一次。 */-export const SCAN_CARD_TEXT = '同步文件与影片资料,按设置生成本地视频预览。下拉菜单可选择只扫描文件、同步已入库影片、生成预览或补全资料。';-export const REPAIR_CARD_TEXT = '修缺时间戳表(播放卡顿)和缺索引(打不开)的 MP4。常看的片子先修。';+export const SCAN_CARD_TEXT = '扫描文件并更新馆藏,读取本地资料、补齐缺失资料和封面,按设置生成视频预览。';+export const REPAIR_CARD_TEXT = '部分视频文件可能播放卡顿、打不开,修复缺时间戳表和缺索引的问题。';const bar = '<span class="skeleton skeleton-text" aria-hidden="true"></span>';/* 要等数据才能执行的键是真的按不了:原生 `disabled` 挡住点击与聚焦,`data-skeleton-action`diff --git a/frontend/src/react/data-cleanup/orphan-records-card.tsx b/frontend/src/react/data-cleanup/orphan-records-card.tsxindex 15995338d..3d1f4073a 100644--- a/frontend/src/react/data-cleanup/orphan-records-card.tsx+++ b/frontend/src/react/data-cleanup/orphan-records-card.tsx@@ -132,7 +132,7 @@ export function OrphanRecordsCard({ toast }: { toast(message: string): void }) {</Fieldset>: <DataTable label="文件已消失的作品" items={items} columns={columns}title="文件已丢失的记录" titleId="orphan-records-title" unit="条作品"- description="这些作品的文件已找不到,喜欢、稍后看、播放列表与观看历史仍保留。选择替代文件后,这些记录会转移到该文件,旧作品记录随之删除。"+ description="这些作品的源文件已删除,喜欢、稍后看、播放列表与观看历史仍保留。选择替代文件后,这些记录会转移到该文件,旧作品记录随之删除。"rowId={(item) => String(item.id)} rowLabel={(item) => item.name}selected={selected} onSelected={setSelected}actions={(chosen) => <Button variant="danger" size="small" disabled={!chosen.length}diff --git a/frontend/src/react/data-cleanup/resource-sync-card.tsx b/frontend/src/react/data-cleanup/resource-sync-card.tsxindex b89e341e5..0967847b1 100644--- a/frontend/src/react/data-cleanup/resource-sync-card.tsx+++ b/frontend/src/react/data-cleanup/resource-sync-card.tsx@@ -158,16 +158,15 @@ export function ResourceSyncCard(result = (<><ScanResult scan={state} />- {changes ? <Note tone="neutral" title="清理内容">{applyPlanText(state)}</Note> : null}- <div className="flex flex-wrap items-center justify-end gap-2">- {changes- ? <Button variant="danger" {...busyProps(cleaning)} onClick={() => runApply(state)}>+ {changes+ ? <Note tone="neutral" title="清理内容" action={+ <Button variant="danger" {...busyProps(cleaning)} onClick={() => runApply(state)}>{cleaning ? '正在复核并清理…' : APPLY_LABEL}</Button>- : <p className="mr-auto text-body-regular text-notification-success-foreground">- 已检查可访问的来源,没有待清理的记录、空文件夹或缓存。- </p>}- </div>+ }>{applyPlanText(state)}</Note>+ : <p className="mr-auto text-body-regular text-notification-success-foreground">+ 已检查可访问的来源,没有待清理的记录、空文件夹或缓存。+ </p>}</>);}diff --git a/scripts/dev/copy-editor.js b/scripts/dev/copy-editor.jsindex dc177d84b..250955a01 100644--- a/scripts/dev/copy-editor.js+++ b/scripts/dev/copy-editor.js@@ -39,9 +39,14 @@for (let node = walker.nextNode(); node; node = walker.nextNode()) {if (!node.parentElement || node.parentElement.closest(skip)) continue;const original = originals.get(node) || node.data.trim();- if (Object.hasOwn(edits, original) && original !== edits[original]) {+ let replacement = edits[original];+ const seen = new Set([original]);+ while (Object.hasOwn(edits, replacement) && !seen.has(replacement)) {+ seen.add(replacement); replacement = edits[replacement];+ }+ if (Object.hasOwn(edits, original) && original !== replacement) {originals.set(node, original);- const next = /^\s*/.exec(node.data)[0] + edits[original] + /\s*$/.exec(node.data)[0];+ const next = /^\s*/.exec(node.data)[0] + replacement + /\s*$/.exec(node.data)[0];if (node.data !== next) node.data = next;}}@@ -69,8 +74,20 @@const node = textAt(event.clientX, event.clientY); if (!node) return;event.preventDefault(); event.stopImmediatePropagation(); begin(node);}, true);- function begin(node) {- const before = node.data, lead = /^\s*/.exec(before)[0], trail = /\s*$/.exec(before)[0], core = before.trim(); let box;+ async function begin(node) {+ const before = node.data, lead = /^\s*/.exec(before)[0], trail = /\s*$/.exec(before)[0], originalText = before.trim();+ let core = originalText, candidate = null, box;+ if (source) {+ saving = true; bar.setAttribute('aria-busy', 'true'); say('查找文案来源…');+ try {+ const response = await fetch('/dev/copy-candidates?text=' + encodeURIComponent(originalText)), candidates = await response.json();+ if (!response.ok || !candidates.length) throw Error('这段文字尚无可编辑的文案来源');+ candidate = candidates.length === 1 ? candidates[0] : await choose(candidates, rectsOf(node)[0]);+ if (!candidate || !node.isConnected || node.data !== before) { say('已取消'); return; }+ core = candidate.template || originalText;+ } catch (error) { say(error.message); return; }+ finally { saving = false; bar.removeAttribute('aria-busy'); }+ }if (node.parentElement.closest('button,a,[role=button]')) {const rect = rectsOf(node)[0], style = getComputedStyle(node.parentElement);box = document.createElement('input'); box.value = core; box.dataset.copyEditor = ''; box.dataset.copyInput = '';@@ -81,10 +98,10 @@box = document.createElement('span'); box.dataset.copyInline = ''; box.contentEditable = 'plaintext-only'; box.spellcheck = false; box.textContent = core;node.replaceWith(...[lead, box, trail].filter(Boolean));}- box.setAttribute('aria-label', '修改文字'); editing = { node, before, lead, trail, core, box, original: originals.get(node) || core }; box.focus();+ box.setAttribute('aria-label', '修改文字'); editing = { node, before, lead, trail, core, box, candidate, originalText, original: originals.get(node) || originalText }; box.focus();if (box.tagName === 'INPUT') box.select();else { const range = document.createRange(); range.selectNodeContents(box); getSelection().removeAllRanges(); getSelection().addRange(range); }- highlight.style.display = 'none'; say('Enter 保存 · Esc 取消');+ highlight.style.display = 'none'; say(candidate?.template ? '保留 {占位符},只改文字 · Enter 保存 · Esc 取消' : 'Enter 保存 · Esc 取消');box.addEventListener('keydown', event => {event.stopPropagation(); if (event.isComposing) return;if (event.key === 'Enter') { event.preventDefault(); commit(); }@@ -111,23 +128,19 @@async function commit(cancel = false) {const ed = editing; if (!ed) return; editing = null;const replacement = (ed.box.tagName === 'INPUT' ? ed.box.value : ed.box.textContent).replace(/\s*\n\s*/g, ' ').trim();- const connected = ed.node.isConnected || ed.box.isConnected, rect = ed.box.getBoundingClientRect(); putBack(ed);+ const connected = ed.node.isConnected || ed.box.isConnected; putBack(ed);if (cancel || !connected) { say('已取消'); return; }if (replacement === ed.core) return;if (!replacement) { say('不能留空,没有保存'); return; }saving = true; bar.setAttribute('aria-busy', 'true'); say('保存中…');try {- let message = '已保存草稿';+ let message = '已保存草稿', text = replacement;if (source) {- const response = await fetch('/dev/copy-candidates?text=' + encodeURIComponent(ed.core)), candidates = await response.json();- if (!response.ok || !candidates.length) throw Error('未找到静态源文案');- const candidate = candidates.length === 1 ? candidates[0] : await choose(candidates, rect);- if (!candidate) { say('已取消'); return; }- const saved = await fetch('/dev/copy-save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ original: ed.core, replacement, candidate }) });+ const saved = await fetch('/dev/copy-save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ original: ed.originalText, replacement, candidate: ed.candidate }) });const result = await saved.json(); if (!saved.ok) throw Error(result.error || '保存失败');- message = '已保存修改';+ text = result.text ?? replacement; message = '已保存修改';}- edits[ed.original] = replacement; originals.set(ed.node, ed.original); localStorage.setItem(key, JSON.stringify(edits)); ed.node.data = ed.lead + replacement + ed.trail;+ edits[ed.original] = text; originals.set(ed.node, ed.original); localStorage.setItem(key, JSON.stringify(edits)); ed.node.data = ed.lead + text + ed.trail;say(message);} catch (error) { ed.node.data = ed.before; say('没保存:' + error.message); }finally { saving = false; bar.removeAttribute('aria-busy'); apply(); }diff --git a/src/peach/dev_copy.py b/src/peach/dev_copy.pyindex 11fe7a296..04cfca246 100644--- a/src/peach/dev_copy.py+++ b/src/peach/dev_copy.py@@ -1,22 +1,99 @@-"""源码检出的改字工具:定位静态文案,核对文件摘要后保存。"""+"""源码检出的改字工具:定位文案与数量模板,核对文件摘要后保存。"""from __future__ import annotations+import ast+from collections import Counter+from copy import deepcopyimport hashlibimport jsonfrom pathlib import Pathimport re+from string import Formatterdef files(root: Path):yield root / "web/index.html"yield root / "src/peach/library_sharing.py"+ yield root / "src/peach/library_processing.py"yield from sorted((root / "frontend/src").rglob("*.js"))yield from sorted((root / "frontend/src").rglob("*.tsx"))yield from sorted((root / "frontend/src").rglob("*.ts"))+def _template_parts(node: ast.JoinedStr):+ """占位符只命名已有表达式,格式与求值代码由 AST 保管。"""+ fields = {}+ parts = []+ for value in node.values:+ if isinstance(value, ast.Constant):+ parts.append(value.value.replace("{", "{{").replace("}", "}}"))+ else:+ name = value.value.id if isinstance(value.value, ast.Name) else f"value{len(fields) + 1}"+ while name in fields:+ name += "_"+ fields[name] = value+ parts.append("{" + name + "}")+ return "".join(parts), fields+++def _python_candidates(source: str, original: str):+ tree = ast.parse(source)+ inside_template = {id(child) for node in ast.walk(tree) if isinstance(node, ast.JoinedStr)+ for child in ast.walk(node) if child is not node}+ lines = source.splitlines(keepends=True)++ def offset(line, column):+ return sum(map(len, lines[:line - 1])) + len(lines[line - 1].encode("utf-8")[:column].decode("utf-8"))++ for node in ast.walk(tree):+ if id(node) in inside_template:+ continue+ extra = {}+ if isinstance(node, ast.JoinedStr):+ template, fields = _template_parts(node)+ parsed = list(Formatter().parse(template))+ if not any(literal.strip() for literal, _, _, _ in parsed):+ continue+ pattern = "".join(re.escape(literal) + (f"(?P<{name}>.*?)" if name else "")+ for literal, name, _, _ in parsed)+ match = re.fullmatch(pattern, original, re.DOTALL)+ if not match or not fields:+ continue+ extra = {"template": template, "values": match.groupdict()}+ elif not isinstance(node, ast.Constant) or node.value != original:+ continue+ yield {"start": offset(node.lineno, node.col_offset),+ "end": offset(node.end_lineno, node.end_col_offset), "line": node.lineno,+ "quote": "", "python": True, **extra}+++def _python_replacement(source: str, selected: dict, replacement: str):+ expression = source[selected["start"]:selected["end"]]+ if "template" not in selected:+ return (json.dumps(replacement, ensure_ascii=False) if expression.startswith('"') else repr(replacement)), replacement+ node = ast.parse("(" + expression + ")", mode="eval").body+ _, fields = _template_parts(node)+ values, rendered, used = [], [], []+ try:+ for literal, name, spec, conversion in Formatter().parse(replacement):+ if literal:+ values.append(ast.Constant(literal))+ rendered.append(literal)+ if name is not None:+ if name not in fields or spec or conversion:+ raise ValueError("请保留原有占位符,只修改文字")+ used.append(name)+ values.append(deepcopy(fields[name]))+ rendered.append(selected["values"][name])+ except ValueError as error:+ raise ValueError("请保留原有占位符,只修改文字;字面花括号写成 {{ 和 }}") from error+ if Counter(used) != Counter(fields.keys()):+ raise ValueError("请保留全部占位符,各出现一次")+ return ast.unparse(ast.JoinedStr(values)), "".join(rendered)++def candidates(root: Path, original: str) -> list[dict]:if not isinstance(original, str) or not original.strip() or len(original) > 2000:- raise ValueError("请选择不超过 2000 字的静态文案")+ raise ValueError("请选择不超过 2000 字的文案")found = []for path in files(root):if not path.is_file() or ".test." in path.name:@@ -24,6 +101,11 @@ def candidates(root: Path, original: str) -> list[dict]:source = path.read_text(encoding="utf-8")if len(source) > 2_000_000:continue+ if path.suffix == ".py":+ found.extend({"file": path.relative_to(root).as_posix(),+ "hash": hashlib.sha256(source.encode()).hexdigest(), **candidate}+ for candidate in _python_candidates(source, original))+ continue# 只定位完整文字节点或完整字符串,避免改到标识和代码的一部分。pattern = re.compile(r"(?P<quote>['\"`])" + re.escape(original) + r"(?P=quote)|>\s*(?P<jsx>" + re.escape(original) + r")\s*<")for match in pattern.finditer(source):@@ -50,7 +132,10 @@ def save(root: Path, body: dict) -> dict:raise ValueError("不能修改这个文件")source = path.read_text(encoding="utf-8")quote = selected["quote"]- if quote:+ text = replacement+ if selected.get("python"):+ escaped, text = _python_replacement(source, selected, replacement)+ elif quote:escaped = replacement.replace("\\", "\\\\").replace(quote, "\\" + quote).replace("\n", "\\n").replace("\r", "\\r")if quote == "`":escaped = escaped.replace("${", "\\${")@@ -65,6 +150,7 @@ def save(root: Path, body: dict) -> dict:path.write_text(source[:selected["start"]] + escaped + source[selected["end"]:], encoding="utf-8")record = root / "build/copy-editor/edits.json"edits = json.loads(record.read_text(encoding="utf-8")) if record.exists() else {}- edits[original] = replacement+ edits[original] = textrecord.write_text(json.dumps(edits, ensure_ascii=False, indent=2), encoding="utf-8")- return {"ok": True, "file": selected["file"], "needs_build": selected["file"].startswith("frontend/")}+ return {"ok": True, "file": selected["file"], "text": text,+ "needs_build": selected["file"].startswith("frontend/")}diff --git a/tests/test_dev_copy.py b/tests/test_dev_copy.pyindex aa7096459..248fe7890 100644--- a/tests/test_dev_copy.py+++ b/tests/test_dev_copy.py@@ -1,4 +1,4 @@-"""改字工具只保存静态源文案,冲突与代码路径不能误写。"""+"""改字工具保存源文案与动态模板,冲突与代码路径不能误写。"""from pathlib import Pathimport tempfileimport unittest@@ -6,6 +6,48 @@ from peach import dev_copyclass DevCopyTests(unittest.TestCase):+ def test_processing_template_keeps_live_values_and_validates_placeholders(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp).resolve()+ package = root / "src/peach"+ package.mkdir(parents=True)+ path = package / "library_processing.py"+ source = ("# 中文说明\n"+ "def summary(problems, paused):\n"+ " return (f'{problems} 项需要处理,其中 {paused} 项是来源限流;'\n"+ " '其余可重试。')\n")+ path.write_text(source, encoding="utf-8")+ original = "768 项需要处理,其中 533 项是来源限流;其余可重试。"+ candidate, = dev_copy.candidates(root, original)+ self.assertEqual(candidate["template"], "{problems} 项需要处理,其中 {paused} 项是来源限流;其余可重试。")+ for replacement in ["处理 {problems} 项", "处理 {unknown} 项", "处理 {problems!r}、{paused}", "{problems} {paused} {paused}"]:+ with self.assertRaises(ValueError):+ dev_copy.save(root, {"original": original, "replacement": replacement, "candidate": candidate})+ self.assertEqual(path.read_text(encoding="utf-8"), source)+ result = dev_copy.save(root, {"original": original,+ "replacement": "来源限流 {paused} 项,共 {problems} 项待处理。", "candidate": candidate})+ self.assertEqual(result["text"], "来源限流 533 项,共 768 项待处理。")+ namespace = {}+ exec(compile(path.read_text(encoding="utf-8"), str(path), "exec"), namespace)+ self.assertEqual(namespace["summary"](10, 3), "来源限流 3 项,共 10 项待处理。")+ self.assertEqual(len(list((root / "build/copy-editor/backups").rglob(path.name))), 1)+ with self.assertRaises(ValueError):+ dev_copy.save(root, {"original": original, "replacement": "{problems} {paused}", "candidate": candidate})++ def test_template_preserves_expressions_formatting_and_literal_braces(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp).resolve()+ package = root / "src/peach"+ package.mkdir(parents=True)+ path = package / "library_processing.py"+ path.write_text("def summary(total):\n return f'共 {{数量}} {total + 1:04d} 项'\n", encoding="utf-8")+ candidate, = dev_copy.candidates(root, "共 {数量} 0003 项")+ self.assertEqual(candidate["template"], "共 {{数量}} {value1} 项")+ dev_copy.save(root, {"original": "共 {数量} 0003 项", "replacement": "{{总数}} '{value1}' 项", "candidate": candidate})+ namespace = {}+ exec(compile(path.read_text(encoding="utf-8"), str(path), "exec"), namespace)+ self.assertEqual(namespace["summary"](4), "{总数} '0005' 项")+def test_library_notice_is_editable_and_other_python_files_are_excluded(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp).resolve()diff --git a/web/dist/peach-app.js b/web/dist/peach-app.jsindex 5de2e9485..c15c2c23f 100644--- a/web/dist/peach-app.js+++ b/web/dist/peach-app.js@@ -57938,7 +57938,7 @@ function QB({ label: e, icon: t, accent: n = 0, figure: r, footer: i }) {}//#endregion//#region src/management.ts-var $B = "同步文件与影片资料,按设置生成本地视频预览。下拉菜单可选择只扫描文件、同步已入库影片、生成预览或补全资料。", eV = "修缺时间戳表(播放卡顿)和缺索引(打不开)的 MP4。常看的片子先修。", tV = "<span class=\"skeleton skeleton-text\" aria-hidden=\"true\"></span>", nV = "type=\"button\" disabled data-skeleton-action", rV = "disabled data-skeleton-action", COe = "aria-disabled=\"true\"", iV = (e) => `<div class="peach-react"><div class="flex flex-col gap-4">${e}</div></div>`, aV = (e, t) => `<div data-geist-fieldset-content>+var $B = "扫描文件并更新馆藏,读取本地资料、补齐缺失资料和封面,按设置生成视频预览。", eV = "部分视频文件可能播放卡顿、打不开,修复缺时间戳表和缺索引的问题。", tV = "<span class=\"skeleton skeleton-text\" aria-hidden=\"true\"></span>", nV = "type=\"button\" disabled data-skeleton-action", rV = "disabled data-skeleton-action", COe = "aria-disabled=\"true\"", iV = (e) => `<div class="peach-react"><div class="flex flex-col gap-4">${e}</div></div>`, aV = (e, t) => `<div data-geist-fieldset-content><h3 class="text-title-2-medium text-text-primary">${e}</h3><p class="text-body-2-regular text-text-secondary">${t}</p></div>`;function wOe() {@@ -59312,7 +59312,7 @@ function dke({ toast: e }) {title: "文件已丢失的记录",titleId: "orphan-records-title",unit: "条作品",- description: "这些作品的文件已找不到,喜欢、稍后看、播放列表与观看历史仍保留。选择替代文件后,这些记录会转移到该文件,旧作品记录随之删除。",+ description: "这些作品的源文件已删除,喜欢、稍后看、播放列表与观看历史仍保留。选择替代文件后,这些记录会转移到该文件,旧作品记录随之删除。",rowId: (e) => String(e.id),rowLabel: (e) => e.name,selected: t,@@ -59471,26 +59471,20 @@ function hke({ toast: e }) {});else if (r?.status === "complete") {let e = oOe(r);- f = /* @__PURE__ */ (0, C.jsxs)(C.Fragment, { children: [- /* @__PURE__ */ (0, C.jsx)(AV, { scan: r }),- e ? /* @__PURE__ */ (0, C.jsx)(J, {- tone: "neutral",- title: "清理内容",- children: cOe(r)- }) : null,- /* @__PURE__ */ (0, C.jsx)("div", {- className: "flex flex-wrap items-center justify-end gap-2",- children: e ? /* @__PURE__ */ (0, C.jsx)(q, {- variant: "danger",- ...Y(a),- onClick: () => c(r),- children: a ? "正在复核并清理…" : DV- }) : /* @__PURE__ */ (0, C.jsx)("p", {- className: "mr-auto text-body-regular text-notification-success-foreground",- children: "已检查可访问的来源,没有待清理的记录、空文件夹或缓存。"- })- })- ] });+ f = /* @__PURE__ */ (0, C.jsxs)(C.Fragment, { children: [/* @__PURE__ */ (0, C.jsx)(AV, { scan: r }), e ? /* @__PURE__ */ (0, C.jsx)(J, {+ tone: "neutral",+ title: "清理内容",+ action: /* @__PURE__ */ (0, C.jsx)(q, {+ variant: "danger",+ ...Y(a),+ onClick: () => c(r),+ children: a ? "正在复核并清理…" : DV+ }),+ children: cOe(r)+ }) : /* @__PURE__ */ (0, C.jsx)("p", {+ className: "mr-auto text-body-regular text-notification-success-foreground",+ children: "已检查可访问的来源,没有待清理的记录、空文件夹或缓存。"+ })] });}return t.start.isError && !l && (f = /* @__PURE__ */ (0, C.jsxs)(C.Fragment, { children: [f, /* @__PURE__ */ (0, C.jsx)(J, {tone: "error",