Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor(edit): 统一预览工具栏并提供双模式入口约定

longmeidaofa22bace94f0
diff --git a/.claude/skills/peach-web-ui/SKILL.md b/.claude/skills/peach-web-ui/SKILL.md
index a4a3f47ed..d4a443d79 100644
--- a/.claude/skills/peach-web-ui/SKILL.md
+++ b/.claude/skills/peach-web-ui/SKILL.md
@@ -6,7 +6,7 @@ description: 在新增、修改、预览或复核 Peach 页面、控件、提示
# Peach Web UI 复用门槛
最后复核:2026-10-23
-证据来源:现有 UI 契约、`docs/TESTING.md`、本机重复文案与异步轮询回归记录、jakubkrehel/skills 与 emilkowalski/skills 摘录、`docs/reference-snapshots/open-claude-ui.md`、用户真实小样本预览、明确确认后测试及所有预览默认接入 `?edit` 的约定。
+证据来源:现有 UI 契约、`docs/TESTING.md`、本机重复文案与异步轮询回归记录、jakubkrehel/skills 与 emilkowalski/skills 摘录、`docs/reference-snapshots/open-claude-ui.md`、用户真实小样本预览、明确确认后测试及成对提供直接预览与 edit 模式链接的约定。
## 开工顺序
@@ -87,7 +87,7 @@ description: 在新增、修改、预览或复核 Peach 页面、控件、提示
## 验收门槛
- 监听预览端口前由启动入口调用 `check_ui_preview.py`,取得成功的 `real-ledger-subset` 报告;提供地址时说明已读约定、实际样本与已查看场景。缺少清单、伪造字段或关联、图像缓存缺失均拒收,不以进程就绪代替实图验收。
-- 交给用户的所有预览默认接入 `?edit`,覆盖首次设置、登录、错误页、主界面及演示站;复用现有编辑器,按 `docs/UI_PREVIEW.md`「文案编辑」核对工作树归属、浮条与保存生效链路,不能只给地址追加参数。
+- 交给用户的每个页面预览成对提供「直接预览」与「edit 模式」链接,覆盖首次设置、登录、错误页、主界面及演示站;两者保留相同查询条件与片段,edit 模式带 `edit` 参数。复用现有编辑器,按 `docs/UI_PREVIEW.md`「文案编辑」核对工作树归属、浮条与保存生效链路,不能只给地址追加参数。
- 预览前核对标题、说明、持久提示与操作回执的职责,同一事实只在承担该职责的位置说明;检查加载、空态、错误和完成态,避免重复说明与残余内容。
- 界面改动先构建并保留可访问的预览,提供地址;只有用户明确确认当前预览后才能运行测试,确认绑定该预览与范围,范围内沿用。发出地址、用户继续纠正和等待超时都不算确认;收到界面新纠正时停止本任务运行中及排队的测试,修好后重新等待确认。确认前只做实现、预览构建与视觉查看;用户明确只要图片时才仅提供截图。
- UI 标签、身份、反馈状态和搜索推荐属于语义契约:按实际影响验证数据层、组件或浏览器行为。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 2aa886c74..88487f686 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -843,7 +843,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` 保留各端来源定位与保存入口。适配器可用 `element` 与 `nodes` 指定连续行内文字的共同编辑区域,`replaceTextParts` 将纯文字修改映射到原有节点,保留未改动片段的样式,并清理无内容且仅带样式属性的行内元素。空字符串可作为删除结果,无法确认的保存响应保留核对提示。切换控件正常响应点击,Alt 点击进入文字编辑。官网与演示站按应用提交与 SHA256 同步核心,适配器先取得原始文字索引再运行页面脚本。
-应用适配器 `scripts/dev/copy-editor.js` 负责源码候选、草稿、工具条和自动生效状态。源码模式按顺序加载 `/dev/copy-editor-core.js` 与 `/dev/copy-editor.js`,动态文案保留模板占位符。
+核心的 `createTools()` 提供工具栏、编辑样式、状态、暂停/继续、导出/退出动作、恢复按钮与来源选择;工具栏和悬停范围跟随模态弹层,避让页面底部选择操作条,`destroy()` 清理节点、监听与未完成选择。应用适配器 `scripts/dev/copy-editor.js` 负责源码候选、草稿、自动生效状态与动作回调。源码模式按顺序加载 `/dev/copy-editor-core.js` 与 `/dev/copy-editor.js`,动态文案保留模板占位符。
改字浮条使用多选操作条的 `data-selection-dock`、`data-glass-pane` 与 `data-batch-scope` 样式,几何、玻璃、字体和按钮共享;窄屏状态提示独占一行。
应用的 React 与动态页面使用源码定位、摘要校验和备份入口;演示站使用浏览器草稿。两者只在 `?edit` 启用,无新增依赖。
Python 源文件纳入 `src/peach/library_sharing.py` 与 `src/peach/library_processing.py`。动态句子复用标准库 `ast`、`string.Formatter` 定位 f-string 与相邻字符串,编辑时显示命名占位符,保存时校验占位符齐全且各出现一次。求值表达式与格式保留在 AST 中,当前数量只用于显示;其他 Python 文件不属于改字范围。
diff --git a/docs/UI_PREVIEW.md b/docs/UI_PREVIEW.md
index 75b384281..5702f38c5 100644
--- a/docs/UI_PREVIEW.md
+++ b/docs/UI_PREVIEW.md
@@ -24,7 +24,7 @@
## 文案编辑
-交给用户的所有页面预览默认开启 `?edit`,包括首次设置、登录、错误页、主界面、新路由与演示站。链接保留已有查询参数和片段:无查询参数时加 `?edit`,已有查询参数时加 `&edit`。用户明确要求普通查看时按其要求提供。
+交给用户的每个页面预览成对提供「直接预览」与「edit 模式」链接,包括首次设置、登录、错误页、主界面、新路由与演示站。两者保留相同的查询参数和片段:直接预览移除 `edit` 参数,edit 模式保留该参数,无查询参数时加 `?edit`,已有查询参数时加 `&edit`。例如 `/tags?scope=online#list` 与 `/tags?scope=online&edit#list`。用户明确指定一种模式时按其要求提供。
复用[源码环境改字](OPERATIONS.md#源码环境改字)的核心、适配器和保存接口。主界面的注入不会自动覆盖首次设置等独立页面壳;目标页面缺少接入时,在当前界面任务中补齐共用入口。不得把参数存在当成已启用,也不另造一套编辑器。
@@ -32,6 +32,6 @@
提供预览前,在目标页面确认「文案编辑」浮条、悬停范围、原位输入和取消操作可用。首次接入或保存链路变化时,用隔离的临时源码副本核对保存、构建或重载、刷新后生效及 `edit` 参数保留;同一工作树和入口的有效证据可复用。核对后恢复临时文案,保留用户修改。未取得某项能力时说明具体页面和错误,不宣称可编辑预览已就绪。
-布局验收和控件操作使用「暂停编辑」或普通查看状态;交付给用户的入口保留编辑模式。编辑器产生的源码修改纳入当前任务的 diff、回归和集成,不写真实账本或修改生产配置。
+布局验收和控件操作使用直接预览或「暂停编辑」状态,改字使用 edit 模式。编辑器产生的源码修改纳入当前任务的 diff、回归和集成,不写真实账本或修改生产配置。
-文案编辑工具栏、悬停范围和来源选择跟随当前模态弹层;弹层关闭后回到页面。工具栏为页面的底部选择操作条让出空间。
+文案编辑工具栏、样式、来源选择和模态跟随由 `frontend/src/copy-editor-core.js` 的 `createTools()` 共用;适配器提供来源、草稿、保存与动作回调。工具栏、悬停范围和来源选择跟随当前模态弹层,弹层关闭后回到页面。工具栏为页面的底部选择操作条让出空间。
diff --git a/frontend/e2e/copy-editor.test.ts b/frontend/e2e/copy-editor.test.ts
index f7d5cb029..9cb15523c 100644
--- a/frontend/e2e/copy-editor.test.ts
+++ b/frontend/e2e/copy-editor.test.ts
@@ -14,6 +14,62 @@ 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"><body><p>预览说明</p></body>');
+ await page.addScriptTag({ content: await readFile(new URL('../src/copy-editor-core.js', import.meta.url), 'utf8') });
+ await page.evaluate(() => {
+ const tools = (globalThis as any).PeachCopyEditorCore.createTools({
+ onToggle(active: boolean) { document.body.dataset.active = String(active); },
+ onExport() { document.body.dataset.exported = 'true'; },
+ onExit() { document.body.dataset.exited = 'true'; },
+ });
+ (globalThis as any).copyTools = tools;
+ tools.say('编辑就绪');
+ });
+ assert.equal(await page.getByRole('status').innerText(), '编辑就绪');
+ await page.getByRole('button', { name: '暂停编辑', exact: true }).click();
+ assert.equal(await page.locator('body').getAttribute('data-active'), 'false');
+ await page.getByRole('button', { name: '继续编辑', exact: true }).click();
+ assert.equal(await page.locator('body').getAttribute('data-active'), 'true');
+ await page.evaluate(() => (globalThis as any).copyTools.setBusy(true));
+ await page.getByRole('button', { name: '暂停编辑', exact: true }).click();
+ await page.getByRole('button', { name: '退出编辑', exact: true }).click();
+ assert.equal(await page.locator('body').getAttribute('data-active'), 'true');
+ assert.equal(await page.locator('body').getAttribute('data-exited'), null);
+ await page.evaluate(() => (globalThis as any).copyTools.setBusy(false));
+ await page.getByRole('button', { name: '导出修改', exact: true }).click();
+ await page.getByRole('button', { name: '退出编辑', exact: true }).click();
+ assert.equal(await page.locator('body').getAttribute('data-exported'), 'true');
+ assert.equal(await page.locator('body').getAttribute('data-exited'), 'true');
+ await page.evaluate(() => {
+ const tools = (globalThis as any).copyTools;
+ tools.setRecovery('继续等待', () => { document.body.dataset.recovery = 'wait'; });
+ tools.setRecovery('重试生效', () => { document.body.dataset.recovery = 'retry'; });
+ });
+ assert.equal(await page.getByRole('button', { name: '继续等待', exact: true }).count(), 0);
+ await page.getByRole('button', { name: '重试生效', exact: true }).click();
+ assert.equal(await page.locator('body').getAttribute('data-recovery'), 'retry');
+ assert.equal(await page.getByRole('button', { name: '重试生效', exact: true }).count(), 0);
+ await page.evaluate(() => {
+ (globalThis as any).copyTools.choose([{ label: '文案位置', value: 'source-1' }], { left: 20, bottom: 80 }, { label: '文案来源' })
+ .then((value: unknown) => { document.body.dataset.choice = JSON.stringify(value); });
+ });
+ await page.getByRole('combobox', { name: '文案来源' }).selectOption('0');
+ assert.equal(await page.locator('body').getAttribute('data-choice'), '"source-1"');
+ await page.evaluate(() => {
+ const tools = (globalThis as any).copyTools;
+ tools.choose([{ label: '文案位置', value: 'source-2' }], { left: 20, bottom: 80 })
+ .then((value: unknown) => { document.body.dataset.choice = JSON.stringify(value); });
+ tools.destroy();
+ });
+ assert.equal(await page.locator('body').getAttribute('data-choice'), 'null');
+ assert.equal(await page.locator('[data-copy-editor]').count(), 0);
+ } finally { await context.close(); }
+ });
+
it(`模态弹层中的工具栏可暂停编辑并随关闭返回页面(${viewport.name})`, async () => {
const context = await browser.newContext({ viewport });
try {
@@ -276,6 +332,9 @@ describe('原位改字', () => {
assert.equal(measured.buttons.length, 3);
for (const button of measured.buttons) assert.deepEqual(button,
{ height: 36, radius: '10px', fontSize: '14px', lineHeight: '20px', weight: '500' });
+ await page.evaluate(() => document.documentElement.style.setProperty('--selection-dock-space', '120px'));
+ assert.equal(await dock.evaluate(node => getComputedStyle(node).bottom), '120px');
+ assert.ok(await dock.evaluate(node => node.getBoundingClientRect().bottom <= innerHeight - 119));
assert.deepEqual(opened.problems, []);
} finally { await opened.close(); }
});
diff --git a/frontend/src/copy-editor-core.js b/frontend/src/copy-editor-core.js
index 0afa4ccd7..b97e1016b 100644
--- a/frontend/src/copy-editor-core.js
+++ b/frontend/src/copy-editor-core.js
@@ -1,4 +1,4 @@
-/* Peach 原位改字核心。以 classic script 同步注册,保存与工具条由各端适配器提供。 */
+/* Peach 原位改字核心。以 classic script 同步注册,保存由各端适配器提供。 */
(() => {
const SKIP = '[data-copy-editor],script,style,textarea,input,select,svg,[contenteditable]';
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]';
@@ -79,6 +79,77 @@
}
}
+ function createTools(options = {}) {
+ const css = document.createElement('style'); css.dataset.copyEditor = '';
+ css.textContent = `
+ [data-copy-highlight]{position:fixed;pointer-events:none;z-index:2147483646;outline:1.5px dashed var(--tungsten);outline-offset:3px;border-radius:var(--badge-radius);display:none}
+ [data-copy-inline]{outline:2px solid var(--tungsten);outline-offset:3px;border-radius:var(--badge-radius);background:var(--hover);user-select:text;cursor:text}
+ [data-copy-input]{position:fixed;z-index:2147483647;padding:2px 6px;border:0;border-radius:var(--badge-radius);outline:2px solid var(--tungsten);background:var(--ground);color:var(--ink)}
+ [data-copy-bar]>[role=status]{max-width:min(360px,calc(100vw - 64px));white-space:normal;overflow-wrap:anywhere}
+ [data-copy-bar][data-selection-dock]{bottom:max(16px,var(--selection-dock-space,0px))}
+ @media(max-width:600px){[data-copy-bar]>[role=status]{flex-basis:100%;text-align:center}}
+ [data-copy-choice]{position:fixed;z-index:2147483647;background:var(--ground);color:var(--ink);border:1px solid var(--border-15);border-radius:var(--control-radius);padding:8px;max-width:calc(100vw - 32px)}
+ `;
+ document.head.append(css);
+ const highlight = document.createElement('div'); highlight.dataset.copyEditor = ''; highlight.dataset.copyHighlight = '';
+ const host = document.createElement('div'); host.className = 'peach-react'; host.dataset.copyEditor = ''; host.dataset.batchScope = '';
+ for (const type of ['pointerdown', 'click']) host.addEventListener(type, event => event.stopPropagation());
+ const bar = document.createElement('div'); bar.dataset.copyEditor = ''; bar.dataset.copyBar = '';
+ bar.dataset.selectionDock = ''; bar.dataset.glassPane = ''; bar.setAttribute('role', 'group'); bar.setAttribute('aria-label', '文案编辑');
+ const hint = document.createElement('span'); hint.id = 'peach-copy-hint'; hint.hidden = true;
+ hint.textContent = '点击文字修改,回车或点别处保存,Esc 取消;暂停编辑后可操作页面。';
+ bar.setAttribute('aria-describedby', hint.id);
+ const status = document.createElement('span'); status.setAttribute('role', 'status'); status.textContent = '编辑文案'; bar.append(status);
+ const say = text => { status.textContent = text; };
+ const button = (text, action) => {
+ const node = document.createElement('button'); node.type = 'button'; node.textContent = text;
+ node.onclick = action; bar.append(node); return node;
+ };
+ let active = true, busy = false, recovery = null, choice = null;
+ const toggle = button('暂停编辑', () => {
+ if (busy) return;
+ active = !active; options.onToggle?.(active); toggle.textContent = active ? '暂停编辑' : '继续编辑';
+ });
+ button('导出修改', () => options.onExport?.());
+ button('退出编辑', () => { if (!busy) options.onExit?.(); });
+ host.append(hint, bar);
+ const modalHost = () => [...document.querySelectorAll('dialog:modal')].at(-1) || document.body;
+ function placeTools() {
+ const parent = modalHost();
+ for (const node of [highlight, host, choice?.node]) if (node && node.parentElement !== parent) parent.append(node);
+ }
+ const observer = new MutationObserver(placeTools);
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['open'] });
+ placeTools();
+ return {
+ highlight, say,
+ setBusy(value) { busy = value; if (value) bar.setAttribute('aria-busy', 'true'); else bar.removeAttribute('aria-busy'); },
+ setRecovery(text, action) {
+ recovery?.remove(); recovery = null;
+ if (action) recovery = button(text, () => {
+ recovery.remove(); recovery = null; action();
+ });
+ },
+ choose(items, rect, { label = '选项', message = '' } = {}) {
+ choice?.cancel();
+ const select = document.createElement('select'); select.dataset.copyEditor = ''; select.dataset.copyChoice = '';
+ select.setAttribute('aria-label', label); select.add(new Option(`请选择${label}`, ''));
+ items.forEach((item, index) => select.add(new Option(item.label, String(index))));
+ Object.assign(select.style, { left: Math.max(16, Math.min(rect.left, innerWidth - 300)) + 'px',
+ top: Math.max(16, Math.min(rect.bottom + 8, innerHeight - 60)) + 'px' });
+ modalHost().append(select); select.focus(); if (message) say(message);
+ return new Promise(resolve => {
+ const finish = value => { select.remove(); document.removeEventListener('keydown', cancel, true); choice = null; resolve(value); };
+ const cancel = event => { if (event.key === 'Escape') { event.preventDefault(); event.stopImmediatePropagation(); finish(null); } };
+ choice = { node: select, cancel: () => finish(null) };
+ select.onchange = () => { if (select.value !== '') finish(items[Number(select.value)].value); };
+ document.addEventListener('keydown', cancel, true);
+ });
+ },
+ destroy() { observer.disconnect(); choice?.cancel(); highlight.remove(); host.remove(); css.remove(); },
+ };
+ }
+
function create(options) {
const skip = SKIP + (options.skip ? ',' + options.skip : '');
const highlight = options.highlight || document.createElement('div');
@@ -236,5 +307,5 @@
},
};
}
- globalThis.PeachCopyEditorCore = Object.freeze({ version: 1, create, readJson, resolveDraft, applyDrafts, replaceTextParts });
+ globalThis.PeachCopyEditorCore = Object.freeze({ version: 1, create, createTools, readJson, resolveDraft, applyDrafts, replaceTextParts });
})();
diff --git a/scripts/dev/copy-editor.js b/scripts/dev/copy-editor.js
index 3347e2150..8ee923eaa 100644
--- a/scripts/dev/copy-editor.js
+++ b/scripts/dev/copy-editor.js
@@ -5,36 +5,21 @@
let edits = {}, active = true, saving = false, editor;
try { edits = JSON.parse(localStorage.getItem(key) || '{}'); } catch {}
const originals = new WeakMap();
- const css = document.createElement('style'); css.dataset.copyEditor = '';
- css.textContent = `
- [data-copy-highlight]{position:fixed;pointer-events:none;z-index:2147483646;outline:1.5px dashed var(--tungsten);outline-offset:3px;border-radius:var(--badge-radius);display:none}
- [data-copy-inline]{outline:2px solid var(--tungsten);outline-offset:3px;border-radius:var(--badge-radius);background:var(--hover);user-select:text;cursor:text}
- [data-copy-input]{position:fixed;z-index:2147483647;padding:2px 6px;border:0;border-radius:var(--badge-radius);outline:2px solid var(--tungsten);background:var(--ground);color:var(--ink)}
- [data-copy-bar]>[role=status]{max-width:min(360px,calc(100vw - 64px));white-space:normal;overflow-wrap:anywhere}
- [data-copy-bar][data-selection-dock]{bottom:max(16px,var(--selection-dock-space,0px))}
- @media(max-width:600px){[data-copy-bar]>[role=status]{flex-basis:100%;text-align:center}}
- [data-copy-choice]{position:fixed;z-index:2147483647;background:var(--ground);color:var(--ink);border:1px solid var(--border-15);border-radius:var(--control-radius);padding:8px;max-width:calc(100vw - 32px)}
- `;
- document.head.append(css);
- const highlight = document.createElement('div'); highlight.dataset.copyEditor = ''; highlight.dataset.copyHighlight = '';
- const host = document.createElement('div'); host.className = 'peach-react'; host.dataset.copyEditor = ''; host.dataset.batchScope = '';
- for (const type of ['pointerdown', 'click']) host.addEventListener(type, event => event.stopPropagation());
- const bar = document.createElement('div'); bar.dataset.copyEditor = ''; bar.dataset.copyBar = '';
- bar.dataset.selectionDock = ''; bar.dataset.glassPane = ''; bar.setAttribute('role', 'group'); bar.setAttribute('aria-label', '文案编辑');
- const hint = document.createElement('span'); hint.id = 'peach-copy-hint'; hint.hidden = true; hint.textContent = '点击文字修改,回车或点别处保存,Esc 取消;暂停编辑后可操作页面。';
- bar.setAttribute('aria-describedby', hint.id);
- const status = document.createElement('span'); status.setAttribute('role', 'status'); status.textContent = '编辑文案'; bar.append(status);
- const say = text => { status.textContent = text; };
+ const tools = core.createTools({
+ onToggle(value) { editor.commit(); active = value; editor.hideHighlight(); },
+ onExport() {
+ const url = URL.createObjectURL(new Blob([JSON.stringify(edits, null, 2)], { type: 'application/json' }));
+ const a = document.createElement('a'); a.href = url; a.download = 'peach-copy-edits.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
+ },
+ onExit() { editor.commit(true); const url = new URL(location.href); url.searchParams.delete('edit'); location.href = url; },
+ });
+ const say = tools.say;
const pendingKey = 'peach.copy-apply.v1';
- let applyButton;
- function recovery(text, action) {
- applyButton?.remove();
- applyButton = button(text, () => { applyButton.remove(); applyButton = null; action(); });
- }
+ const recovery = tools.setRecovery;
async function watchApply(job) {
- applyButton?.remove(); applyButton = null;
+ tools.setRecovery();
sessionStorage.setItem(pendingKey, JSON.stringify(job));
- saving = true; bar.setAttribute('aria-busy', 'true');
+ saving = true; tools.setBusy(true);
const deadline = Date.now() + 300000;
try {
while (Date.now() < deadline) {
@@ -66,26 +51,8 @@
}
say('已保存,生效仍在处理中');
recovery('继续等待', () => watchApply(job));
- } finally { saving = false; bar.removeAttribute('aria-busy'); }
- }
- const button = (text, fn) => { const b = document.createElement('button'); b.type = 'button'; b.textContent = text; b.onclick = fn; bar.append(b); return b; };
- const toggle = button('暂停编辑', () => {
- if (saving) return;
- editor.commit(); active = !active; editor.hideHighlight(); toggle.textContent = active ? '暂停编辑' : '继续编辑';
- });
- button('导出修改', () => {
- const url = URL.createObjectURL(new Blob([JSON.stringify(edits, null, 2)], { type: 'application/json' }));
- const a = document.createElement('a'); a.href = url; a.download = 'peach-copy-edits.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
- });
- button('退出编辑', () => { if (saving) return; editor.commit(true); const url = new URL(location.href); url.searchParams.delete('edit'); location.href = url; });
- host.append(hint, bar); document.body.append(highlight, host);
- const modalHost = () => [...document.querySelectorAll('dialog:modal')].at(-1) || document.body;
- function placeTools() {
- const parent = modalHost();
- for (const node of [highlight, host]) if (node.parentElement !== parent) parent.append(node);
+ } finally { saving = false; tools.setBusy(false); }
}
- new MutationObserver(placeTools).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['open'] });
- placeTools();
if (source) {
const position = sessionStorage.getItem('peach.copy-scroll');
if (position !== null) { sessionStorage.removeItem('peach.copy-scroll'); requestAnimationFrame(() => scrollTo(0, Number(position))); }
@@ -103,12 +70,12 @@
new MutationObserver(apply).observe(document.body, { childList: true, subtree: true, characterData: true }); apply();
if (source) fetch('/dev/copy-edits').then(r => r.ok ? r.json() : {}).then(saved => { edits = { ...edits, ...saved }; apply(); }).catch(() => say('暂时无法读取修改记录'));
editor = core.create({
- highlight, isActive: () => active, isBusy: () => saving,
+ highlight: tools.highlight, isActive: () => active, isBusy: () => saving,
resolve: node => ({ original: originals.get(node) ?? node.data.trim() }),
onStatus: say,
onBusy(value) {
saving = value;
- if (value) bar.setAttribute('aria-busy', 'true'); else bar.removeAttribute('aria-busy');
+ tools.setBusy(value);
if (!value) apply();
},
async prepare(ed) {
@@ -139,14 +106,7 @@
},
});
async function choose(candidates, rect) {
- const select = document.createElement('select'); select.dataset.copyEditor = ''; select.dataset.copyChoice = ''; select.setAttribute('aria-label', '文案来源');
- select.add(new Option('请选择文案来源', '')); candidates.forEach((x, i) => select.add(new Option(`${x.file}:${x.line}`, String(i))));
- Object.assign(select.style, { left: Math.max(16, Math.min(rect.left, innerWidth - 300)) + 'px', top: Math.max(16, Math.min(rect.bottom + 8, innerHeight - 60)) + 'px' });
- modalHost().append(select); select.focus(); say('这段文案有多个来源,请选择要修改的位置');
- return new Promise(resolve => {
- const finish = value => { select.remove(); document.removeEventListener('keydown', cancel, true); resolve(value); };
- const cancel = event => { if (event.key === 'Escape') { event.preventDefault(); event.stopImmediatePropagation(); finish(null); } };
- select.onchange = () => { if (select.value !== '') finish(candidates[Number(select.value)]); }; document.addEventListener('keydown', cancel, true);
- });
+ return tools.choose(candidates.map(candidate => ({ label: `${candidate.file}:${candidate.line}`, value: candidate })), rect,
+ { label: '文案来源', message: '这段文案有多个来源,请选择要修改的位置' });
}
})();