Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(edit): 支持连续文案编辑并清理空样式

longmeidaod4068c6aa6c3
diff --git a/docs/REUSE.md b/docs/REUSE.md
index cb0dac025..7b3f57a45 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -805,7 +805,7 @@ Python 复用 MIT 许可的 [Ruff](https://docs.astral.sh/ruff/) 0.17.0,版本
## 原位改字
-`frontend/src/copy-editor-core.js` 是应用、官网与演示站的原位编辑核心,以 classic script 注册 `PeachCopyEditorCore`。核心负责文字命中、原位输入、回车和失焦保存、Esc 取消、连续草稿和 JSON 结果解析;`create` 的 `resolve`/`prepare`/`save`/`onSaved` 保留各端来源定位与保存入口。空字符串可作为删除结果,无法确认的保存响应保留核对提示。切换控件正常响应点击,Alt 点击进入文字编辑。官网与演示站按应用提交与 SHA256 同步核心,适配器先取得原始文字索引再运行页面脚本。
+`frontend/src/copy-editor-core.js` 是应用、官网与演示站的原位编辑核心,以 classic script 注册 `PeachCopyEditorCore`。核心负责文字命中、原位输入、回车和失焦保存、Esc 取消、连续草稿和 JSON 结果解析;`create` 的 `resolve`/`prepare`/`save`/`onSaved` 保留各端来源定位与保存入口。适配器可用 `element` 与 `nodes` 指定连续行内文字的共同编辑区域,`replaceTextParts` 将纯文字修改映射到原有节点,保留未改动片段的样式,并清理无内容且仅带样式属性的行内元素。空字符串可作为删除结果,无法确认的保存响应保留核对提示。切换控件正常响应点击,Alt 点击进入文字编辑。官网与演示站按应用提交与 SHA256 同步核心,适配器先取得原始文字索引再运行页面脚本。
应用适配器 `scripts/dev/copy-editor.js` 负责源码候选、草稿、工具条和自动生效状态。源码模式按顺序加载 `/dev/copy-editor-core.js` 与 `/dev/copy-editor.js`,动态文案保留模板占位符。
改字浮条使用多选操作条的 `data-selection-dock`、`data-glass-pane` 与 `data-batch-scope` 样式,几何、玻璃、字体和按钮共享;窄屏状态提示独占一行。
diff --git a/frontend/e2e/copy-editor.test.ts b/frontend/e2e/copy-editor.test.ts
index 430ea4e7a..e384c7b88 100644
--- a/frontend/e2e/copy-editor.test.ts
+++ b/frontend/e2e/copy-editor.test.ts
@@ -14,6 +14,44 @@ 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.setContent('<meta charset="utf-8"><style>[data-copy-highlight]{pointer-events:none}</style><p id="copy" style="margin:80px 20px">配置保存在 <code>/data</code>,媒体在 <code>/media</code>。</p>');
+ await page.addScriptTag({ content: await readFile(new URL('../src/copy-editor-core.js', import.meta.url), 'utf8') });
+ await page.evaluate(() => {
+ const core = (globalThis as any).PeachCopyEditorCore;
+ core.create({ resolve(node: Text) {
+ const element = node.parentElement!.closest('#copy');
+ if (!element) return null;
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT), nodes = [];
+ for (let part = walker.nextNode(); part; part = walker.nextNode()) nodes.push(part);
+ return { element, nodes };
+ }, save(_edit: unknown, text: string) {
+ if (text === '保存失败') throw Error('临时失败');
+ return {};
+ } });
+ });
+ const box = page.locator('[contenteditable]');
+ await page.locator('#copy code').first().click();
+ assert.equal(await box.innerText(), '配置保存在 /data,媒体在 /media。');
+ await box.fill('取消修改'); await box.press('Escape');
+ assert.equal(await page.locator('#copy code').count(), 2);
+ await page.locator('#copy code').first().click();
+ await box.fill('保存失败'); await box.press('Enter');
+ assert.equal(await page.locator('#copy').innerText(), '配置保存在 /data,媒体在 /media。');
+ assert.equal(await page.locator('#copy code').count(), 2);
+ await page.locator('#copy code').first().click();
+ await box.fill('配置保存在 ,媒体在 /media。'); await box.press('Enter');
+ assert.equal(await page.locator('#copy code').count(), 1);
+ assert.equal(await page.locator('#copy code').innerText(), '/media');
+ await page.locator('#copy code').click();
+ await box.fill(''); await box.press('Enter');
+ assert.equal(await page.locator('#copy').innerText(), '');
+ assert.equal(await page.locator('#copy code').count(), 0);
+ } finally { await context.close(); }
+ });
it(`切换控件可操作、Alt 改字与清空草稿可保存(${viewport.name})`, async () => {
const context = await browser.newContext({ viewport });
try {
diff --git a/frontend/src/copy-editor-core.js b/frontend/src/copy-editor-core.js
index 4def894a7..bf77af0bb 100644
--- a/frontend/src/copy-editor-core.js
+++ b/frontend/src/copy-editor-core.js
@@ -4,6 +4,32 @@
const INTERACT = '[role="tab"],[role="switch"],[role="radio"],[role="radiogroup"],[role="slider"],[role="checkbox"],[role="combobox"],[data-platform-option],[aria-expanded],[aria-pressed],[aria-haspopup],summary,input,select,label,[data-copy-interact]';
const spacing = new WeakMap();
+ // 连续文字共用输入框,未改动的前后片段留在各自的行内元素里。
+ function replaceTextParts(parts, text) {
+ const before = parts.join('');
+ let start = 0, suffix = 0;
+ while (start < before.length && start < text.length && before[start] === text[start]) start++;
+ while (suffix < before.length - start && suffix < text.length - start
+ && before.at(-suffix - 1) === text.at(-suffix - 1)) suffix++;
+ const end = before.length - suffix, insert = text.slice(start, text.length - suffix);
+ let offset = 0, inserted = false;
+ return parts.map((part, i) => {
+ const from = offset; offset += part.length;
+ const add = !inserted && start >= from && (start < offset || i === parts.length - 1);
+ if (add) inserted = true;
+ return part.slice(0, Math.max(0, Math.min(part.length, start - from)))
+ + (add ? insert : '') + part.slice(Math.max(0, Math.min(part.length, end - from)));
+ });
+ }
+
+ function cleanInline(element) {
+ for (const child of [...element.querySelectorAll('span,code,b,strong,em,i,small,s,mark')].reverse()) {
+ if (!child.textContent.trim() && !child.children.length
+ && ![...child.attributes].some(attr => !['class', 'style'].includes(attr.name))) child.remove();
+ }
+ element.normalize();
+ }
+
async function readJson(response) {
const raw = await response.text();
let result;
@@ -77,7 +103,7 @@
if (!event.altKey && event.target.closest?.(INTERACT)) { hideHighlight(); return; }
const node = textAt(event.clientX, event.clientY);
if (!node || !resolve(node)) { hideHighlight(); return; }
- const rects = rectsOf(node), left = Math.min(...rects.map(rect => rect.left)), top = Math.min(...rects.map(rect => rect.top));
+ const rects = rectsOf(resolve(node)?.element || node), left = Math.min(...rects.map(rect => rect.left)), top = Math.min(...rects.map(rect => rect.top));
Object.assign(highlight.style, { position: 'fixed', display: 'block', left: left + 'px', top: top + 'px',
width: Math.max(...rects.map(rect => rect.right)) - left + 'px', height: Math.max(...rects.map(rect => rect.bottom)) - top + 'px' });
}
@@ -104,13 +130,13 @@
top: Math.max(y + 16, Math.min(rect.top - 2, y + height - editing.box.getBoundingClientRect().height - 16)) + 'px', width: inputWidth + 'px' });
}
async function begin(node, target) {
- const before = node.data, originalText = before.trim();
+ const before = target.element ? target.element.textContent : node.data, originalText = before.trim();
let ed = { node, before, originalText, lead: /^\s*/.exec(before)[0], trail: /\s*$/.exec(before)[0],
core: originalText, multiline: !!node.parentElement.closest('pre,code'), ...target };
setBusy(true);
try {
const prepared = await options.prepare?.(ed);
- if (prepared === null || destroyed || !node.isConnected || node.data !== before) { say('已取消'); return; }
+ if (prepared === null || destroyed || !node.isConnected || (ed.element ? ed.element.textContent : node.data) !== before) { say('已取消'); return; }
ed = { ...ed, ...prepared };
const input = !!node.parentElement.closest('button,a,[role="button"]');
const box = document.createElement(input ? 'input' : 'span');
@@ -126,7 +152,12 @@
box.dataset.copyInline = '';
if (options.inlineClass) box.className = options.inlineClass;
box.contentEditable = 'plaintext-only'; box.spellcheck = false; box.textContent = ed.core;
- node.replaceWith(...[ed.lead, box, ed.trail].filter(Boolean));
+ if (ed.element) {
+ ed.parts = ed.nodes.map(node => node.data);
+ ed.fragment = document.createDocumentFragment();
+ ed.fragment.append(...ed.element.childNodes);
+ ed.element.append(box);
+ } else node.replaceWith(...[ed.lead, box, ed.trail].filter(Boolean));
}
box.setAttribute('aria-label', '修改文字'); editing = ed; positionInput(); box.focus();
if (input) box.select();
@@ -138,11 +169,16 @@
else if (event.key === 'Escape') { event.preventDefault(); commit(true); }
});
box.addEventListener('blur', () => commit());
+ if (ed.element) box.addEventListener('input', () => {
+ const text = box.textContent.replace(/\s*\n\s*/g, ' ').trim();
+ ed.parts = replaceTextParts(ed.parts, ed.lead + text + ed.trail);
+ });
} catch (error) { say(error.message, 'err'); }
finally { setBusy(false); }
}
function putBack(ed) {
if (ed.box.tagName === 'INPUT') { ed.box.remove(); return; }
+ if (ed.element) { ed.box.replaceWith(ed.fragment); return; }
const a = ed.box.previousSibling, c = ed.box.nextSibling;
if (ed.lead && a?.nodeType === 3) a.remove();
if (ed.trail && c?.nodeType === 3) c.remove();
@@ -162,11 +198,15 @@
const result = await options.save(ed, text) ?? {};
persisted = true;
const rendered = result.text ?? text;
- if (result.remove) ed.node.remove(); else ed.node.data = ed.lead + rendered + ed.trail;
+ if (ed.element) {
+ const parts = replaceTextParts(ed.parts, ed.lead + rendered + ed.trail);
+ ed.nodes.forEach((node, i) => { node.data = parts[i]; });
+ cleanInline(ed.element);
+ } else if (result.remove) ed.node.remove(); else ed.node.data = ed.lead + rendered + ed.trail;
say(result.message || (rendered ? '已保存修改' : '已删除文字'), 'ok');
await options.onSaved?.(ed, { ...result, text: rendered });
} catch (error) {
- if (!persisted) ed.node.data = ed.before;
+ if (!persisted && !ed.element) ed.node.data = ed.before;
say((persisted ? '已保存,界面更新未完成:' : error.unconfirmed ? '未确认保存:' : '没保存:') + error.message, 'err');
} finally { setBusy(false); }
}
@@ -191,5 +231,5 @@
},
};
}
- globalThis.PeachCopyEditorCore = Object.freeze({ version: 1, create, readJson, resolveDraft, applyDrafts });
+ globalThis.PeachCopyEditorCore = Object.freeze({ version: 1, create, readJson, resolveDraft, applyDrafts, replaceTextParts });
})();
diff --git a/tests/test_web_e2e.py b/tests/test_web_e2e.py
index c7b571715..e1b785e05 100644
--- a/tests/test_web_e2e.py
+++ b/tests/test_web_e2e.py
@@ -228,6 +228,11 @@ class WebE2ESmokeTests(unittest.TestCase):
if cached is None:
raise AssertionError(f"采集来源没有可缓存的主机:{spec['login']}")
cached.write_bytes(mark)
+ # 浏览器添加页的示例域名与采集来源分别取站标。
+ browser_example = link_marks.cached_path(mark_root, 'https://missav.com/')
+ if browser_example is None:
+ raise AssertionError('浏览器示例域名没有可缓存的主机')
+ browser_example.write_bytes(mark)
icon_root = generated / follow_assets.ROOT_NAME
for provider in follow_assets.SOURCE_ICON_URLS:
cached = follow_assets.cache_path(icon_root, "icons", provider)