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): 修复 Windows 中文输入预览时标点抖动 (#894)

zhangyongjie4fd0df6c92df
diff --git a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
index 1800b47453..c9579cb584 100644
--- a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
@@ -284,7 +284,7 @@ describe('ComposerListIndentDecoration in a real editor', () => {
'1. 第一项\n2. ',
);
- const indentedRows = editor.view.dom.querySelectorAll('.composer-list-line-indent');
+ const indentedRows = editor.view.dom.querySelectorAll('.composer-list-fallback-prefix');
expect(indentedRows).toHaveLength(2);
expect(indentedRows[1]?.textContent).toBe('2. ');
@@ -292,7 +292,7 @@ describe('ComposerListIndentDecoration in a real editor', () => {
expect(editor.state.doc.textBetween(0, editor.state.doc.content.size, '\n', '\n')).toBe(
'1. 第一项\n2. 中文',
);
- expect(editor.view.dom.querySelectorAll('.composer-list-line-indent')).toHaveLength(2);
+ expect(editor.view.dom.querySelectorAll('.composer-list-fallback-prefix')).toHaveLength(2);
});
it('does not rewrite decoration-owned styles while laying out multiline CJK lists', () => {
@@ -461,6 +461,58 @@ describe('ComposerListIndentDecoration in a real editor', () => {
}
});
+ it('keeps ASCII punctuation in a CJK sentence stable during IME preview', () => {
+ vi.useFakeTimers();
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [Document, Paragraph, Text, CjkPunctDecoration],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ {
+ type: 'text',
+ text: '现代都市开放世界共创游戏。 () 在上面这个句语基础上,',
+ },
+ ],
+ },
+ ],
+ },
+ });
+
+ const punctuationSelector = 'span[style*="font-family"]';
+ const currentEditor = editor;
+ if (!currentEditor) throw new Error('editor failed to initialize');
+ const decoratedPunctuation = () =>
+ Array.from(currentEditor.view.dom.querySelectorAll(punctuationSelector), (node) => node.textContent);
+ expect(decoratedPunctuation()).toEqual(['。', '(', ')', ',']);
+
+ editor.view.dom.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
+ editor.view.dispatch(
+ editor.state.tr
+ .insertText('w', editor.state.doc.content.size - 1)
+ .setMeta('composition', 1),
+ );
+ expect(editor.getText()).toBe('现代都市开放世界共创游戏。 () 在上面这个句语基础上,w');
+ expect(decoratedPunctuation()).toEqual(['。', '(', ')', ',']);
+
+ editor.view.dom.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));
+ vi.runOnlyPendingTimers();
+ expect(decoratedPunctuation()).toEqual(['。', '(', ')', ',']);
+ });
+
+ it('does not apply the CJK punctuation font to an isolated Latin punctuation run', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [Document, Paragraph, Text, CjkPunctDecoration],
+ content: 'hello (), world',
+ });
+
+ expect(editor.view.dom.querySelectorAll('span[style*="font-family"]')).toHaveLength(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');
@@ -589,6 +641,90 @@ describe('ComposerListIndentDecoration in a real editor', () => {
).toBeGreaterThan(0);
});
+ it('keeps ASCII punctuation in a list prefix inside the fixed CJK font slot', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ CjkPunctDecoration,
+ ComposerListIndentDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'intro' },
+ { type: 'hardBreak' },
+ { type: 'text', text: '1. 中文正文' },
+ ],
+ },
+ ],
+ },
+ });
+ const prefix = editor.view.dom.querySelector(
+ '.composer-list-fallback-prefix.composer-list-cjk-font',
+ );
+ expect(prefix?.textContent).toBe('1. ');
+ expect(prefix?.querySelectorAll('span[style*="font-family"]')).toHaveLength(0);
+ expect(editor.view.dom.querySelectorAll('span[style*="font-family"]')).toHaveLength(0);
+ });
+
+ it('keeps fallback-owned ASCII punctuation stable while list wrappers are suspended for IME', () => {
+ 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. 中文正文' },
+ { type: 'hardBreak' },
+ { type: 'text', text: '中文,内容' },
+ ],
+ },
+ ],
+ },
+ });
+
+ const punctuation = () =>
+ Array.from(editor?.view.dom.querySelectorAll('span[style*="font-family"]') ?? [], (node) =>
+ node.textContent,
+ );
+ expect(punctuation()).toEqual([]);
+ expect(editor.view.dom.querySelector('.composer-list-fallback-container')).not.toBeNull();
+
+ editor.view.dom.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
+ expect(editor.view.composing).toBe(true);
+ expect(editor.view.dom.querySelector('.composer-list-fallback-container')).toBeNull();
+ expect(punctuation()).toEqual(['.', ',']);
+
+ editor.view.dispatch(
+ editor.state.tr.insertText('中', editor.state.doc.content.size - 1).setMeta('composition', 1),
+ );
+ expect(punctuation()).toEqual(['.', ',']);
+
+ editor.view.dom.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));
+ vi.runOnlyPendingTimers();
+ expect(editor.view.composing).toBe(false);
+ expect(punctuation()).toEqual([]);
+ expect(editor.view.dom.querySelector('.composer-list-fallback-container')).not.toBeNull();
+ });
+
it('keeps slash-command pills inline inside the paragraph fallback flow', () => {
editor = new Editor({
element: document.createElement('div'),
@@ -797,7 +933,7 @@ describe('ComposerListIndentDecoration in a real editor', () => {
{
type: 'paragraph',
content: [
- { type: 'text', text: '1. 有新增游戏数的用户数、占全部用户比例。' },
+ { type: 'text', text: '1. 有新增游戏数的用户数,占全部用户比例。' },
{ type: 'hardBreak' },
{ type: 'text', text: '2. 有新增游戏数的近30天、近1年活跃用户数及占比。' },
{ type: 'hardBreak' },
@@ -817,7 +953,7 @@ describe('ComposerListIndentDecoration in a real editor', () => {
const unindentedRows = container?.querySelectorAll('.composer-list-fallback-unindented');
expect(container).not.toBeNull();
expect(unindentedRows).toHaveLength(1);
- expect(unindentedRows?.[0]?.textContent).toBe('有新增游戏数的用户数、占全部用户比例。');
+ expect(unindentedRows?.[0]?.textContent).toBe('有新增游戏数的用户数,占全部用户比例。');
expect(unindentedRows?.[0]?.classList.contains('composer-list-cjk-font')).toBe(false);
expect(
unindentedRows?.[0]?.classList.contains('composer-list-cjk-punctuation-font'),
@@ -988,7 +1124,8 @@ describe('wiring contract', () => {
expect(css).toContain('.ProseMirror .composer-list-cjk-punctuation-font');
expect(css).toContain("font-family: 'Cindy CJK Punctuation Local'");
expect(css).toContain("font-family: 'Cindy CJK Punctuation Bundled'");
- expect(css).toContain('unicode-range: U+3000-303F, U+FF00-FFEF;');
+ expect(css).toContain('U+3000-303F, U+FF00-FFEF;');
+ expect(css.match(/U\+0021-0022, U\+0027-0029/g)).toHaveLength(2);
const punctuationFontCss = css.slice(
css.indexOf("font-family: 'Cindy CJK Punctuation Local'"),
css.indexOf('.ProseMirror .composer-list-cjk-punctuation-font'),
diff --git a/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts b/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
index fc73ec4c05..78975b3146 100644
--- a/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
@@ -51,6 +51,10 @@ import {
resolveVoiceInputReplacementRange,
type VoiceInputReplacementRange,
} from './VoiceInputDraftDecoration';
+import {
+ hasCjkContextPunctuation,
+ isCjkContextPunctuation,
+} from './CjkPunctuationUtils';
type CjkDecorationPluginState = {
decorations: DecorationSet;
@@ -61,15 +65,6 @@ type CompositionMeta = 'suspend' | 'resume';
const PLUGIN_KEY = new PluginKey<CjkDecorationPluginState>('cjkPunctDecoration');
-/**
- * CJK 标点字符集合。覆盖最常用的几个区段,够 chat input 场景用:
- * U+3000-303F: CJK Symbols and Punctuation (含 《》「」『』【】 等)
- * U+FF00-FFEF: Halfwidth and Fullwidth Forms (含全角 (), !? 等)
- *
- * 不包括 ASCII 标点,因为它们 script 已经是 Latin,不会触发 itemization 错乱。
- */
-const CJK_PUNCT_REGEX = /[\u3000-\u303f\uff00-\uffef]/g;
-
const LONG_ALPHANUMERIC_BODY_RE = /^\s*[A-Za-z0-9]{12,}\s*$/;
type ListLineRange = { from: number; to: number };
@@ -140,8 +135,7 @@ function listLineRanges(
voiceReplacementRange !== null &&
voiceReplacementRange.from < contentBase + line.end &&
voiceReplacementRange.to > contentBase + line.start;
- const hasCjkPunctuation = CJK_PUNCT_REGEX.test(line.text);
- CJK_PUNCT_REGEX.lastIndex = 0;
+ const hasCjkPunctuation = hasCjkContextPunctuation(line.text);
return (
line.hasInlineAtom ||
overlapsSlashCommandPill ||
@@ -201,25 +195,27 @@ const CJK_FONT_STACK =
/**
* 扫描整个 doc, 给所有 CJK 标点位置生成 inline decoration。
- * 用 descendants 遍历所有 text node, 对每个 text node 内的字符做正则匹配。
+ * 用 descendants 遍历所有 text node, 对每个 text node 内的字符做上下文匹配。
* 注意 from/to 是 doc-level position, 不是 text-node-local offset。
*/
function buildDecorations(
doc: PMNode,
slashCommandMatches: ReadonlyArray<Pick<SlashCommandMatch, 'from' | 'to'>> = [],
voiceReplacementRange: VoiceInputReplacementRange | null = null,
+ ignoreListRanges = false,
): DecorationSet {
const decorations: Decoration[] = [];
- const listRanges = listLineRanges(doc, slashCommandMatches, voiceReplacementRange);
+ const listRanges = ignoreListRanges
+ ? []
+ : listLineRanges(doc, slashCommandMatches, voiceReplacementRange);
doc.descendants((node, pos) => {
if (!node.isText || !node.text) return;
const text = node.text;
- CJK_PUNCT_REGEX.lastIndex = 0;
- let m: RegExpExecArray | null;
- while ((m = CJK_PUNCT_REGEX.exec(text)) !== null) {
- const from = pos + m.index;
- const to = from + m[0].length;
+ for (let index = 0; index < text.length; index += 1) {
+ if (!isCjkContextPunctuation(text, index)) continue;
+ const from = pos + index;
+ const to = from + 1;
if (listRanges.some((range) => from >= range.from && to <= range.to)) {
// ComposerListIndentDecoration owns the wrapping container for these
// ranges. An overlapping inline font decoration would split fixed-width
@@ -260,8 +256,20 @@ export const CjkPunctDecoration = Extension.create({
apply(tr: Transaction, old: CjkDecorationPluginState, oldState: EditorState) {
const compositionMeta = tr.getMeta(PLUGIN_KEY) as CompositionMeta | undefined;
if (compositionMeta === 'suspend') {
+ // ComposerListIndentDecoration removes its wrappers during IME
+ // composition so ProseMirror does not let native composition DOM
+ // get split by stale layout decorations. Rebuild CJK spans
+ // without the list-owned exclusions for that same window; this
+ // keeps marker dots and fallback sibling ASCII punctuation in the
+ // explicit CJK font stack while the list wrappers are absent.
+ const roster = getSlashCommandRoster(oldState);
return {
- decorations: old.decorations,
+ decorations: buildDecorations(
+ tr.doc,
+ findSlashCommandMatches(tr.doc, roster),
+ resolveVoiceInputReplacementRange(tr, oldState).range,
+ true,
+ ),
suspendedForComposition: true,
};
}
diff --git a/apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts b/apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts
new file mode 100644
index 0000000000..4f6575dcf0
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts
@@ -0,0 +1,71 @@
+/**
+ * Shared CJK-context punctuation rules for the composer decoration plugins.
+ *
+ * ASCII punctuation can take the neighboring Latin font during Windows IME
+ * composition, but only punctuation next to CJK text needs the CJK font stack.
+ * Keeping this predicate shared prevents list fallback wrappers and inline
+ * punctuation spans from disagreeing about which ranges they own.
+ */
+const CJK_PUNCT_CHAR_REGEX = /[\u3000-\u303f\uff00-\uffef]/;
+const CJK_SCRIPT_CHAR_REGEX = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/;
+const ASCII_CJK_PUNCTUATION = new Set([
+ '!',
+ '"',
+ "'",
+ '(',
+ ')',
+ ',',
+ '.',
+ ':',
+ ';',
+ '?',
+ '[',
+ ']',
+ '{',
+ '}',
+]);
+
+function isCjkChar(char: string | undefined): boolean {
+ return (
+ char !== undefined &&
+ (CJK_SCRIPT_CHAR_REGEX.test(char) || CJK_PUNCT_CHAR_REGEX.test(char))
+ );
+}
+
+/**
+ * Tests one character in the full text. The optional range limits which
+ * punctuation characters are selected, while neighbor lookup still sees the
+ * complete text so a list prefix can inherit context from its body.
+ */
+export function isCjkContextPunctuation(
+ text: string,
+ index: number,
+ from = 0,
+ to = text.length,
+): boolean {
+ const char = text[index];
+ if (char === undefined || index < from || index >= to) return false;
+ if (CJK_PUNCT_CHAR_REGEX.test(char)) return true;
+ if (!ASCII_CJK_PUNCTUATION.has(char)) return false;
+
+ const isContextSeparator = (value: string | undefined) =>
+ value !== undefined && (/\s/.test(value) || ASCII_CJK_PUNCTUATION.has(value));
+ let before = index - 1;
+ while (before >= 0 && isContextSeparator(text[before])) before -= 1;
+ if (before >= 0 && isCjkChar(text[before])) return true;
+
+ let after = index + 1;
+ while (after < text.length && isContextSeparator(text[after])) after += 1;
+ return after < text.length && isCjkChar(text[after]);
+}
+
+export function hasCjkContextPunctuation(
+ text: string,
+ from = 0,
+ to = text.length,
+): boolean {
+ for (let index = from; index < to; index += 1) {
+ if (isCjkContextPunctuation(text, index, from, to)) return true;
+ }
+ return false;
+}
diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
index 9b6bde7ae9..c71437397d 100644
--- a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
@@ -40,6 +40,7 @@ import {
resolveVoiceInputReplacementRange,
type VoiceInputReplacementRange,
} from './VoiceInputDraftDecoration';
+import { hasCjkContextPunctuation } from './CjkPunctuationUtils';
const TAB_SIZE = 8;
@@ -56,7 +57,6 @@ const PLUGIN_STATE_KEY = new PluginKey<ListDecorationPluginState>(
/** 行内一个非文本 inline 节点(mention chip 等)的占位符,与 applyListContinuation 一致。 */
const ATOM_PLACEHOLDER = '\uFFFC';
-const CJK_PUNCTUATION_RE = /[\u3000-\u303f\uff00-\uffef]/;
// 只有正文整体是一个没有自然断点的数字/字母串时才拆成 marker/body。
// 普通句子里偶然出现长 token 时,交给 overflow-wrap:anywhere,保留空格
// 的自然断词行为,避免把整句变成逐字断行。
@@ -217,7 +217,7 @@ export function buildListIndentDecorations(
voiceReplacementRange !== null &&
voiceReplacementRange.from < contentBase + line.end &&
voiceReplacementRange.to > contentBase + line.start;
- const hasCjkPunctuation = CJK_PUNCTUATION_RE.test(line.text);
+ const hasCjkPunctuation = hasCjkContextPunctuation(line.text);
return (
line.hasInlineAtom ||
overlapsSlashCommandPill ||
@@ -249,7 +249,7 @@ export function buildListIndentDecorations(
const match = compatibilityMatch(line);
if (!match) {
if (hasFallbackLine && lines.length > 1 && line.end > line.start) {
- const hasCjkPunctuation = CJK_PUNCTUATION_RE.test(line.text);
+ const hasCjkPunctuation = hasCjkContextPunctuation(line.text);
decorations.push(
Decoration.inline(contentBase + line.start, contentBase + line.end, {
class: [
@@ -268,7 +268,8 @@ export function buildListIndentDecorations(
const prefix = line.text.slice(0, match.prefixLength);
const body = line.text.slice(match.prefixLength);
const hasTabPrefix = prefix.includes('\t');
- const prefixHasCjkPunctuation = CJK_PUNCTUATION_RE.test(prefix);
+ const prefixHasCjkPunctuation =
+ match !== null && hasCjkContextPunctuation(line.text, 0, match.prefixLength);
const lineClass = hasTabPrefix ? 'composer-list-tab-indent' : '';
if (hasFallbackLine) {
// The paragraph-level fallback supplies the available line width. The
@@ -324,7 +325,8 @@ export function buildListIndentDecorations(
const body = line && match ? line.text.slice(match.prefixLength) : '';
const from = line ? contentBase + line.start : contentBase;
const hasLongAlphanumericBody = LONG_ALPHANUMERIC_BODY_RE.test(body);
- const prefixHasCjkPunctuation = CJK_PUNCTUATION_RE.test(prefix);
+ const prefixHasCjkPunctuation =
+ match !== null && hasCjkContextPunctuation(line.text, 0, match.prefixLength);
const hasTabPrefix = prefix.includes('\t');
// A node decoration stays on the paragraph even when CjkPunctDecoration
// adds nested inline spans, so punctuation cannot split the list wrapper.
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index c450b3f0e7..3515637cb8 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -463,9 +463,10 @@ html:lang(ko) {
/* The fallback unindented row must remain one inline-block; character-scoped
ProseMirror decorations would split it into several full-width fragments.
The local face covers the same ranges as CjkPunctDecoration, while the
- bundled faces cover the punctuation glyphs HarmonyOS actually ships. Latin
- text and digits continue through the configured UI font. Keep the asset
- names aligned with the exact-pinned font package. */
+ bundled faces cover the punctuation glyphs HarmonyOS actually ships. The
+ ASCII range is punctuation-only, so Latin letters and digits continue
+ through the configured UI font. Keep the asset names aligned with the
+ exact-pinned font package. */
@font-face {
font-family: 'Cindy CJK Punctuation Local';
src:
@@ -478,7 +479,9 @@ html:lang(ko) {
font-style: normal;
font-weight: 400;
font-display: swap;
- unicode-range: U+3000-303F, U+FF00-FFEF;
+ unicode-range:
+ U+0021-0022, U+0027-0029, U+002C, U+002E, U+003A-003B, U+003F, U+005B, U+005D, U+007B, U+007D,
+ U+3000-303F, U+FF00-FFEF;
}
@font-face {
font-family: 'Cindy CJK Punctuation Bundled';
@@ -517,7 +520,9 @@ html:lang(ko) {
font-style: normal;
font-weight: 400;
font-display: swap;
- unicode-range: U+FF04, U+FF0B, U+FF1C-FF1E, U+FF3E, U+FF40, U+FF5C, U+FF5E, U+FFE0-FFE5;
+ unicode-range:
+ U+0021-0022, U+0027-0029, U+002C, U+002E, U+003A-003B, U+003F, U+005B, U+005D, U+007B, U+007D,
+ U+FF04, U+FF0B, U+FF1C-FF1E, U+FF3E, U+FF40, U+FF5C, U+FF5E, U+FFE0-FFE5;
}
.ProseMirror .composer-list-cjk-punctuation-font {
font-family: