Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 输入框右键补上编辑菜单 (#1017)

Dash15fb15b980d7
diff --git a/apps/desktop/src/main/__tests__/applicationMenuLabels.test.ts b/apps/desktop/src/main/__tests__/applicationMenuLabels.test.ts
index 7948a208e5..00ef8bf484 100644
--- a/apps/desktop/src/main/__tests__/applicationMenuLabels.test.ts
+++ b/apps/desktop/src/main/__tests__/applicationMenuLabels.test.ts
@@ -6,151 +6,16 @@
* 还写着「议题」(Issue 的禁用译法),三语的 `settings` / `checkForUpdates` 还带着
* ASCII 三点省略号,而这是 macOS 上常驻屏幕顶端的菜单栏,比大多数界面文案更显眼。
*
- * 判定逻辑复用 scripts/shared/glossary-rules.mjs,与根门禁、mobile 影子 catalog 同一套,
- * 避免三处各写一份规则后悄悄漂移。
+ * 断言集抽在 ./shadowCatalogGlossary,与可编辑控件右键菜单 catalog 共用;判定逻辑
+ * 复用 scripts/shared/glossary-rules.mjs,与根门禁、mobile 影子 catalog 同一套,
+ * 避免各处各写一份规则后悄悄漂移。
*/
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-import {
- ELLIPSIS_LOCALES,
- HALFWIDTH_PUNCT_LOCALES,
- findCaseMismatch,
- findHalfWidthPunct,
- hasAsciiEllipsis,
- makeExemptChecker,
- normalizeForPunctuation,
- occursIn,
- stripNonProse,
- caseStandardFor,
- sourceMentions,
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore -- 共享规则是 .mjs,没有类型声明;这里只用它做断言
-} from '../../../../../scripts/shared/glossary-rules.mjs';
-
import { APPLICATION_MENU_LABELS } from '../applicationMenuLabels';
-const REPO_ROOT = resolve(__dirname, '../../../../..');
-
-interface GlossaryTerm {
- id: string;
- status: 'decided' | 'proposed';
- en: string;
- translations?: Record<string, string>;
- forbidden?: Record<string, (string | { text: string; whenEn: string })[]>;
- exempt?: string[];
- checkCase?: boolean;
-}
+import { describeShadowCatalogGlossary, flattenShadowCatalog } from './shadowCatalogGlossary';
-const glossary = JSON.parse(
- readFileSync(resolve(REPO_ROOT, 'i18n/glossary.json'), 'utf8'),
-) as {
- locales: string[];
- sourceLocale: string;
- punctuationExempt?: string[];
- terms: GlossaryTerm[];
-};
-
-/**
- * 摊平成 (locale, key, value)。
- *
- * 前缀必须是 `desktop:`——glossary.json 的 exempt 用 `^(desktop|mobile/xxx):` 校验格式,
- * 也按这个前缀匹配。用 `desktop-menu:` 之类的自造前缀会让 exempt 对这份 catalog 完全
- * 失效(而 note 里还写着"可复用同一套写法"),将来给某个菜单项加豁免时会白写一条。
- * 用 `menu.` 子命名空间区分来源。
- */
-const entries = Object.entries(APPLICATION_MENU_LABELS).flatMap(([locale, labels]) =>
- Object.entries(labels).map(([key, value]) => ({
- locale,
- key: `desktop:menu.${key}`,
- value: value as string,
- })),
+describeShadowCatalogGlossary(
+ '原生应用菜单标签符合术语表',
+ flattenShadowCatalog(APPLICATION_MENU_LABELS, 'desktop:menu.'),
+ '原生菜单',
);
-
-/** 标点豁免:与根门禁同源,只作用于半角标点检查(不含省略号)。 */
-const isHalfWidthExempt = makeExemptChecker(glossary.punctuationExempt);
-
-/** key → 英文源文案,供条件禁用按英文源判断。 */
-const sourceByKey = new Map(
- entries.filter((e) => e.locale === glossary.sourceLocale).map((e) => [e.key, e.value]),
-);
-
-describe('原生应用菜单标签符合术语表', () => {
- it('摊平后覆盖四种语言', () => {
- const locales = new Set(entries.map((e) => e.locale));
- expect([...locales].sort()).toEqual([...glossary.locales].sort());
- expect(entries.length).toBeGreaterThan(0);
- });
-
- it('不使用术语表的禁用译法', () => {
- const violations: string[] = [];
- const notes: string[] = [];
- for (const term of glossary.terms) {
- const isExempt = makeExemptChecker(term.exempt);
- for (const { locale, key, value } of entries) {
- if (isExempt(key)) continue;
- for (const entry of term.forbidden?.[locale] ?? []) {
- const bad = typeof entry === 'string' ? entry : entry.text;
- const whenEn = typeof entry === 'string' ? null : entry.whenEn;
- if (!occursIn(stripNonProse(value), bad)) continue;
- if (whenEn) {
- // 复用共享匹配器:词边界与真实复数形态(Proxy → proxies)都由它统一处理。
- // 这里原先抄了一份正则,与根门禁各自演进早晚失配。
- const source = sourceByKey.get(key);
- if (!source || !sourceMentions(stripNonProse(source), whenEn)) continue;
- }
- const line = `${locale} ${key}: 「${bad}」(${term.en})— ${value}`;
- // proposed 只提示不阻断,与根门禁的分级一致:那些术语还没拍板,
- // 但它们在本 catalog 的命中数同样该出现在讨论材料里。
- if (term.status === 'decided') violations.push(line);
- else notes.push(line);
- }
- }
- }
- if (notes.length > 0) console.warn(`[menu-glossary] 待裁决术语命中:\n${notes.join('\n')}`);
- expect(violations, `原生菜单命中禁用译法:\n${violations.join('\n')}`).toEqual([]);
- });
-
- it('保留英文的术语大小写形态统一', () => {
- const violations: string[] = [];
- // 与 forbidden 用例同一分级:proposed 也扫,只是降级为告警。跳过的话,菜单文案里
- // 「待裁决术语当前命中多少处」的数据就没了,而根门禁是会统计的。
- const notes: string[] = [];
- for (const term of glossary.terms) {
- const isExempt = makeExemptChecker(term.exempt);
- for (const { locale, key, value } of entries) {
- if (isExempt(key)) continue;
- // 触发条件统一由 caseStandardFor 判定(含 alsoAllowed 允许英文原词的情形),
- // 与根门禁同一份逻辑。
- const standard = caseStandardFor(term, locale);
- if (!standard) continue;
- const hit = findCaseMismatch(stripNonProse(value), standard);
- if (!hit) continue;
- const line = `${locale} ${key}: 「${hit}」应为「${standard}」`;
- if (term.status === 'decided') violations.push(line);
- else notes.push(line);
- }
- }
- if (notes.length > 0) console.warn(`[menu-glossary] 待裁决术语大小写:\n${notes.join('\n')}`);
- expect(violations, `原生菜单大小写不统一:\n${violations.join('\n')}`).toEqual([]);
- });
-
- it('标点风格符合各语言规则', () => {
- const violations: string[] = [];
- for (const { locale, key, value } of entries) {
- const prose = normalizeForPunctuation(value);
- // 与根门禁一致:punctuationExempt 只豁免半角标点、不豁免省略号。
- // 两边不一致的话,加一条豁免会让根门禁放行、而本测试误报阻断 CI。
- if (HALFWIDTH_PUNCT_LOCALES.has(locale) && !isHalfWidthExempt(key)) {
- const mark = findHalfWidthPunct(prose);
- if (mark) violations.push(`${locale} ${key}: 中文后半角「${mark}」— ${value}`);
- }
- if (ELLIPSIS_LOCALES.has(locale) && hasAsciiEllipsis(prose)) {
- violations.push(`${locale} ${key}: 应使用「…」而非三个半角点 — ${value}`);
- }
- }
- expect(violations, `原生菜单标点不符:\n${violations.join('\n')}`).toEqual([]);
- });
-});
diff --git a/apps/desktop/src/main/__tests__/editableContextMenuLabels.test.ts b/apps/desktop/src/main/__tests__/editableContextMenuLabels.test.ts
new file mode 100644
index 0000000000..e5696c27f7
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/editableContextMenuLabels.test.ts
@@ -0,0 +1,16 @@
+/**
+ * 可编辑控件右键菜单四语标签的术语门禁。
+ *
+ * 与应用菜单同理:这份 catalog 是用户可见文案但不走 i18next,根门禁扫不到它。
+ * 菜单里的「粘贴」「全选」等词直接对标系统级编辑命令,一旦译法漂移会比普通界面
+ * 文案更刺眼,所以同样纳入术语与标点门禁。
+ */
+import { EDITABLE_CONTEXT_MENU_LABELS } from '../editableContextMenuLabels';
+
+import { describeShadowCatalogGlossary, flattenShadowCatalog } from './shadowCatalogGlossary';
+
+describeShadowCatalogGlossary(
+ '可编辑控件右键菜单标签符合术语表',
+ flattenShadowCatalog(EDITABLE_CONTEXT_MENU_LABELS, 'desktop:editMenu.'),
+ '可编辑控件右键菜单',
+);
diff --git a/apps/desktop/src/main/__tests__/selectionContextMenu.test.ts b/apps/desktop/src/main/__tests__/selectionContextMenu.test.ts
index 54016bf2d7..d75ae8f326 100644
--- a/apps/desktop/src/main/__tests__/selectionContextMenu.test.ts
+++ b/apps/desktop/src/main/__tests__/selectionContextMenu.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ buildEditableContextMenuTemplate,
buildSelectionContextMenuTemplate,
buildSelectionSearchUrl,
frameSelectionSupportsAddToChat,
@@ -92,3 +93,153 @@ describe('selection context menu platform shape', () => {
expect(decodeURIComponent(buildSelectionSearchUrl('x'.repeat(2500)).split('?q=')[1] ?? '')).toHaveLength(2000);
});
});
+
+type EditableParams = Parameters<typeof buildEditableContextMenuTemplate>[2];
+type EditFlags = EditableParams['editFlags'];
+
+const RICH_EDIT_FLAGS = {
+ canUndo: true,
+ canRedo: true,
+ canCut: true,
+ canCopy: true,
+ canPaste: true,
+ canSelectAll: true,
+ canEditRichly: true,
+} as EditFlags;
+
+function editableParams(
+ overrides: Partial<EditFlags> = {},
+ selectionText = '',
+): EditableParams {
+ return {
+ editFlags: { ...RICH_EDIT_FLAGS, ...overrides } as EditFlags,
+ selectionText,
+ } as EditableParams;
+}
+
+const editableActions = () => ({ lookUp: vi.fn(), searchWeb: vi.fn() });
+
+describe('editable context menu shape', () => {
+ it('offers the standard edit commands in the user locale', () => {
+ const template = buildEditableContextMenuTemplate(
+ 'darwin',
+ 'zh-CN',
+ editableParams(),
+ editableActions(),
+ );
+
+ expect(template.map((item) => item.role ?? item.type)).toEqual([
+ 'undo',
+ 'redo',
+ 'separator',
+ 'cut',
+ 'copy',
+ 'paste',
+ 'pasteAndMatchStyle',
+ 'separator',
+ 'selectAll',
+ ]);
+ expect(template.map((item) => item.label).filter(Boolean)).toEqual([
+ '撤销',
+ '重做',
+ '剪切',
+ '复制',
+ '粘贴',
+ '粘贴为纯文本',
+ '全选',
+ ]);
+ expect(template.every((item) => item.enabled !== false)).toBe(true);
+ });
+
+ it('never exposes browser developer actions', () => {
+ const template = buildEditableContextMenuTemplate(
+ 'win32',
+ 'en-US',
+ editableParams({}, 'word'),
+ editableActions(),
+ );
+
+ for (const role of ['reload', 'toggleDevTools', 'forceReload'] as const) {
+ expect(template.some((item) => item.role === role)).toBe(false);
+ }
+ });
+
+ it('mirrors Chromium editFlags instead of re-deriving enablement', () => {
+ const template = buildEditableContextMenuTemplate(
+ 'win32',
+ 'en',
+ editableParams({ canUndo: false, canRedo: false, canPaste: false, canCopy: false }),
+ editableActions(),
+ );
+ const enabledByRole = new Map(template.map((item) => [item.role, item.enabled]));
+
+ expect(enabledByRole.get('undo')).toBe(false);
+ expect(enabledByRole.get('redo')).toBe(false);
+ expect(enabledByRole.get('paste')).toBe(false);
+ expect(enabledByRole.get('pasteAndMatchStyle')).toBe(false);
+ expect(enabledByRole.get('copy')).toBe(false);
+ expect(enabledByRole.get('cut')).toBe(true);
+ expect(enabledByRole.get('selectAll')).toBe(true);
+ });
+
+ it('drops paste-as-plain-text for plain inputs where it duplicates paste', () => {
+ const template = buildEditableContextMenuTemplate(
+ 'darwin',
+ 'en',
+ editableParams({ canEditRichly: false }),
+ editableActions(),
+ );
+
+ expect(template.some((item) => item.role === 'pasteAndMatchStyle')).toBe(false);
+ expect(template.some((item) => item.role === 'paste')).toBe(true);
+ });
+
+ it('adds the platform lookup action only when text is selected', () => {
+ const withoutSelection = buildEditableContextMenuTemplate(
+ 'darwin',
+ 'en',
+ editableParams(),
+ editableActions(),
+ );
+ expect(withoutSelection.at(-1)?.role).toBe('selectAll');
+
+ const macActions = editableActions();
+ const mac = buildEditableContextMenuTemplate(
+ 'darwin',
+ 'en',
+ editableParams({}, ' typo '),
+ macActions,
+ );
+ expect(mac.at(-1)?.label).toBe('Look Up “typo”');
+ (mac.at(-1)?.click as () => void)();
+ expect(macActions.lookUp).toHaveBeenCalledTimes(1);
+
+ const winActions = editableActions();
+ const win = buildEditableContextMenuTemplate(
+ 'win32',
+ 'zh-CN',
+ editableParams({}, 'typo'),
+ winActions,
+ );
+ expect(win.at(-1)?.label).toBe('在网页中搜索“typo”');
+ (win.at(-1)?.click as () => void)();
+ expect(winActions.searchWeb).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the read-only selection menu label in sync with the edit catalog', () => {
+ const selection = buildSelectionContextMenuTemplate('darwin', 'ja', params, {
+ addToChat: vi.fn(),
+ lookUp: vi.fn(),
+ searchWeb: vi.fn(),
+ });
+ const editable = buildEditableContextMenuTemplate(
+ 'darwin',
+ 'ja',
+ editableParams(),
+ editableActions(),
+ );
+
+ expect(selection[0]?.label).toBe('コピー');
+ expect(editable.find((item) => item.role === 'copy')?.label).toBe('コピー');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/shadowCatalogGlossary.ts b/apps/desktop/src/main/__tests__/shadowCatalogGlossary.ts
new file mode 100644
index 0000000000..5f8522fd2e
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/shadowCatalogGlossary.ts
@@ -0,0 +1,182 @@
+/**
+ * 影子 catalog 的术语门禁断言(供多个 catalog 复用,本身不是测试文件)。
+ *
+ * 为什么需要它:`scripts/check-i18n-glossary.mjs` 只读 renderer 的 locale JSON,扫不到
+ * main 侧手写的四语 TS catalog。引入术语表那轮 applicationMenuLabels 就整个漏掉了——
+ * zh-CN 的 `issues` 还写着「议题」(Issue 的禁用译法),三语的 `settings` /
+ * `checkForUpdates` 还带着 ASCII 三点省略号,而那是 macOS 上常驻屏幕顶端的菜单栏。
+ *
+ * 判定逻辑复用 scripts/shared/glossary-rules.mjs,与根门禁、mobile 影子 catalog 同一套,
+ * 避免各写一份规则后悄悄漂移。第二份 catalog(可编辑控件右键菜单)进来时抽成本模块,
+ * 免得同一批断言被复制两份、日后只改一处。
+ */
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ ELLIPSIS_LOCALES,
+ HALFWIDTH_PUNCT_LOCALES,
+ findCaseMismatch,
+ findHalfWidthPunct,
+ hasAsciiEllipsis,
+ makeExemptChecker,
+ normalizeForPunctuation,
+ occursIn,
+ stripNonProse,
+ caseStandardFor,
+ sourceMentions,
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-ignore -- 共享规则是 .mjs,没有类型声明;这里只用它做断言
+} from '../../../../../scripts/shared/glossary-rules.mjs';
+
+const REPO_ROOT = resolve(__dirname, '../../../../..');
+
+interface GlossaryTerm {
+ id: string;
+ status: 'decided' | 'proposed';
+ en: string;
+ translations?: Record<string, string>;
+ forbidden?: Record<string, (string | { text: string; whenEn: string })[]>;
+ exempt?: string[];
+ checkCase?: boolean;
+}
+
+const glossary = JSON.parse(
+ readFileSync(resolve(REPO_ROOT, 'i18n/glossary.json'), 'utf8'),
+) as {
+ locales: string[];
+ sourceLocale: string;
+ punctuationExempt?: string[];
+ terms: GlossaryTerm[];
+};
+
+export interface ShadowCatalogEntry {
+ locale: string;
+ key: string;
+ value: string;
+}
+
+/**
+ * 把 `Record<locale, Record<key, string>>` 摊平成 (locale, key, value)。
+ *
+ * `keyPrefix` 必须以 `desktop:` 开头——glossary.json 的 exempt 用
+ * `^(desktop|mobile/xxx):` 校验格式,也按这个前缀匹配。用 `desktop-menu:` 之类的自造
+ * 前缀会让 exempt 对这份 catalog 完全失效,将来给某个菜单项加豁免时会白写一条。
+ * 前缀后面用子命名空间(`menu.` / `editMenu.`)区分来源。
+ */
+export function flattenShadowCatalog(
+ // 各 catalog 的值是 interface,没有 index signature,结构上匹配不了
+ // Record<string, string>;这里收 unknown 再断言,免得每个 catalog 都得为测试
+ // 改成带索引签名的类型。
+ catalog: Readonly<Record<string, unknown>>,
+ keyPrefix: string,
+): ShadowCatalogEntry[] {
+ if (!keyPrefix.startsWith('desktop:')) {
+ throw new Error(`影子 catalog 的 key 前缀必须以 desktop: 开头,收到 ${keyPrefix}`);
+ }
+ return Object.entries(catalog).flatMap(([locale, labels]) =>
+ Object.entries(labels as Record<string, string>).map(([key, value]) => ({
+ locale,
+ key: `${keyPrefix}${key}`,
+ value,
+ })));
+}
+
+/**
+ * 对一份摊平后的影子 catalog 跑完整术语门禁。
+ *
+ * `surface` 只进断言与告警文案,用来在失败输出里区分是哪份 catalog 出的问题。
+ */
+export function describeShadowCatalogGlossary(
+ title: string,
+ entries: readonly ShadowCatalogEntry[],
+ surface: string,
+): void {
+ /** 标点豁免:与根门禁同源,只作用于半角标点检查(不含省略号)。 */
+ const isHalfWidthExempt = makeExemptChecker(glossary.punctuationExempt);
+
+ /** key → 英文源文案,供条件禁用按英文源判断。 */
+ const sourceByKey = new Map(
+ entries.filter((e) => e.locale === glossary.sourceLocale).map((e) => [e.key, e.value]),
+ );
+
+ describe(title, () => {
+ it('摊平后覆盖四种语言', () => {
+ const locales = new Set(entries.map((e) => e.locale));
+ expect([...locales].sort()).toEqual([...glossary.locales].sort());
+ expect(entries.length).toBeGreaterThan(0);
+ });
+
+ it('不使用术语表的禁用译法', () => {
+ const violations: string[] = [];
+ const notes: string[] = [];
+ for (const term of glossary.terms) {
+ const isExempt = makeExemptChecker(term.exempt);
+ for (const { locale, key, value } of entries) {
+ if (isExempt(key)) continue;
+ for (const entry of term.forbidden?.[locale] ?? []) {
+ const bad = typeof entry === 'string' ? entry : entry.text;
+ const whenEn = typeof entry === 'string' ? null : entry.whenEn;
+ if (!occursIn(stripNonProse(value), bad)) continue;
+ if (whenEn) {
+ // 复用共享匹配器:词边界与真实复数形态(Proxy → proxies)都由它统一处理。
+ // 这里原先抄了一份正则,与根门禁各自演进早晚失配。
+ const source = sourceByKey.get(key);
+ if (!source || !sourceMentions(stripNonProse(source), whenEn)) continue;
+ }
+ const line = `${locale} ${key}: 「${bad}」(${term.en})— ${value}`;
+ // proposed 只提示不阻断,与根门禁的分级一致:那些术语还没拍板,
+ // 但它们在本 catalog 的命中数同样该出现在讨论材料里。
+ if (term.status === 'decided') violations.push(line);
+ else notes.push(line);
+ }
+ }
+ }
+ if (notes.length > 0) console.warn(`[menu-glossary] 待裁决术语命中:\n${notes.join('\n')}`);
+ expect(violations, `${surface}命中禁用译法:\n${violations.join('\n')}`).toEqual([]);
+ });
+
+ it('保留英文的术语大小写形态统一', () => {
+ const violations: string[] = [];
+ // 与 forbidden 用例同一分级:proposed 也扫,只是降级为告警。跳过的话,菜单文案里
+ // 「待裁决术语当前命中多少处」的数据就没了,而根门禁是会统计的。
+ const notes: string[] = [];
+ for (const term of glossary.terms) {
+ const isExempt = makeExemptChecker(term.exempt);
+ for (const { locale, key, value } of entries) {
+ if (isExempt(key)) continue;
+ // 触发条件统一由 caseStandardFor 判定(含 alsoAllowed 允许英文原词的情形),
+ // 与根门禁同一份逻辑。
+ const standard = caseStandardFor(term, locale);
+ if (!standard) continue;
+ const hit = findCaseMismatch(stripNonProse(value), standard);
+ if (!hit) continue;
+ const line = `${locale} ${key}: 「${hit}」应为「${standard}」`;
+ if (term.status === 'decided') violations.push(line);
+ else notes.push(line);
+ }
+ }
+ if (notes.length > 0) console.warn(`[menu-glossary] 待裁决术语大小写:\n${notes.join('\n')}`);
+ expect(violations, `${surface}大小写不统一:\n${violations.join('\n')}`).toEqual([]);
+ });
+
+ it('标点风格符合各语言规则', () => {
+ const violations: string[] = [];
+ for (const { locale, key, value } of entries) {
+ const prose = normalizeForPunctuation(value);
+ // 与根门禁一致:punctuationExempt 只豁免半角标点、不豁免省略号。
+ // 两边不一致的话,加一条豁免会让根门禁放行、而本测试误报阻断 CI。
+ if (HALFWIDTH_PUNCT_LOCALES.has(locale) && !isHalfWidthExempt(key)) {
+ const mark = findHalfWidthPunct(prose);
+ if (mark) violations.push(`${locale} ${key}: 中文后半角「${mark}」— ${value}`);
+ }
+ if (ELLIPSIS_LOCALES.has(locale) && hasAsciiEllipsis(prose)) {
+ violations.push(`${locale} ${key}: 应使用「…」而非三个半角点 — ${value}`);
+ }
+ }
+ expect(violations, `${surface}标点不符:\n${violations.join('\n')}`).toEqual([]);
+ });
+ });
+}
diff --git a/apps/desktop/src/main/editableContextMenuLabels.ts b/apps/desktop/src/main/editableContextMenuLabels.ts
new file mode 100644
index 0000000000..5612368b6c
--- /dev/null
+++ b/apps/desktop/src/main/editableContextMenuLabels.ts
@@ -0,0 +1,60 @@
+/**
+ * 可编辑控件(输入框、文本域、contenteditable)原生右键菜单的四语标签。
+ *
+ * 和 applicationMenuLabels.ts 同样是**影子 catalog**:属于用户可见文案,但不走
+ * i18next,`check-i18n-glossary.mjs` 只读 renderer 的 locale JSON 扫不到它。覆盖它的
+ * 是 __tests__/editableContextMenuLabels.test.ts,判定逻辑与根门禁同源。
+ *
+ * 措辞取各平台系统级编辑命令的既有译法(macOS 菜单栏 / Chromium 右键菜单),不自造:
+ * 用户对这几个词的预期由操作系统而非 Cindy 建立。
+ */
+import type { SupportedLocale } from '../shared/locale.js';
+
+export interface EditableContextMenuLabels {
+ undo: string;
+ redo: string;
+ cut: string;
+ copy: string;
+ paste: string;
+ pasteAsPlainText: string;
+ selectAll: string;
+}
+
+export const EDITABLE_CONTEXT_MENU_LABELS: Record<SupportedLocale, EditableContextMenuLabels> = {
+ 'zh-CN': {
+ undo: '撤销',
+ redo: '重做',
+ cut: '剪切',
+ copy: '复制',
+ paste: '粘贴',
+ pasteAsPlainText: '粘贴为纯文本',
+ selectAll: '全选',
+ },
+ en: {
+ undo: 'Undo',
+ redo: 'Redo',
+ cut: 'Cut',
+ copy: 'Copy',
+ paste: 'Paste',
+ pasteAsPlainText: 'Paste as Plain Text',
+ selectAll: 'Select All',
+ },
+ ja: {
+ undo: '元に戻す',
+ redo: 'やり直す',
+ cut: '切り取り',
+ copy: 'コピー',
+ paste: '貼り付け',
+ pasteAsPlainText: 'テキストのみ貼り付け',
+ selectAll: 'すべて選択',
+ },
+ ko: {
+ undo: '실행 취소',
+ redo: '다시 실행',
+ cut: '잘라내기',
+ copy: '복사',
+ paste: '붙여넣기',
+ pasteAsPlainText: '서식 없이 붙여넣기',
+ selectAll: '모두 선택',
+ },
+};
diff --git a/apps/desktop/src/main/selection-context-menu.ts b/apps/desktop/src/main/selection-context-menu.ts
index 7366c60999..7c941b39f8 100644
--- a/apps/desktop/src/main/selection-context-menu.ts
+++ b/apps/desktop/src/main/selection-context-menu.ts
@@ -1,10 +1,13 @@
/**
- * App-owned BrowserWindow text-selection context menu.
+ * App-owned BrowserWindow context menu for text selections and editable
+ * controls.
*
* Electron does not expose Chromium's full native menu as a safe reusable
* default, so we intentionally build the small platform set Cindy needs:
- * macOS gets Copy / Look Up; Windows gets Copy / web search. Browser-only
- * actions such as reload, view source, and inspect are never included.
+ * read-only selections get macOS Copy / Look Up or Windows Copy / web search,
+ * and editable controls get the standard edit commands (undo … select all).
+ * Browser-only actions such as reload, view source, and inspect are never
+ * included.
*/
import {
app,
@@ -19,8 +22,13 @@ import {
import { SELECTION_CONTEXT_MENU_ADD_TO_CHAT_CHANNEL } from '../shared/selectionContextMenu.js';
import {
resolvePreferredSystemLocale,
+ resolveSystemLocale,
type SupportedLocale,
} from '../shared/locale.js';
+import {
+ EDITABLE_CONTEXT_MENU_LABELS,
+ type EditableContextMenuLabels,
+} from './editableContextMenuLabels.js';
const SEARCH_URL = 'https://www.bing.com/search?q=';
const LABEL_PREVIEW_CHARS = 48;
@@ -51,6 +59,11 @@ function compactSelectionLabel(text: string): string {
: compact;
}
+/** 宽松 locale 串('en-US'、'zh-TW' 等)落到 catalog 支持的四种语言。 */
+function editableMenuLabels(locale: string): EditableContextMenuLabels {
+ return EDITABLE_CONTEXT_MENU_LABELS[resolveSystemLocale(locale)];
+}
+
function localizedActionLabel(
action: 'addToChat' | 'copy' | 'lookUp' | 'searchWeb',
locale: string,
@@ -64,12 +77,8 @@ function localizedActionLabel(
if (language.startsWith('ko')) return '대화에 추가';
return 'Add to chat';
}
- if (action === 'copy') {
- if (language.startsWith('zh')) return '复制';
- if (language.startsWith('ja')) return 'コピー';
- if (language.startsWith('ko')) return '복사';
- return 'Copy';
- }
+ // Copy 是两套菜单共用的同一条命令,标签只保留 catalog 一处正本。
+ if (action === 'copy') return editableMenuLabels(locale).copy;
if (action === 'lookUp') {
if (language.startsWith('zh')) return `查询“${preview}”`;
if (language.startsWith('ja')) return `「${preview}」を調べる`;
@@ -130,6 +139,60 @@ export function buildSelectionContextMenuTemplate(
];
}
+/**
+ * Build the editable-control menu; exported for platform regression tests.
+ *
+ * Electron ships no default menu at all, so without this an input, textarea or
+ * contenteditable right-click produced nothing — paste was keyboard-only. The
+ * item set follows the platform edit menu users already know; enablement comes
+ * from Chromium's editFlags, so read-only and password fields grey out on their
+ * own instead of us re-deriving the rules.
+ */
+export function buildEditableContextMenuTemplate(
+ platform: SupportedPlatform,
+ locale: string,
+ params: Pick<ContextMenuParams, 'editFlags' | 'selectionText'>,
+ actions: Pick<SelectionMenuActions, 'lookUp' | 'searchWeb'>,
+): MenuItemConstructorOptions[] {
+ const labels = editableMenuLabels(locale);
+ const { editFlags } = params;
+ const template: MenuItemConstructorOptions[] = [
+ { role: 'undo', label: labels.undo, enabled: editFlags.canUndo },
+ { role: 'redo', label: labels.redo, enabled: editFlags.canRedo },
+ { type: 'separator' },
+ { role: 'cut', label: labels.cut, enabled: editFlags.canCut },
+ { role: 'copy', label: labels.copy, enabled: editFlags.canCopy },
+ { role: 'paste', label: labels.paste, enabled: editFlags.canPaste },
+ ];
+ // 只有富文本目标才给「粘贴为纯文本」:普通 input / textarea 里它和「粘贴」等效,
+ // 多一条只会让菜单更长。
+ if (editFlags.canEditRichly) {
+ template.push({
+ role: 'pasteAndMatchStyle',
+ label: labels.pasteAsPlainText,
+ enabled: editFlags.canPaste,
+ });
+ }
+ template.push(
+ { type: 'separator' },
+ { role: 'selectAll', label: labels.selectAll, enabled: editFlags.canSelectAll },
+ );
+ const selectionText = params.selectionText.trim();
+ if (selectionText) {
+ template.push({ type: 'separator' });
+ template.push(platform === 'darwin'
+ ? {
+ label: localizedActionLabel('lookUp', locale, selectionText),
+ click: actions.lookUp,
+ }
+ : {
+ label: localizedActionLabel('searchWeb', locale, selectionText),
+ click: actions.searchWeb,
+ });
+ }
+ return template;
+}
+
/** Keep custom context-menu labels aligned with Cindy's effective UI locale. */
export function setSelectionContextMenuLocale(locale: SupportedLocale): void {
currentLocale = locale;
@@ -164,11 +227,15 @@ async function showSelectionContextMenu(
win: BrowserWindow,
params: ContextMenuParams,
): Promise<void> {
- const selectionText = params.selectionText.trim();
- // Editable controls keep Chromium's existing edit/spellcheck menu. The app
- // menu is only for non-editable selected text.
- if (!selectionText || params.isEditable) return;
if (process.platform !== 'darwin' && process.platform !== 'win32') return;
+ if (params.isEditable) {
+ // 可编辑目标不问 renderer:「添加到对话」只对只读引用区有意义,少一次
+ // executeJavaScript 也让输入框右键即时弹出。
+ showEditableContextMenu(win, params, process.platform);
+ return;
+ }
+ const selectionText = params.selectionText.trim();
+ if (!selectionText) return;
const canAddToChat = await frameSelectionSupportsAddToChat(params.frame);
if (win.isDestroyed()) return;
const sourceFrame = params.frame;
@@ -193,3 +260,25 @@ async function showSelectionContextMenu(
);
Menu.buildFromTemplate(template).popup({ window: win, x: params.x, y: params.y });
}
+
+function showEditableContextMenu(
+ win: BrowserWindow,
+ params: ContextMenuParams,
+ platform: SupportedPlatform,
+): void {
+ const selectionText = params.selectionText.trim();
+ const template = buildEditableContextMenuTemplate(
+ platform,
+ getSelectionContextMenuLocale(),
+ { editFlags: params.editFlags, selectionText },
+ {
+ lookUp: () => {
+ if (!win.isDestroyed()) win.webContents.showDefinitionForSelection();
+ },
+ searchWeb: () => {
+ void shell.openExternal(buildSelectionSearchUrl(selectionText));
+ },
+ },
+ );
+ Menu.buildFromTemplate(template).popup({ window: win, x: params.x, y: params.y });
+}