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): 避免列表输入时 IME 卡死 (#626)

DavidShenXD5be7d7fa7edf
diff --git a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
index 3627240fda..711b14ff38 100644
--- a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
@@ -71,6 +71,7 @@ function indentSpans(ed: Editor): string[] {
afterEach(() => {
editor?.destroy();
editor = null;
+ vi.useRealTimers();
});
describe('buildListIndentDecorations', () => {
@@ -352,6 +353,53 @@ describe('ComposerListIndentDecoration in a real editor', () => {
}
});
+ it('suspends list and CJK decorations for the full IME composition', () => {
+ vi.useFakeTimers();
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ CjkPunctDecoration,
+ ComposerListIndentDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '1. 《旧》' }] }],
+ },
+ });
+
+ expect(editor.view.dom.querySelector('.composer-list-block-indent')).not.toBeNull();
+ expect(editor.view.dom.querySelectorAll('span[style*="font-family"]').length).toBeGreaterThan(
+ 0,
+ );
+
+ editor.view.dom.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
+ expect(editor.view.composing).toBe(true);
+ expect(editor.view.dom.querySelector('.composer-list-block-indent')).toBeNull();
+ expect(editor.view.dom.querySelector('span[style*="font-family"]')).toBeNull();
+
+ editor.view.dispatch(
+ editor.state.tr.insertText('中', editor.state.doc.content.size - 1).setMeta('composition', 1),
+ );
+ expect(editor.getText()).toBe('1. 《旧》中');
+ expect(editor.view.dom.querySelector('.composer-list-block-indent')).toBeNull();
+ expect(editor.view.dom.querySelector('span[style*="font-family"]')).toBeNull();
+
+ editor.view.dom.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));
+ expect(editor.view.composing).toBe(false);
+ vi.runOnlyPendingTimers();
+
+ expect(editor.view.dom.querySelector('.composer-list-block-indent')?.textContent).toBe(
+ '1. 《旧》中',
+ );
+ expect(editor.view.dom.querySelectorAll('span[style*="font-family"]').length).toBeGreaterThan(
+ 0,
+ );
+ });
+
it('renders the indent span into the DOM for list lines', () => {
const ed = makeEditor(['1. hello']);
expect(ed.view.dom.querySelector('p.composer-list-block-indent')?.textContent).toBe('1. hello');
diff --git a/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts b/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
index a0679c2bcb..48afb721f2 100644
--- a/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
@@ -21,9 +21,8 @@
*
* 边界处理
* --------
- * - IME 组合期 (用户打 pinyin 还没选字): view.update() 跳过布局测量,
- * 避免同步 layout 读写干扰输入法候选框; decoration state 仍由 transaction
- * 驱动,在 doc/meta 变化时按正常路径重算。
+ * - IME 组合期 (用户打 pinyin 还没选字): compositionstart 前临时移除
+ * decoration,compositionend 后再按当前 doc 补算,避免改写输入法维护的 DOM。
* - 性能: chat input 文本量很小,doc 变化、slash roster 或 voice replacement
* range 变化时采用全量重扫;不使用 DecorationSet.map 增量映射,以保持边界逻辑简单。
* - 不污染源数据: decoration 只是渲染层,doc JSON 里没有 span,copy/paste/save
@@ -52,7 +51,14 @@ import {
type VoiceInputReplacementRange,
} from './VoiceInputDraftDecoration';
-const PLUGIN_KEY = new PluginKey<DecorationSet>('cjkPunctDecoration');
+type CjkDecorationPluginState = {
+ decorations: DecorationSet;
+ suspendedForComposition: boolean;
+};
+
+type CompositionMeta = 'suspend' | 'resume';
+
+const PLUGIN_KEY = new PluginKey<CjkDecorationPluginState>('cjkPunctDecoration');
/**
* CJK 标点字符集合。覆盖最常用的几个区段,够 chat input 场景用:
@@ -236,20 +242,41 @@ export const CjkPunctDecoration = Extension.create({
name: 'cjkPunctDecoration',
addProseMirrorPlugins() {
+ let resumeTimer: ReturnType<typeof setTimeout> | null = null;
+
return [
- new Plugin<DecorationSet>({
+ new Plugin<CjkDecorationPluginState>({
key: PLUGIN_KEY,
state: {
init(_config, state: EditorState) {
const roster = getSlashCommandRoster(state);
- return buildDecorations(state.doc, findSlashCommandMatches(state.doc, roster));
+ return {
+ decorations: buildDecorations(state.doc, findSlashCommandMatches(state.doc, roster)),
+ suspendedForComposition: false,
+ };
},
- apply(tr: Transaction, old: DecorationSet, oldState: EditorState) {
+ apply(tr: Transaction, old: CjkDecorationPluginState, oldState: EditorState) {
+ const compositionMeta = tr.getMeta(PLUGIN_KEY) as CompositionMeta | undefined;
+ if (compositionMeta === 'suspend') {
+ return {
+ decorations: DecorationSet.empty,
+ suspendedForComposition: true,
+ };
+ }
+
const rosterUpdate = getSlashCommandRosterUpdate(tr);
const voiceReplacement = resolveVoiceInputReplacementRange(tr, oldState);
+ if (old.suspendedForComposition && compositionMeta !== 'resume') {
+ return old;
+ }
// doc、命令 roster 和 voice replacement 都没变 → decoration 位置不变,
// 直接复用;任一输入变化都需要重新扫描。
- if (!tr.docChanged && rosterUpdate === undefined && !voiceReplacement.changed) {
+ if (
+ compositionMeta !== 'resume' &&
+ !tr.docChanged &&
+ rosterUpdate === undefined &&
+ !voiceReplacement.changed
+ ) {
return old;
}
// doc、命令 roster 或 voice replacement 变化 → 全量重算。
@@ -257,28 +284,56 @@ export const CjkPunctDecoration = Extension.create({
// 文本量很小 (< 1KB 常见), 全量重扫成本可忽略, 而增量映射要额外
// 处理"变化范围内新增/删除的 CJK 标点", 代码复杂度上升不划算。
const roster = rosterUpdate ?? getSlashCommandRoster(oldState);
- return buildDecorations(
- tr.doc,
- findSlashCommandMatches(tr.doc, roster),
- voiceReplacement.range,
- );
+ return {
+ decorations: buildDecorations(
+ tr.doc,
+ findSlashCommandMatches(tr.doc, roster),
+ voiceReplacement.range,
+ ),
+ suspendedForComposition: false,
+ };
},
},
props: {
decorations(state) {
- return this.getState(state) ?? DecorationSet.empty;
+ return this.getState(state)?.decorations ?? DecorationSet.empty;
+ },
+ handleDOMEvents: {
+ compositionstart(view) {
+ if (resumeTimer !== null) {
+ clearTimeout(resumeTimer);
+ resumeTimer = null;
+ }
+ if (!PLUGIN_KEY.getState(view.state)?.suspendedForComposition) {
+ view.dispatch(
+ view.state.tr
+ .setMeta(PLUGIN_KEY, 'suspend' satisfies CompositionMeta)
+ .setMeta('addToHistory', false),
+ );
+ }
+ return false;
+ },
+ compositionend(view) {
+ if (resumeTimer !== null) clearTimeout(resumeTimer);
+ resumeTimer = setTimeout(() => {
+ resumeTimer = null;
+ if (view.isDestroyed || view.composing) return;
+ if (!PLUGIN_KEY.getState(view.state)?.suspendedForComposition) return;
+ view.dispatch(
+ view.state.tr
+ .setMeta(PLUGIN_KEY, 'resume' satisfies CompositionMeta)
+ .setMeta('addToHistory', false),
+ );
+ }, 0);
+ return false;
+ },
},
},
view() {
return {
- update(view, prevState) {
- // IME 组合期 (用户打 pinyin 还没回车选字) 不重新计算 decoration,
- // 避免 DOM 抖动把输入法候选框踢掉。组合结束后 ProseMirror 会发
- // 一个常规 transaction, apply() 会把 decoration 补上。
- if (view.composing) return;
- // composing 期间 doc 也会变, 但 apply() 已经在每次 docChanged
- // 时重算了, 这里 view.update 是后置 hook, 不需要额外动作。
- void prevState;
+ destroy() {
+ if (resumeTimer !== null) clearTimeout(resumeTimer);
+ resumeTimer = null;
},
};
},
diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
index 07291c9df0..d051fcf6e0 100644
--- a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
@@ -19,7 +19,8 @@
* - decoration 只是渲染层,doc JSON / 草稿存储 / 发送内容里没有任何痕迹;
* - doc 没变直接复用 DecorationSet,变了全量重扫(chat input 文本量小,
* 全量成本可忽略,不值得做增量映射);
- * - 只在 doc 发生变化时重算,view.update 不参与 decoration 计算;
+ * - IME composition 开始前临时移除 decoration,结束后的下一轮 task 再按
+ * 当前 doc 补算,避免微软拼音输入时改写 composition DOM;
* - 这是纯文本编辑器的视觉缩进,不改变 doc JSON / 发送文本。
*/
import { Extension } from '@tiptap/core';
@@ -39,9 +40,19 @@ import {
type VoiceInputReplacementRange,
} from './VoiceInputDraftDecoration';
-const PLUGIN_KEY = new PluginKey<DecorationSet>('composerListIndentDecoration');
const TAB_SIZE = 8;
+type ListDecorationPluginState = {
+ decorations: DecorationSet;
+ suspendedForComposition: boolean;
+};
+
+type CompositionMeta = 'suspend' | 'resume';
+
+const PLUGIN_STATE_KEY = new PluginKey<ListDecorationPluginState>(
+ 'composerListIndentDecorationState',
+);
+
/** 行内一个非文本 inline 节点(mention chip 等)的占位符,与 applyListContinuation 一致。 */
const ATOM_PLACEHOLDER = '\uFFFC';
const CJK_PUNCTUATION_RE = /[\u3000-\u303f\uff00-\uffef]/;
@@ -380,40 +391,102 @@ export const ComposerListIndentDecoration = Extension.create({
name: 'composerListIndentDecoration',
addProseMirrorPlugins() {
+ let resumeTimer: ReturnType<typeof setTimeout> | null = null;
+
return [
- new Plugin<DecorationSet>({
- key: PLUGIN_KEY,
+ new Plugin<ListDecorationPluginState>({
+ key: PLUGIN_STATE_KEY,
state: {
init(_config, state: EditorState) {
const roster = getSlashCommandRoster(state);
- return buildListIndentDecorations(
- state.doc,
- findSlashCommandMatches(state.doc, roster),
- );
+ return {
+ decorations: buildListIndentDecorations(
+ state.doc,
+ findSlashCommandMatches(state.doc, roster),
+ ),
+ suspendedForComposition: false,
+ };
},
- apply(tr: Transaction, old: DecorationSet, oldState: EditorState) {
+ apply(tr: Transaction, old: ListDecorationPluginState, oldState: EditorState) {
+ const compositionMeta = tr.getMeta(PLUGIN_STATE_KEY) as CompositionMeta | undefined;
+ if (compositionMeta === 'suspend') {
+ return {
+ decorations: DecorationSet.empty,
+ suspendedForComposition: true,
+ };
+ }
+
const rosterUpdate = getSlashCommandRosterUpdate(tr);
const voiceReplacement = resolveVoiceInputReplacementRange(tr, oldState);
- if (!tr.docChanged && rosterUpdate === undefined && !voiceReplacement.changed) {
+ if (old.suspendedForComposition && compositionMeta !== 'resume') {
+ return old;
+ }
+ if (
+ compositionMeta !== 'resume' &&
+ !tr.docChanged &&
+ rosterUpdate === undefined &&
+ !voiceReplacement.changed
+ ) {
return old;
}
const roster = rosterUpdate ?? getSlashCommandRoster(oldState);
- return buildListIndentDecorations(
- tr.doc,
- findSlashCommandMatches(tr.doc, roster),
- voiceReplacement.range,
- );
+ return {
+ decorations: buildListIndentDecorations(
+ tr.doc,
+ findSlashCommandMatches(tr.doc, roster),
+ voiceReplacement.range,
+ ),
+ suspendedForComposition: false,
+ };
},
},
props: {
decorations(state) {
- return this.getState(state) ?? DecorationSet.empty;
+ return this.getState(state)?.decorations ?? DecorationSet.empty;
+ },
+ handleDOMEvents: {
+ compositionstart(view) {
+ if (resumeTimer !== null) {
+ clearTimeout(resumeTimer);
+ resumeTimer = null;
+ }
+ if (!PLUGIN_STATE_KEY.getState(view.state)?.suspendedForComposition) {
+ view.dispatch(
+ view.state.tr
+ .setMeta(PLUGIN_STATE_KEY, 'suspend' satisfies CompositionMeta)
+ .setMeta('addToHistory', false),
+ );
+ }
+ return false;
+ },
+ compositionend(view) {
+ if (resumeTimer !== null) clearTimeout(resumeTimer);
+ // ProseMirror's own compositionend handler runs after custom
+ // handlers and flushes pending DOM records in a microtask.
+ // A timer restores decorations after that flush, never while
+ // EditorView.composing still owns the native IME DOM.
+ resumeTimer = setTimeout(() => {
+ resumeTimer = null;
+ if (view.isDestroyed || view.composing) return;
+ if (!PLUGIN_STATE_KEY.getState(view.state)?.suspendedForComposition) return;
+ view.dispatch(
+ view.state.tr
+ .setMeta(PLUGIN_STATE_KEY, 'resume' satisfies CompositionMeta)
+ .setMeta('addToHistory', false),
+ );
+ }, 0);
+ return false;
+ },
},
},
- // 注:曾有一个 view().update 里 `if (view.composing) return` 的"IME 保护",
- // 但重算发生在上面的 state.apply(只看 tr.docChanged),view.update 在视图更新
- // 之后才跑、DecorationSet 早已算好,该钩子等价 no-op(greptile P2)——已删除。
- // 真要在 IME 期跳过重算,应在 apply 里按 composition 事务标记判断,而非此处。
+ view() {
+ return {
+ destroy() {
+ if (resumeTimer !== null) clearTimeout(resumeTimer);
+ resumeTimer = null;
+ },
+ };
+ },
}),
];
},