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): 修复对话框列表长文本换行缩进 (#486)

zhangyongjie5f7d5fa337d5
diff --git a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
index 837fe87361..178a5ad5d3 100644
--- a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts
@@ -17,6 +17,10 @@ import {
setSlashCommandRoster,
SlashCommandDecoration,
} from '@/components/new-chat/SlashCommandDecoration';
+import {
+ setVoiceInputDraftDecoration,
+ VoiceInputDraftDecoration,
+} from '@/components/new-chat/VoiceInputDraftDecoration';
/**
* composer 列表行缩进 decoration:
@@ -81,9 +85,11 @@ describe('buildListIndentDecorations', () => {
expect(cjkStyle).not.toContain('10、');
});
- it('skips tab-indented lines instead of guessing a proportional-font tab width', () => {
+ it('decorates tab-indented lines and leaves their final width to browser measurement', () => {
const ed = makeEditor(['\t1. item']);
- expect(buildListIndentDecorations(ed.state.doc).find()).toHaveLength(0);
+ const tabIndent = ed.view.dom.querySelector('.composer-list-tab-indent');
+ expect(tabIndent).not.toBeNull();
+ expect(tabIndent?.getAttribute('data-composer-list-prefix-length')).toBe('4');
});
it('decorates the full content of a single-line item', () => {
@@ -109,10 +115,42 @@ describe('buildListIndentDecorations', () => {
Array.from(ed.view.dom.querySelectorAll('span.composer-list-long-run-body')).map(
(node) => node.textContent,
),
- ).toEqual([
- '221241412423532235235325235212414',
- 'abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
- ]);
+ ).toEqual(['221241412423532235235325235212414', 'abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb']);
+ });
+
+ it('keeps ordinary prose as one wrapper when it contains a long token', () => {
+ const ed = makeEditor(['- review abcdefghijklmnop before sending']);
+ expect(ed.view.dom.querySelector('p.composer-list-block-indent')).not.toBeNull();
+ expect(ed.view.dom.querySelector('span.composer-list-long-run-body')).toBeNull();
+ });
+
+ it('keeps a recognized slash pill inside a single-line list wrapper', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ SlashCommandDecoration,
+ ComposerListIndentDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '- /foo abcdefghijklmnop' }],
+ },
+ ],
+ },
+ });
+ setSlashCommandRoster(editor, [{ name: 'foo', description: 'test command' }]);
+ expect(editor.view.dom.querySelector('p.composer-list-fallback-container')?.textContent).toBe(
+ '- /foo abcdefghijklmnop',
+ );
+ expect(editor.view.dom.querySelector('span.slash-cmd-pill')?.textContent).toBe('/foo');
+ expect(editor.view.dom.querySelector('span.composer-list-long-run-body')).toBeNull();
});
it('decorates each list line independently across hardBreaks', () => {
@@ -136,7 +174,7 @@ describe('buildListIndentDecorations', () => {
expect(buildListIndentDecorations(ed.state.doc).find()).toHaveLength(0);
});
- it('uses prefix-only fallback so inline atoms keep their geometry', () => {
+ it('uses a paragraph fallback so inline atoms keep their geometry', () => {
editor = new Editor({
element: document.createElement('div'),
extensions: [Document, Paragraph, Text, HardBreak, TestAtom, ComposerListIndentDecoration],
@@ -154,24 +192,50 @@ describe('buildListIndentDecorations', () => {
],
},
});
- expect(buildListIndentDecorations(editor.state.doc).find()).toHaveLength(1);
- expect(
- editor.view.dom.querySelector('span.composer-list-prefix-indent')?.textContent,
- ).toBe('- ');
+ expect(editor.view.dom.querySelector('p.composer-list-fallback-container')).not.toBeNull();
+ expect(editor.view.dom.querySelector('span.composer-list-fallback-prefix')?.textContent).toBe(
+ '- ',
+ );
expect(
editor.view.dom
.querySelector('[data-test-atom]')
?.classList.contains('composer-list-line-indent'),
).toBe(false);
});
+
+ it('chooses the widest complete fallback prefix instead of combining their units', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [Document, Paragraph, Text, HardBreak, TestAtom, ComposerListIndentDecoration],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: '10. before ' },
+ { type: 'testAtom' },
+ { type: 'hardBreak' },
+ { type: 'text', text: '1、next' },
+ ],
+ },
+ ],
+ },
+ });
+ const container = editor.view.dom.querySelector<HTMLElement>(
+ 'p.composer-list-fallback-container',
+ );
+ expect(container?.style.getPropertyValue('--composer-list-fallback-indent')).toBe(
+ 'max(2.8ch, calc(1ch + 1em))',
+ );
+ expect(container?.getAttribute('style')).not.toContain('calc(2.8ch + 1em)');
+ });
});
describe('ComposerListIndentDecoration in a real editor', () => {
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',
- );
+ expect(ed.view.dom.querySelector('p.composer-list-block-indent')?.textContent).toBe('1. hello');
expect(
ed.view.dom
.querySelector<HTMLElement>('p.composer-list-block-indent')
@@ -202,30 +266,102 @@ describe('ComposerListIndentDecoration in a real editor', () => {
});
expect(editor.view.dom.querySelectorAll('p.composer-list-block-indent')).toHaveLength(1);
expect(editor.view.dom.querySelectorAll('span.composer-list-line-indent')).toHaveLength(0);
- expect(editor.view.dom.querySelectorAll('span[style*="font-family"]')).not.toHaveLength(0);
+ const wrapper = editor.view.dom.querySelector('p.composer-list-block-indent');
+ expect(wrapper?.classList.contains('composer-list-cjk-font')).toBe(false);
+ expect(wrapper?.querySelectorAll('span[style*="font-family"]').length).toBeGreaterThan(0);
});
- it('uses prefix-only fallback for CJK punctuation in hardBreak-separated list lines', () => {
- const ed = makeEditor(['- 中文,内容', '2. plain']);
- expect(
- Array.from(ed.view.dom.querySelectorAll('span.composer-list-prefix-indent')).map(
- (node) => node.textContent,
- ),
- ).toEqual(['- ']);
- expect(indentSpans(ed)).toEqual(['2. plain']);
+ it('keeps Tab-prefixed CJK rows inside the measured list wrapper', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ CjkPunctDecoration,
+ ComposerListIndentDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '\t1. 中文《内容》' }] }],
+ },
+ });
+ const wrapper = editor.view.dom.querySelector('p.composer-list-block-indent');
+ expect(wrapper?.classList.contains('composer-list-tab-indent')).toBe(true);
+ expect(wrapper?.classList.contains('composer-list-cjk-font')).toBe(false);
+ expect(wrapper?.querySelectorAll('span[style*="font-family"]').length).toBeGreaterThan(0);
});
- it('keeps hanging indent when CJK punctuation belongs only to the list marker', () => {
- const ed = makeEditor(['intro', '1、中文正文会在输入框边界自然换行']);
+ it('keeps multiline CJK punctuation inside the paragraph fallback flow', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ CjkPunctDecoration,
+ ComposerListIndentDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: '- 中文《内容》' },
+ { type: 'hardBreak' },
+ { type: 'text', text: '2. plain' },
+ ],
+ },
+ ],
+ },
+ });
+ const container = editor.view.dom.querySelector('p.composer-list-fallback-container');
+ expect(container).not.toBeNull();
+ expect(container?.querySelectorAll('.composer-list-line-indent')).toHaveLength(0);
+ expect(container?.querySelectorAll('span[style*="font-family"]').length).toBeGreaterThan(0);
+ });
+
+ it('keeps the CJK marker in one fixed fallback prefix 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(
- Array.from(ed.view.dom.querySelectorAll('span.composer-list-prefix-indent')).map(
- (node) => node.textContent,
- ),
- ).toEqual([]);
- expect(indentSpans(ed)).toEqual(['1、中文正文会在输入框边界自然换行']);
+ editor.view.dom.querySelectorAll(
+ 'p.composer-list-fallback-container span[style*="font-family"]',
+ ).length,
+ ).toBeGreaterThan(0);
});
- it('keeps slash-command pills inline by falling back to prefix-only decoration', () => {
+ it('keeps slash-command pills inline inside the paragraph fallback flow', () => {
editor = new Editor({
element: document.createElement('div'),
extensions: [
@@ -251,11 +387,169 @@ describe('ComposerListIndentDecoration in a real editor', () => {
},
});
setSlashCommandRoster(editor, [{ name: 'foo', description: 'test command' }]);
- expect(
- editor.view.dom.querySelector('span.composer-list-prefix-indent')?.textContent,
- ).toBe('- ');
+ expect(editor.view.dom.querySelector('span.composer-list-fallback-prefix')?.textContent).toBe(
+ '- ',
+ );
+ expect(editor.view.dom.querySelector('p.composer-list-fallback-container')).not.toBeNull();
+ expect(editor.view.dom.querySelector('br.composer-list-fallback-break')).not.toBeNull();
expect(editor.view.dom.querySelector('span.slash-cmd-pill')?.textContent).toBe('/foo');
- expect(indentSpans(editor)).toEqual(['2. plain']);
+ expect(editor.view.dom.querySelector('p.composer-list-fallback-container')?.textContent).toBe(
+ '- /foo details2. plain',
+ );
+ });
+
+ it('preserves consecutive hard breaks inside the paragraph fallback flow', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ SlashCommandDecoration,
+ ComposerListIndentDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: '- /foo' },
+ { type: 'hardBreak' },
+ { type: 'hardBreak' },
+ { type: 'text', text: '2. next' },
+ ],
+ },
+ ],
+ },
+ });
+ setSlashCommandRoster(editor, [{ name: 'foo', description: 'test command' }]);
+ expect(
+ editor.view.dom.querySelectorAll(
+ 'p.composer-list-fallback-container br.composer-list-fallback-break',
+ ),
+ ).toHaveLength(2);
+ });
+
+ it('uses the paragraph fallback while voice replacement overlaps a multiline list row', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ CjkPunctDecoration,
+ ComposerListIndentDecoration,
+ VoiceInputDraftDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: '- first' },
+ { type: 'hardBreak' },
+ { type: 'text', text: '2. second row' },
+ ],
+ },
+ ],
+ },
+ });
+ expect(editor.view.dom.querySelectorAll('.composer-list-line-indent')).toHaveLength(2);
+
+ setVoiceInputDraftDecoration(
+ editor,
+ 'replacement',
+ 'refinement',
+ { from: 9, to: 21 },
+ 'processing',
+ );
+ expect(editor.view.dom.querySelector('p.composer-list-fallback-container')).not.toBeNull();
+ expect(editor.view.dom.querySelector('.composer-list-line-indent')).toBeNull();
+ expect(editor.view.dom.querySelector('[data-voice-draft-inline]')?.textContent).toBe(
+ 'replacement',
+ );
+ expect(editor.view.dom.querySelector('.voice-input-draft-replaced')).not.toBeNull();
+
+ setVoiceInputDraftDecoration(editor, '', null);
+ expect(editor.view.dom.querySelector('p.composer-list-fallback-container')).toBeNull();
+ expect(editor.view.dom.querySelectorAll('.composer-list-line-indent')).toHaveLength(2);
+ });
+
+ it('keeps an inline atom and body punctuation inside the multiline fallback flow', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ TestAtom,
+ CjkPunctDecoration,
+ ComposerListIndentDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: '- before ' },
+ { type: 'testAtom' },
+ { type: 'text', text: ' 《body》' },
+ { type: 'hardBreak' },
+ { type: 'text', text: '2. next' },
+ ],
+ },
+ ],
+ },
+ });
+ const container = editor.view.dom.querySelector('p.composer-list-fallback-container');
+ expect(container).not.toBeNull();
+ expect(container?.querySelector('[data-test-atom]')).not.toBeNull();
+ expect(container?.querySelector('.composer-list-fallback-prefix')?.textContent).toBe('- ');
+ expect(container?.querySelectorAll('.composer-list-line-indent')).toHaveLength(0);
+ // The fallback does not suppress CjkPunctDecoration, so body punctuation
+ // still receives an explicit font span instead of being silently skipped.
+ expect(container?.querySelectorAll('span[style*="font-family"]')).not.toHaveLength(0);
+ });
+
+ it('keeps CJK styling on fallback sibling rows', () => {
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [
+ Document,
+ Paragraph,
+ Text,
+ HardBreak,
+ TestAtom,
+ CjkPunctDecoration,
+ ComposerListIndentDecoration,
+ ],
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: '- before ' },
+ { type: 'testAtom' },
+ { type: 'text', text: ' 《body》' },
+ { type: 'hardBreak' },
+ { type: 'text', text: '2. 中文,内容' },
+ ],
+ },
+ ],
+ },
+ });
+ const container = editor.view.dom.querySelector('p.composer-list-fallback-container');
+ expect(container).not.toBeNull();
+ expect(container?.querySelectorAll('span[style*="font-family"]').length).toBeGreaterThanOrEqual(
+ 3,
+ );
});
it('keeps hanging indent for slash paths and unknown commands without pills', () => {
@@ -313,7 +607,9 @@ describe('wiring contract', () => {
resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),
'utf8',
);
- expect(src).toContain("import { ComposerListIndentDecoration } from './ComposerListIndentDecoration';");
+ expect(src).toContain(
+ "import { ComposerListIndentDecoration } from './ComposerListIndentDecoration';",
+ );
expect(src).toMatch(/CjkPunctDecoration,\s*\n\s*ComposerListIndentDecoration,/);
});
@@ -321,19 +617,35 @@ describe('wiring contract', () => {
const css = readFileSync(resolve(__dirname, '..', 'styles', 'globals.css'), 'utf8');
expect(css).toContain('.ProseMirror .composer-list-block-indent');
expect(css).toContain('.ProseMirror .composer-list-prefix-indent');
- expect(css).toContain('.ProseMirror span.composer-list-line-indent');
+ expect(css).toContain('.ProseMirror .composer-list-line-indent');
+ expect(css).toContain(
+ 'width: calc(100% + 1em + var(--composer-list-fallback-indent, 1.25em));',
+ );
+ expect(css).toContain(
+ 'margin-left: calc(-1em - var(--composer-list-fallback-indent, 1.25em));',
+ );
expect(css).toContain('display: inline-block;');
expect(css).toContain('width: 100%;');
expect(css).toContain('padding-left: calc(1em + var(--composer-list-hang, 1.25em));');
expect(css).toContain('text-indent: var(--composer-list-hang-negative, -1.25em);');
expect(css).toContain('overflow-wrap: anywhere;');
- expect(css).toContain('.ProseMirror .composer-list-long-run-indent');
- expect(css).toContain('word-break: break-all;');
expect(css).toContain('.ProseMirror .composer-list-long-run-marker');
expect(css).toContain('.ProseMirror .composer-list-long-run-body');
+ expect(css).toContain('.ProseMirror .composer-list-tab-indent');
+ expect(css).toContain('tab-size: 8;');
expect(css).toContain('white-space: nowrap;');
+ const fallbackBreakRule = css.match(
+ /\.ProseMirror \.composer-list-fallback-break \{([\s\S]*?)\n\}/,
+ )?.[1];
+ expect(fallbackBreakRule).toContain('display: inline;');
+ expect(fallbackBreakRule).not.toContain('height: 0');
+ expect(fallbackBreakRule).not.toContain('line-height: 0');
+ const longRunBodyRule = css.match(
+ /\.ProseMirror \.composer-list-long-run-body \{([\s\S]*?)\n\}/,
+ )?.[1];
+ expect(longRunBodyRule).toContain('word-break: break-all;');
const regularIndentRule = css.match(
- /\.ProseMirror span\.composer-list-line-indent \{([\s\S]*?)\n\}/,
+ /\.ProseMirror \.composer-list-line-indent \{([\s\S]*?)\n\}/,
)?.[1];
expect(regularIndentRule).not.toContain('word-break: break-all;');
});
diff --git a/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts b/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
index 3339b3a90e..0321c6f3a6 100644
--- a/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts
@@ -21,10 +21,11 @@
*
* 边界处理
* --------
- * - IME 组合期 (用户打 pinyin 还没选字): view.composing === true,跳过 decoration
- * 重算,避免 DOM 抖动打断输入法候选框
- * - 性能: 用 DecorationSet.map(tr.mapping, tr.doc) 增量映射 —— 只对变化范围内的
- * 节点重扫,不全文扫
+ * - IME 组合期 (用户打 pinyin 还没选字): view.update() 跳过布局测量,
+ * 避免同步 layout 读写干扰输入法候选框; decoration state 仍由 transaction
+ * 驱动,在 doc/meta 变化时按正常路径重算。
+ * - 性能: chat input 文本量很小,doc 变化、slash roster 或 voice replacement
+ * range 变化时采用全量重扫;不使用 DecorationSet.map 增量映射,以保持边界逻辑简单。
* - 不污染源数据: decoration 只是渲染层,doc JSON 里没有 span,copy/paste/save
* 拿到的都是纯文本
*
@@ -39,6 +40,17 @@ import { Plugin, PluginKey } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import type { EditorState, Transaction } from '@tiptap/pm/state';
import type { Node as PMNode } from '@tiptap/pm/model';
+import { matchListPrefix } from '@/lib/composerListContinuation';
+import {
+ findSlashCommandMatches,
+ getSlashCommandRoster,
+ getSlashCommandRosterUpdate,
+ type SlashCommandMatch,
+} from './SlashCommandDecoration';
+import {
+ resolveVoiceInputReplacementRange,
+ type VoiceInputReplacementRange,
+} from './VoiceInputDraftDecoration';
const PLUGIN_KEY = new PluginKey<DecorationSet>('cjkPunctDecoration');
@@ -51,6 +63,108 @@ const PLUGIN_KEY = new PluginKey<DecorationSet>('cjkPunctDecoration');
*/
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 };
+
+function listLineRanges(
+ doc: PMNode,
+ slashCommandMatches: ReadonlyArray<Pick<SlashCommandMatch, 'from' | 'to'>> = [],
+ voiceReplacementRange: VoiceInputReplacementRange | null = null,
+): ListLineRange[] {
+ const ranges: ListLineRange[] = [];
+ doc.descendants((block, blockPos) => {
+ if (!block.isTextblock) return true;
+ const contentBase = blockPos + 1;
+ let lineText = '';
+ let lineStart = 0;
+ let lineEnd = 0;
+ let lineHasInlineAtom = false;
+ const lines: Array<{
+ text: string;
+ start: number;
+ end: number;
+ hasInlineAtom: boolean;
+ }> = [];
+ const flush = () => {
+ lines.push({
+ text: lineText,
+ start: lineStart,
+ end: lineEnd,
+ hasInlineAtom: lineHasInlineAtom,
+ });
+ };
+ block.nodesBetween(0, block.content.size, (node, pos) => {
+ if (node.type.name === 'hardBreak') {
+ lineEnd = pos;
+ flush();
+ lineText = '';
+ lineStart = pos + node.nodeSize;
+ lineEnd = lineStart;
+ lineHasInlineAtom = false;
+ } else if (node.isText) {
+ lineText += node.text ?? '';
+ lineEnd = pos + node.nodeSize;
+ } else {
+ lineText += '\uFFFC';
+ lineEnd = pos + node.nodeSize;
+ lineHasInlineAtom = true;
+ }
+ return false;
+ });
+ lineEnd = block.content.size;
+ flush();
+ const lineMatches = lines.map((line) => ({
+ line,
+ match: matchListPrefix(line.text),
+ }));
+ // ComposerListIndentDecoration switches the entire paragraph to its
+ // prefix-only fallback when any list row contains an atom or a recognized
+ // slash pill. In that mode even otherwise-plain sibling rows do not have a
+ // complete hanging wrapper, so their punctuation must remain available to
+ // this plugin as well.
+ const hasFallbackLine = lineMatches.some(({ line, match }) => {
+ if (!match) return false;
+ const overlapsSlashCommandPill = slashCommandMatches.some(
+ (slashMatch) =>
+ slashMatch.from < contentBase + line.end && slashMatch.to > contentBase + line.start,
+ );
+ const overlapsVoiceReplacement =
+ 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;
+ return (
+ line.hasInlineAtom ||
+ overlapsSlashCommandPill ||
+ (lines.length > 1 && (overlapsVoiceReplacement || hasCjkPunctuation))
+ );
+ });
+ lineMatches.forEach(({ line, match }) => {
+ if (!match) return;
+ const prefixFrom = contentBase + line.start;
+ const prefixTo = prefixFrom + match.prefixLength;
+ const body = line.text.slice(match.prefixLength);
+ // Prefix-only fallback slots and long-run marker boxes cannot overlap a
+ // per-character font span: ProseMirror would split the fixed-width box
+ // into duplicate fragments. Their tiny marker range opts into the CJK
+ // stack as one box; fallback bodies and node-wrapped single-line bodies
+ // retain character-scoped font spans and the normal UI/user font stack.
+ if (
+ hasFallbackLine ||
+ (lines.length === 1 &&
+ LONG_ALPHANUMERIC_BODY_RE.test(body) &&
+ !line.text.slice(0, match.prefixLength).includes('\t'))
+ ) {
+ ranges.push({ from: prefixFrom, to: prefixTo });
+ }
+ });
+ return false;
+ });
+ return ranges;
+}
+
/**
* 显式 CJK 字体栈。
*
@@ -78,8 +192,13 @@ const CJK_FONT_STACK =
* 用 descendants 遍历所有 text node, 对每个 text node 内的字符做正则匹配。
* 注意 from/to 是 doc-level position, 不是 text-node-local offset。
*/
-function buildDecorations(doc: PMNode): DecorationSet {
+function buildDecorations(
+ doc: PMNode,
+ slashCommandMatches: ReadonlyArray<Pick<SlashCommandMatch, 'from' | 'to'>> = [],
+ voiceReplacementRange: VoiceInputReplacementRange | null = null,
+): DecorationSet {
const decorations: Decoration[] = [];
+ const listRanges = listLineRanges(doc, slashCommandMatches, voiceReplacementRange);
doc.descendants((node, pos) => {
if (!node.isText || !node.text) return;
@@ -89,6 +208,13 @@ function buildDecorations(doc: PMNode): DecorationSet {
while ((m = CJK_PUNCT_REGEX.exec(text)) !== null) {
const from = pos + m.index;
const to = from + m[0].length;
+ if (listRanges.some((range) => from >= range.from && to <= range.to)) {
+ // ComposerListIndentDecoration owns the wrapping container for list
+ // rows. An overlapping inline font decoration would split that
+ // container at every punctuation boundary; list rows opt into the
+ // same CJK font stack through `.composer-list-cjk-font` instead.
+ continue;
+ }
decorations.push(
Decoration.inline(from, to, {
// inline style 的优先级比 .ProseMirror 的 css 规则高, 强制覆盖
@@ -110,16 +236,27 @@ export const CjkPunctDecoration = Extension.create({
key: PLUGIN_KEY,
state: {
init(_config, state: EditorState) {
- return buildDecorations(state.doc);
+ const roster = getSlashCommandRoster(state);
+ return buildDecorations(state.doc, findSlashCommandMatches(state.doc, roster));
},
- apply(tr: Transaction, old: DecorationSet) {
- // doc 没变 → decoration 位置不变, 直接复用
- if (!tr.docChanged) return old;
- // doc 变了 → 全量重算。
+ apply(tr: Transaction, old: DecorationSet, oldState: EditorState) {
+ const rosterUpdate = getSlashCommandRosterUpdate(tr);
+ const voiceReplacement = resolveVoiceInputReplacementRange(tr, oldState);
+ // doc、命令 roster 和 voice replacement 都没变 → decoration 位置不变,
+ // 直接复用;任一输入变化都需要重新扫描。
+ if (!tr.docChanged && rosterUpdate === undefined && !voiceReplacement.changed) {
+ return old;
+ }
+ // doc、命令 roster 或 voice replacement 变化 → 全量重算。
// 之前考虑过用 old.map(tr.mapping, tr.doc) 做增量, 但 chat input
// 文本量很小 (< 1KB 常见), 全量重扫成本可忽略, 而增量映射要额外
// 处理"变化范围内新增/删除的 CJK 标点", 代码复杂度上升不划算。
- return buildDecorations(tr.doc);
+ const roster = rosterUpdate ?? getSlashCommandRoster(oldState);
+ return buildDecorations(
+ tr.doc,
+ findSlashCommandMatches(tr.doc, roster),
+ voiceReplacement.range,
+ );
},
},
props: {
diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
index e2d1baf146..c5e6c47eb6 100644
--- a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts
@@ -4,11 +4,15 @@
*
* 行为:当某一"行"(段落内以 hardBreak 划分)以列表 / 待办 / 引用前缀开头
* (`1. ` / `- ` / `- [ ] ` / `> ` 等,与列表接续共用 matchListPrefix 判定),
- * 给整条列表行包一层 inline decoration span,并把前缀的估算宽度写入 CSS
- * 变量。CSS 将这条列表行作为独立的换行容器:首行用负 text-indent 把标记
- * 悬挂在左侧,自动换行后的续行则从正文起点开始。用户打完 `1. `(空格落下)
- * 那一刻缩进立即出现,即"已进入列表状态"的视觉信号;空项退出(前缀被删)
- * 时缩进同步消失。
+ * 单行段落使用 node decoration,hardBreak 分隔的多行段落按行使用 inline
+ * decoration;连续数字/字母正文使用 marker/body 两个盒子,避免长串把
+ * 列表标记单独挤到上一行。包含 inline atom/pill 的段落使用段落级 fallback
+ * 容器和每行前缀槽位,避免 inline decoration 在 atom 边界被拆成多个 block。
+ * 所有路径都把前缀的估算宽度写入 CSS 变量。
+ * CSS 将列表行作为独立的换行容器:首行用负 text-indent 把标记悬挂在左侧,
+ * 自动换行后的续行则从正文起点开始。用户打完 `1. `(空格落下)那一刻
+ * 缩进立即出现,即"已进入列表状态"的视觉信号;空项退出(前缀被删)时缩进
+ * 同步消失。
*
* 与 CjkPunctDecoration 相同的设计约束:
* - decoration 只是渲染层,doc JSON / 草稿存储 / 发送内容里没有任何痕迹;
@@ -29,13 +33,57 @@ import {
getSlashCommandRosterUpdate,
type SlashCommandMatch,
} from './SlashCommandDecoration';
+import {
+ resolveVoiceInputReplacementRange,
+ type VoiceInputReplacementRange,
+} from './VoiceInputDraftDecoration';
const PLUGIN_KEY = new PluginKey<DecorationSet>('composerListIndentDecoration');
+const TAB_SIZE = 8;
/** 行内一个非文本 inline 节点(mention chip 等)的占位符,与 applyListContinuation 一致。 */
const ATOM_PLACEHOLDER = '\uFFFC';
const CJK_PUNCTUATION_RE = /[\u3000-\u303f\uff00-\uffef]/;
-const LONG_ALPHANUMERIC_RUN_RE = /[A-Za-z0-9]{12,}/;
+// 只有正文整体是一个没有自然断点的数字/字母串时才拆成 marker/body。
+// 普通句子里偶然出现长 token 时,交给 overflow-wrap:anywhere,保留空格
+// 的自然断词行为,避免把整句变成逐字断行。
+const LONG_ALPHANUMERIC_BODY_RE = /^\s*[A-Za-z0-9]{12,}\s*$/;
+
+interface ListIndentValues {
+ ch: number;
+ em: number;
+}
+
+function listPrefixIndentValues(prefix: string): ListIndentValues {
+ let ch = 0;
+ let em = 0;
+ for (const char of prefix) {
+ if (char >= '0' && char <= '9') {
+ ch += 1;
+ } else if (char === '\t') {
+ ch += TAB_SIZE;
+ } else if (char === '、' || char === '\u3000') {
+ em += 1;
+ } else {
+ ch += 0.4;
+ }
+ }
+ return {
+ ch: Number(ch.toFixed(2)),
+ em: Number(em.toFixed(2)),
+ };
+}
+
+function listIndentValue({ ch, em }: ListIndentValues): string {
+ return em > 0 ? `calc(${ch}ch + ${em}em)` : `${ch}ch`;
+}
+
+function widestListIndentValue(values: ListIndentValues[]): string {
+ const candidates = [...new Set(values.map(listIndentValue))];
+ if (candidates.length === 0) return '0ch';
+ if (candidates.length === 1) return candidates[0]!;
+ return `max(${candidates.join(', ')})`;
+}
function addLongRunDecoration(
decorations: Decoration[],
@@ -43,15 +91,17 @@ function addLongRunDecoration(
to: number,
prefixLength: number,
prefix: string,
+ markerClass = '',
): void {
const prefixTo = from + prefixLength;
+ const markerClassSuffix = markerClass ? ` ${markerClass}` : '';
decorations.push(
Decoration.inline(from, prefixTo, {
- class: 'composer-list-long-run-marker',
+ class: `composer-list-long-run-marker${markerClassSuffix}`,
style: listPrefixIndentStyle(prefix),
}),
Decoration.inline(prefixTo, to, {
- class: 'composer-list-long-run-body composer-list-long-run-indent',
+ class: 'composer-list-long-run-body',
style: listPrefixIndentStyle(prefix),
}),
);
@@ -62,31 +112,14 @@ function addLongRunDecoration(
*
* ChatInput 已启用 tabular-nums,所以数字直接用 1ch;句点、空格、方括号等
* 窄字符按 0.4ch 估算;中文顿号按全角 1em。这里只生成数字和 CSS 单位,
- * 不会透传用户文本。含 Tab 的行由调用方跳过,因为比例字体下无法用 ch
- * 准确复现浏览器的 tab advance。
+ * 不会透传用户文本。Tab 先用固定 tab stop 做首帧回退,插件 view 在布局
+ * 完成后用 Range 实测并覆盖变量,避免比例字体下的 ch 近似误差。
*/
export function listPrefixIndentStyle(prefix: string): string {
- let ch = 0;
- let em = 0;
- for (const char of prefix) {
- if (char >= '0' && char <= '9') {
- ch += 1;
- } else if (char === '、' || char === '\u3000') {
- em += 1;
- } else {
- ch += 0.4;
- }
- }
- const chValue = Number(ch.toFixed(2));
- const emValue = Number(em.toFixed(2));
- const positive =
- emValue > 0 ? `calc(${chValue}ch + ${emValue}em)` : `${chValue}ch`;
- const negative =
- emValue > 0 ? `calc(-${chValue}ch - ${emValue}em)` : `-${chValue}ch`;
- return [
- `--composer-list-hang:${positive}`,
- `--composer-list-hang-negative:${negative}`,
- ]
+ const { ch, em } = listPrefixIndentValues(prefix);
+ const positive = listIndentValue({ ch, em });
+ const negative = em > 0 ? `calc(-${ch}ch - ${em}em)` : `-${ch}ch`;
+ return [`--composer-list-hang:${positive}`, `--composer-list-hang-negative:${negative}`]
.map((declaration) => `${declaration};`)
.join('');
}
@@ -98,6 +131,7 @@ export function listPrefixIndentStyle(prefix: string): string {
export function buildListIndentDecorations(
doc: PMNode,
slashCommandMatches: ReadonlyArray<Pick<SlashCommandMatch, 'from' | 'to'>> = [],
+ voiceReplacementRange: VoiceInputReplacementRange | null = null,
): DecorationSet {
const decorations: Decoration[] = [];
@@ -111,6 +145,7 @@ export function buildListIndentDecorations(
let lineStartOffset = 0;
let lineEndOffset = 0;
let lineHasInlineAtom = false;
+ const hardBreaks: number[] = [];
const lines: Array<{
text: string;
start: number;
@@ -130,6 +165,7 @@ export function buildListIndentDecorations(
// `pos` is the end of the current line in the textblock content.
lineEndOffset = pos;
flushLine();
+ hardBreaks.push(pos);
lineText = '';
lineStartOffset = pos + node.nodeSize;
lineEndOffset = lineStartOffset;
@@ -147,42 +183,102 @@ export function buildListIndentDecorations(
lineEndOffset = block.content.size;
flushLine(); // 段落最后一行
+ const lineMatches = lines.map((line) => ({
+ line,
+ match: matchListPrefix(line.text),
+ }));
+ const hasFallbackLine = lineMatches.some(({ line, match }) => {
+ if (!match) return false;
+ const overlapsSlashCommandPill = slashCommandMatches.some(
+ (slashMatch) =>
+ slashMatch.from < contentBase + line.end && slashMatch.to > contentBase + line.start,
+ );
+ const overlapsVoiceReplacement =
+ voiceReplacementRange !== null &&
+ voiceReplacementRange.from < contentBase + line.end &&
+ voiceReplacementRange.to > contentBase + line.start;
+ const hasCjkPunctuation = CJK_PUNCTUATION_RE.test(line.text);
+ return (
+ line.hasInlineAtom ||
+ overlapsSlashCommandPill ||
+ (lines.length > 1 && (overlapsVoiceReplacement || hasCjkPunctuation))
+ );
+ });
+ const fallbackPrefixes = lineMatches
+ .filter(({ match }) => Boolean(match))
+ .map(({ line, match }) => listPrefixIndentValues(line.text.slice(0, match!.prefixLength)));
+ const fallbackStyle = widestListIndentValue(fallbackPrefixes);
+
+ if (hasFallbackLine) {
+ decorations.push(
+ Decoration.node(blockPos, blockPos + block.nodeSize, {
+ class: 'composer-list-fallback-container',
+ style: `--composer-list-fallback-indent:${fallbackStyle};`,
+ }),
+ );
+ hardBreaks.forEach((breakPos) => {
+ decorations.push(
+ Decoration.node(contentBase + breakPos, contentBase + breakPos + 1, {
+ class: 'composer-list-fallback-break',
+ }),
+ );
+ });
+ }
+
const addLineDecoration = (line: (typeof lines)[number]) => {
const match = matchListPrefix(line.text);
- // Inline decorations apply their attributes to every covered inline node.
- // Mixed decoration ranges therefore use a prefix-only fallback below.
- if (!match || line.text.slice(0, match.prefixLength).includes('\t')) {
+ if (!match) {
+ if (hasFallbackLine && lines.length > 1 && line.end > line.start) {
+ decorations.push(
+ Decoration.inline(contentBase + line.start, contentBase + line.end, {
+ class: 'composer-list-fallback-unindented',
+ }),
+ );
+ }
return;
}
const from = contentBase + line.start;
const to = contentBase + line.end;
const prefix = line.text.slice(0, match.prefixLength);
const body = line.text.slice(match.prefixLength);
- const overlapsSlashCommandPill = slashCommandMatches.some(
- (slashMatch) => slashMatch.from < to && slashMatch.to > from,
- );
- const hasOverlappingInlineDecoration =
- line.hasInlineAtom ||
- CJK_PUNCTUATION_RE.test(body) ||
- overlapsSlashCommandPill;
- if (hasOverlappingInlineDecoration) {
- // Keep list-mode feedback without wrapping an inline decoration range.
- // Prefix-only styling cannot be split by CJK punctuation, slash-command
- // pills, or inline atoms, and is safer than producing multiple blocks.
+ const hasTabPrefix = prefix.includes('\t');
+ const prefixHasCjkPunctuation = CJK_PUNCTUATION_RE.test(prefix);
+ const lineClass = hasTabPrefix ? 'composer-list-tab-indent' : '';
+ if (hasFallbackLine) {
+ // The paragraph-level fallback supplies the available line width. The
+ // prefix gets a fixed slot (the widest marker in the paragraph), while
+ // atoms and slash pills remain ordinary inline content inside the same
+ // line flow. This avoids a width:100% wrapper being split at atom edges.
decorations.push(
Decoration.inline(from, from + match.prefixLength, {
- class: 'composer-list-prefix-indent',
+ class: [
+ 'composer-list-fallback-prefix',
+ hasTabPrefix ? 'composer-list-tab-indent' : '',
+ prefixHasCjkPunctuation ? 'composer-list-cjk-font' : '',
+ ]
+ .filter(Boolean)
+ .join(' '),
+ 'data-composer-list-prefix-length': String(match.prefixLength),
+ style: listPrefixIndentStyle(prefix),
}),
);
return;
}
- if (LONG_ALPHANUMERIC_RUN_RE.test(body)) {
- addLongRunDecoration(decorations, from, to, match.prefixLength, prefix);
+ if (LONG_ALPHANUMERIC_BODY_RE.test(body) && !hasTabPrefix) {
+ addLongRunDecoration(
+ decorations,
+ from,
+ to,
+ match.prefixLength,
+ prefix,
+ prefixHasCjkPunctuation ? 'composer-list-cjk-font' : '',
+ );
return;
}
decorations.push(
Decoration.inline(from, to, {
- class: 'composer-list-line-indent',
+ class: `composer-list-line-indent ${lineClass}`.trim(),
+ 'data-composer-list-prefix-length': String(match.prefixLength),
style: listPrefixIndentStyle(prefix),
}),
);
@@ -192,27 +288,49 @@ export function buildListIndentDecorations(
const [line] = lines;
const match = line && matchListPrefix(line.text);
const prefix = match ? line.text.slice(0, match.prefixLength) : '';
+ const body = line && match ? line.text.slice(match.prefixLength) : '';
+ const from = line ? contentBase + line.start : contentBase;
+ const to = line ? contentBase + line.end : contentBase;
+ const hasLongAlphanumericBody = LONG_ALPHANUMERIC_BODY_RE.test(body);
+ const prefixHasCjkPunctuation = CJK_PUNCTUATION_RE.test(prefix);
+ 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.
- if (
+ if (line && match && hasFallbackLine) {
+ decorations.push(
+ Decoration.inline(from, from + match.prefixLength, {
+ class: [
+ 'composer-list-fallback-prefix',
+ hasTabPrefix ? 'composer-list-tab-indent' : '',
+ prefixHasCjkPunctuation ? 'composer-list-cjk-font' : '',
+ ]
+ .filter(Boolean)
+ .join(' '),
+ 'data-composer-list-prefix-length': String(match.prefixLength),
+ style: listPrefixIndentStyle(prefix),
+ }),
+ );
+ } else if (
line &&
match &&
- !prefix.includes('\t') &&
!line.hasInlineAtom &&
- !LONG_ALPHANUMERIC_RUN_RE.test(line.text.slice(match.prefixLength))
+ (!hasLongAlphanumericBody || prefix.includes('\t'))
) {
decorations.push(
Decoration.node(blockPos, blockPos + block.nodeSize, {
- class: 'composer-list-block-indent',
+ class: ['composer-list-block-indent', hasTabPrefix ? 'composer-list-tab-indent' : '']
+ .filter(Boolean)
+ .join(' '),
+ 'data-composer-list-prefix-length': String(match.prefixLength),
style: listPrefixIndentStyle(prefix),
}),
);
} else if (
line &&
match &&
- !prefix.includes('\t') &&
!line.hasInlineAtom &&
- LONG_ALPHANUMERIC_RUN_RE.test(line.text.slice(match.prefixLength))
+ hasLongAlphanumericBody &&
+ !prefix.includes('\t')
) {
addLongRunDecoration(
decorations,
@@ -220,14 +338,23 @@ export function buildListIndentDecorations(
contentBase + line.end,
match.prefixLength,
prefix,
+ prefixHasCjkPunctuation ? 'composer-list-cjk-font' : '',
);
- } else if (line && match && !prefix.includes('\t')) {
+ } else if (line && match) {
decorations.push(
Decoration.inline(
contentBase + line.start,
contentBase + line.start + match.prefixLength,
{
- class: 'composer-list-prefix-indent',
+ class: prefix.includes('\t')
+ ? `composer-list-prefix-indent composer-list-tab-indent${
+ prefixHasCjkPunctuation ? ' composer-list-cjk-font' : ''
+ }`
+ : `composer-list-prefix-indent${
+ prefixHasCjkPunctuation ? ' composer-list-cjk-font' : ''
+ }`,
+ 'data-composer-list-prefix-length': String(match.prefixLength),
+ style: listPrefixIndentStyle(prefix),
},
),
);
@@ -257,17 +384,17 @@ export const ComposerListIndentDecoration = Extension.create({
findSlashCommandMatches(state.doc, roster),
);
},
- apply(
- tr: Transaction,
- old: DecorationSet,
- oldState: EditorState,
- ) {
+ apply(tr: Transaction, old: DecorationSet, oldState: EditorState) {
const rosterUpdate = getSlashCommandRosterUpdate(tr);
- if (!tr.docChanged && rosterUpdate === undefined) return old;
+ const voiceReplacement = resolveVoiceInputReplacementRange(tr, oldState);
+ if (!tr.docChanged && rosterUpdate === undefined && !voiceReplacement.changed) {
+ return old;
+ }
const roster = rosterUpdate ?? getSlashCommandRoster(oldState);
return buildListIndentDecorations(
tr.doc,
findSlashCommandMatches(tr.doc, roster),
+ voiceReplacement.range,
);
},
},
@@ -276,6 +403,74 @@ export const ComposerListIndentDecoration = Extension.create({
return this.getState(state) ?? DecorationSet.empty;
},
},
+ view() {
+ return {
+ update(view) {
+ const measurablePrefixes = view.dom.querySelectorAll<HTMLElement>(
+ '.composer-list-tab-indent, .composer-list-fallback-prefix',
+ );
+ const fallbackWidths = new Map<HTMLElement, number>();
+ measurablePrefixes.forEach((span) => {
+ const prefixLength = Number(span.dataset.composerListPrefixLength ?? Number.NaN);
+ if (!Number.isFinite(prefixLength) || prefixLength <= 0) return;
+ // Once Chromium measurement has replaced the deterministic
+ // fallback with pixels, the same span no longer needs a
+ // synchronous Range/layout read on every editor update.
+ const existingWidth = span.style.getPropertyValue('--composer-list-hang').trim();
+ let width = existingWidth.endsWith('px')
+ ? Number.parseFloat(existingWidth.slice(0, -2))
+ : Number.NaN;
+ if (!Number.isFinite(width)) {
+ const walker = document.createTreeWalker(span, NodeFilter.SHOW_TEXT);
+ let remaining = prefixLength;
+ let startNode: Text | null = null;
+ let endNode: Text | null = null;
+ let endOffset = 0;
+ while (remaining > 0) {
+ const node = walker.nextNode() as Text | null;
+ if (!node) break;
+ const length = node.data.length;
+ if (!startNode) startNode = node;
+ endNode = node;
+ if (length >= remaining) {
+ endOffset = remaining;
+ remaining = 0;
+ break;
+ }
+ remaining -= length;
+ }
+ if (!startNode || !endNode || remaining > 0) return;
+ const range = document.createRange();
+ range.setStart(startNode, 0);
+ range.setEnd(endNode, endOffset);
+ if (typeof range.getBoundingClientRect !== 'function') return;
+ width = range.getBoundingClientRect().width;
+ if (!Number.isFinite(width) || width <= 0) return;
+ span.style.setProperty('--composer-list-hang', `${width}px`);
+ span.style.setProperty('--composer-list-hang-negative', `-${width}px`);
+ }
+ const fallbackContainer = span.closest<HTMLElement>(
+ '.composer-list-fallback-container',
+ );
+ if (fallbackContainer) {
+ fallbackWidths.set(
+ fallbackContainer,
+ Math.max(fallbackWidths.get(fallbackContainer) ?? 0, width),
+ );
+ }
+ });
+ fallbackWidths.forEach((width, fallbackContainer) => {
+ const nextWidth = `${width}px`;
+ if (
+ fallbackContainer.style.getPropertyValue('--composer-list-fallback-indent') !==
+ nextWidth
+ ) {
+ fallbackContainer.style.setProperty('--composer-list-fallback-indent', nextWidth);
+ }
+ });
+ },
+ };
+ },
// 注:曾有一个 view().update 里 `if (view.composing) return` 的"IME 保护",
// 但重算发生在上面的 state.apply(只看 tr.docChanged),view.update 在视图更新
// 之后才跑、DecorationSet 早已算好,该钩子等价 no-op(greptile P2)——已删除。
diff --git a/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts b/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts
index be44b503dd..ef79721532 100644
--- a/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts
@@ -29,6 +29,16 @@ type VoiceInputDraftDecorationState = VoiceInputDraftMeta & {
const PLUGIN_KEY = new PluginKey<VoiceInputDraftDecorationState>('voiceInputDraftDecoration');
const META_KEY = 'voiceInputDraftDecoration';
+export type VoiceInputReplacementRange = {
+ from: number;
+ to: number;
+};
+
+export type VoiceInputReplacementRangeUpdate = {
+ changed: boolean;
+ range: VoiceInputReplacementRange | null;
+};
+
function clampPosition(doc: PMNode, position: number): number {
return Math.max(0, Math.min(position, doc.content.size));
}
@@ -39,6 +49,38 @@ function clampRange(doc: PMNode, from: number, to: number): { from: number; to:
return { from: safeFrom, to: safeTo };
}
+/**
+ * Resolve the replacement range that sibling decoration plugins should use
+ * for this transaction. The voice plugin is registered after the list/CJK
+ * plugins, so they cannot read its next state during their own `apply`; this
+ * helper deliberately reads the shared transaction meta and maps the previous
+ * range when only the document changed.
+ */
+export function resolveVoiceInputReplacementRange(
+ tr: Transaction,
+ oldState: EditorState,
+): VoiceInputReplacementRangeUpdate {
+ const meta = tr.getMeta(META_KEY) as VoiceInputDraftMeta | undefined;
+ if (meta) {
+ const range = clampRange(tr.doc, meta.from, meta.to);
+ return {
+ changed: true,
+ range: meta.text && range.to > range.from ? range : null,
+ };
+ }
+ const old = PLUGIN_KEY.getState(oldState);
+ if (!old?.text || old.to <= old.from) {
+ return { changed: false, range: null };
+ }
+ const range = tr.docChanged
+ ? clampRange(tr.doc, tr.mapping.map(old.from, -1), tr.mapping.map(old.to, 1))
+ : clampRange(tr.doc, old.from, old.to);
+ return {
+ changed: false,
+ range: range.to > range.from ? range : null,
+ };
+}
+
// Lucide `Loader2` arc. The arc rotates around the viewBox centre via CSS
// (`voice-caret-spin` on [data-voice-spinner-arc]) — NOT the whole <svg>.
// Rotating the inline svg element makes its swept bounding box bleed into the
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index b34a4a70d6..a731c4f824 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -361,7 +361,35 @@ html:lang(ko) {
.ProseMirror .composer-list-prefix-indent {
padding-left: 1em;
}
-.ProseMirror span.composer-list-line-indent {
+.ProseMirror .composer-list-fallback-container {
+ display: block;
+ box-sizing: border-box;
+ width: 100%;
+ padding-left: calc(1em + var(--composer-list-fallback-indent, 1.25em));
+ overflow-wrap: anywhere;
+}
+.ProseMirror .composer-list-fallback-prefix {
+ display: inline-block;
+ box-sizing: border-box;
+ width: calc(1em + var(--composer-list-fallback-indent, 1.25em));
+ margin-left: calc(-1em - var(--composer-list-fallback-indent, 1.25em));
+ white-space: nowrap;
+ vertical-align: top;
+}
+.ProseMirror .composer-list-fallback-unindented {
+ display: inline-block;
+ box-sizing: border-box;
+ width: calc(100% + 1em + var(--composer-list-fallback-indent, 1.25em));
+ margin-left: calc(-1em - var(--composer-list-fallback-indent, 1.25em));
+ vertical-align: top;
+ overflow-wrap: anywhere;
+}
+.ProseMirror .composer-list-fallback-break {
+ /* Keep native <br> line boxes so consecutive hard breaks retain intentional
+ blank lines inside a paragraph-level list fallback. */
+ display: inline;
+}
+.ProseMirror .composer-list-line-indent {
display: inline-block;
box-sizing: border-box;
width: 100%;
@@ -370,11 +398,19 @@ html:lang(ko) {
vertical-align: top;
overflow-wrap: anywhere;
}
-/* 只对没有自然断点的长数字/字母串启用强制断字。普通英文句子仍由
- overflow-wrap:anywhere 保持自然单词边界,避免全局 break-all 造成逐字竖排。 */
-.ProseMirror .composer-list-long-run-indent {
- word-break: break-all;
+.ProseMirror .composer-list-tab-indent {
+ /* Keep the fallback and the browser's tab advance deterministic until the
+ plugin view replaces the CSS variables with a measured Range width. */
+ tab-size: 8;
+}
+.ProseMirror .composer-list-cjk-font {
+ font-family:
+ 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei UI', 'Microsoft YaHei', 'Noto Sans CJK SC',
+ 'Source Han Sans SC', 'HarmonyOS Sans SC', sans-serif;
}
+/* 没有自然断点的长数字/字母串拆成 marker/body 两个相邻盒子。marker
+ 始终留在正文首行,body 独占剩余宽度;overflow-wrap:anywhere 仅在正文
+ 需要溢出时启用紧急断字,普通英文仍优先按空格换行。 */
.ProseMirror .composer-list-long-run-marker {
display: inline-block;
box-sizing: border-box;
@@ -390,12 +426,20 @@ html:lang(ko) {
width: calc(100% - 1em - var(--composer-list-hang, 1.25em));
max-width: calc(100% - 1em - var(--composer-list-hang, 1.25em));
overflow-wrap: anywhere;
+ /* 该盒子只由 LONG_ALPHANUMERIC_BODY_RE 生成,正文没有自然断点;
+ 因此可以安全地在串内断字,而不会影响普通英文句子的词边界。 */
word-break: break-all;
vertical-align: top;
}
.ProseMirror .voice-input-draft-replaced {
display: none;
}
+/* Long-run body boxes can overlap a voice replacement in single-line rows.
+ The general multiline list path switches to the paragraph fallback while a
+ replacement is active, so its full-width row wrapper is never fragmented. */
+.ProseMirror .composer-list-long-run-body.voice-input-draft-replaced {
+ display: none;
+}
.ProseMirror [data-voice-draft-inline] {
color: var(--chat-input-text);
opacity: 0.7;