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): 新建对话页语音上屏文字前不再多一个空行(#736 续修) (#820)

Dashfa4044ba45ca
diff --git a/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts b/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts
index f4a734db4e..3482b677d9 100644
--- a/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts
@@ -38,4 +38,20 @@ describe('external draft notification empty-document handling', () => {
expect(block).toContain('tiptapDocHasContent(');
expect(block).not.toMatch(/const normalizedDraftText = draft\.text\s*\n?\s*\?/);
});
+
+ // 同一口径也必须覆盖 storageKey 对齐分支:它依赖 voiceInput.isBusy,录音开始与
+ // 结束各重跑一次。漏判空时新建对话页(草稿键固定、常留一份空正文)会在语音结束
+ // 时重建 doc,把插入点推到 block 边界 —— 上屏文字前多一个空行。
+ it('also collapses an empty draft document on the storageKey-aligned hydration path', () => {
+ const start = chatInput.indexOf('// First-mount hydration path');
+ expect(start).toBeGreaterThan(-1);
+ const end = chatInput.indexOf('editorStorageKeyRef.current = storageKey;', start);
+ expect(end).toBeGreaterThan(start);
+ const block = chatInput.slice(start, end);
+
+ expect(block).toContain('tiptapDocHasContent(draft.text)');
+ expect(block).toContain('composerDocIsEmpty(editor.state.doc)');
+ // 不能再直接拿 draft.text 当"有草稿"的判据。
+ expect(block).not.toMatch(/if \(draft\?\.text && composerDocIsEmpty/);
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputDraftDecoration.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputDraftDecoration.test.ts
index ed82588490..eeb163b4bb 100644
--- a/apps/desktop/src/renderer/__tests__/voiceInputDraftDecoration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/voiceInputDraftDecoration.test.ts
@@ -276,6 +276,31 @@ describe('voice input draft decoration anti-flicker contract', () => {
expect(rebuilt.doc.resolve(anchor!.from).parent.isTextblock).toBe(true);
});
+ // 全选(AllSelection)后开始听写:替换区间就是 0..content.size,两端必须原样保留,
+ // 否则外层节点(列表包装等)留在替换范围外、上屏文字塞进列表项而不是替换整篇。
+ // 但 widget 是 inline 的,渲染位置要单独吸附回段落内,不然又变成段落外的裸 span。
+ it('keeps a whole-document replacement range while rendering widgets inline', () => {
+ const { plugin, state } = makeState('已经上屏的文字');
+ const full = { from: 0, to: state.doc.content.size };
+ const listening = applyDraftMeta(state, {
+ text: '新的听写文字',
+ source: 'partial',
+ ...full,
+ caretState: 'listening',
+ });
+
+ expect(plugin.getState(listening)).toMatchObject(full);
+ const decorations = plugin.getState(listening)!.decorations.find();
+ const replaced = decorations.find(
+ (deco) => (deco.spec as { key?: string }).key === undefined,
+ );
+ expect({ from: replaced!.from, to: replaced!.to }).toEqual(full);
+ for (const deco of decorations.filter((d) => (d.spec as { key?: string }).key)) {
+ expect(deco.from).toBe(1);
+ expect(listening.doc.resolve(deco.from).parent.isTextblock).toBe(true);
+ }
+ });
+
it('deduplicates identical setVoiceInputDraftDecoration calls without dispatching', () => {
const { state } = makeState('前文');
let current = state;
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index c1c4b5d218..633d8d4558 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -2579,10 +2579,17 @@ export function ChatInput({
// alone.
if (storageKey !== undefined) {
const draft = getComposerDraft(storageKey);
- if (draft?.text && composerDocIsEmpty(editor.state.doc)) {
+ // 判空同外部草稿订阅:草稿正文可能是「空文档 JSON」而不是 undefined。此时
+ // 编辑器本来就是空的,setContent 只会原地重建 doc(replace(0, size)),把按
+ // 位置存活的状态(语音插入点、草稿装饰锚点)推到 block 边界上。本 effect 依赖
+ // voiceInput.isBusy,录音开始与结束各会重跑一次——新建对话页的草稿键固定、
+ // 常留着一份空正文,于是上屏文字前凭空多出一个空行。
+ const draftDocument =
+ draft?.text && tiptapDocHasContent(draft.text) ? draft.text : null;
+ if (draftDocument && composerDocIsEmpty(editor.state.doc)) {
isRestoringRef.current = true;
try {
- editor.commands.setContent(normalizeComposerDocumentJSON(draft.text));
+ editor.commands.setContent(normalizeComposerDocumentJSON(draftDocument));
} finally {
isRestoringRef.current = false;
}
diff --git a/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts b/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts
index 36e04e3832..808d588eed 100644
--- a/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts
+++ b/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts
@@ -1,15 +1,13 @@
import { Extension, type Editor } from '@tiptap/core';
-import {
- Plugin,
- PluginKey,
- TextSelection,
- type EditorState,
- type Transaction,
-} from '@tiptap/pm/state';
+import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import type { Node as PMNode } from '@tiptap/pm/model';
import type { VoiceInputDraftSource } from '@cindy/voice-input-core';
+import {
+ clampEditorTextRangeToDoc,
+ clampToInlinePosition,
+} from '../../voice-input/editorRangeMapping';
import { MIC_WAVE_ICON_SVG } from '../../voice-input/VoiceInputMicWaveIcon';
/**
@@ -45,33 +43,12 @@ export type VoiceInputReplacementRangeUpdate = {
range: VoiceInputReplacementRange | null;
};
-function clampPosition(doc: PMNode, position: number): number {
- return Math.max(0, Math.min(position, doc.content.size));
-}
-
-/**
- * Snap a position onto the nearest place that can hold inline content.
- *
- * The draft/caret widgets are inline: rendered at a position whose parent is
- * NOT a textblock (0 or a boundary between blocks), ProseMirror puts them in
- * the doc-level DOM — an inline span between two `<p>`s, which the browser then
- * gives its own line. That reads as a stray blank line above the dictation
- * caret. Anchors reach such a position whenever the composer document is
- * rebuilt wholesale while dictation is live (external draft restore does a
- * `replace(0, size)`), because mapping a collapsed anchor across a full
- * replacement pushes it out to the block boundary.
- */
-function clampToInlinePosition(doc: PMNode, position: number): number {
- const clamped = clampPosition(doc, position);
- const $pos = doc.resolve(clamped);
- if ($pos.parent.isTextblock) return clamped;
- return TextSelection.near($pos, 1).from;
-}
-
+// 折叠锚点吸附到「能承载 inline 内容」的位置(见 clampToInlinePosition):落在 block
+// 边界上时 ProseMirror 会把 inline widget 渲染到段落之外,浏览器给它单独一行 ——
+// 就是听写时凭空多出的那个空行。非折叠区间保留两端(全选后听写要替换整篇),widget
+// 的渲染位置在 createDecorations 里单独吸附。
function clampRange(doc: PMNode, from: number, to: number): { from: number; to: number } {
- const safeFrom = clampToInlinePosition(doc, Math.min(from, to));
- const safeTo = clampToInlinePosition(doc, Math.max(from, to));
- return safeFrom <= safeTo ? { from: safeFrom, to: safeTo } : { from: safeFrom, to: safeFrom };
+ return clampEditorTextRangeToDoc({ from, to }, doc);
}
/**
@@ -137,6 +114,12 @@ function createDecorations(
): DecorationSet {
if (!text && !caretState) return DecorationSet.empty;
const range = clampRange(doc, from, to);
+ // The replaced range keeps its own endpoints (a dictation started over
+ // AllSelection must still replace the whole document), but the inline widgets
+ // have to sit at a position that can hold inline content: at a block boundary
+ // ProseMirror renders them at doc level, where the browser gives the span its
+ // own line — a stray blank line above the caret.
+ const widgetPosition = clampToInlinePosition(doc, range.from);
const decorations: Decoration[] = [];
if (text && range.to > range.from) {
decorations.push(
@@ -155,7 +138,7 @@ function createDecorations(
// browser only repaints the glyphs that actually changed.
decorations.push(
Decoration.widget(
- range.from,
+ widgetPosition,
() => {
const node = document.createElement('span');
node.dataset.voiceDraftInline = 'true';
@@ -164,7 +147,7 @@ function createDecorations(
return node;
},
{
- key: `voice-input-draft:${range.from}:${range.to}`,
+ key: `voice-input-draft:${widgetPosition}:${range.to}`,
side: 1,
},
),
@@ -178,10 +161,10 @@ function createDecorations(
// the next text will land.
decorations.push(
Decoration.widget(
- range.from,
+ widgetPosition,
() => createCaretElement(caretState),
{
- key: `voice-input-caret:${caretState}:${range.from}`,
+ key: `voice-input-caret:${caretState}:${widgetPosition}`,
side: 2,
},
),
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/editorRangeMapping.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/editorRangeMapping.test.ts
index 92886d8a5c..6076c0fdec 100644
--- a/apps/desktop/src/renderer/voice-input/__tests__/editorRangeMapping.test.ts
+++ b/apps/desktop/src/renderer/voice-input/__tests__/editorRangeMapping.test.ts
@@ -13,7 +13,11 @@ import { describe, expect, it } from 'vitest';
import { Schema } from '@tiptap/pm/model';
import { EditorState } from '@tiptap/pm/state';
-import { mapEditorTextRange } from '../editorRangeMapping';
+import {
+ clampEditorTextRangeToDoc,
+ mapEditorTextRange,
+ resolveInsertedTextRange,
+} from '../editorRangeMapping';
const schema = new Schema({
nodes: {
@@ -72,4 +76,87 @@ describe('mapEditorTextRange', () => {
expect(mapped).toEqual({ from: 9, to: 14 });
expect(state.tr.insertText('XY', 1).doc.textBetween(mapped!.from, mapped!.to)).toBe('world');
});
+
+ // 整篇替换(外部草稿恢复走 setContent → replace(0, size))会把锚点映射到 block
+ // 边界。那不是听写能插入的位置:insertText 会另起一个段落,上屏文字前面凭空多出
+ // 一个空行(新建对话页语音结束时多一个回车的成因)。映射结果必须吸附回段落内。
+ it('snaps an anchor back inside the paragraph after a full-document replacement', () => {
+ const state = stateWith('');
+ const tr = state.tr.replaceWith(0, state.doc.content.size, schema.node('paragraph'));
+ const mapped = mapEditorTextRange({ from: 1, to: 1 }, tr);
+
+ expect(mapped).toEqual({ from: 1, to: 1 });
+ expect(tr.doc.resolve(mapped!.from).parent.isTextblock).toBe(true);
+ // 用映射后的位置上屏时不得再生成第二个段落。
+ const inserted = tr.doc.type.schema === schema
+ ? EditorState.create({ doc: tr.doc }).tr.insertText('上屏文字', mapped!.from, mapped!.to).doc
+ : null;
+ expect(inserted?.childCount).toBe(1);
+ expect(inserted?.textContent).toBe('上屏文字');
+ });
+});
+
+describe('clampEditorTextRangeToDoc', () => {
+ it('pulls block-boundary positions onto the nearest inline position', () => {
+ const doc = stateWith('hi').doc;
+ // 0 是 doc 起点、doc.content.size 是段落之后 —— 两者都不是 inline 位置。
+ expect(clampEditorTextRangeToDoc({ from: 0, to: 0 }, doc)).toEqual({ from: 1, to: 1 });
+ expect(clampEditorTextRangeToDoc({ from: doc.content.size, to: doc.content.size }, doc)).toEqual({
+ from: 3,
+ to: 3,
+ });
+ });
+
+ it('clamps out-of-bounds offsets and normalizes inverted ranges', () => {
+ const doc = stateWith('hi').doc;
+ expect(clampEditorTextRangeToDoc({ from: 999, to: 999 }, doc)).toEqual({ from: 3, to: 3 });
+ expect(clampEditorTextRangeToDoc({ from: 3, to: 1 }, doc)).toEqual({ from: 1, to: 3 });
+ });
+
+ // 只有折叠锚点该被吸附。非折叠区间的两端是"要替换什么"的一部分:全选(AllSelection)
+ // 后开始听写,区间就是 0..content.size;把两端往里收会把外层节点(列表包装等)留在
+ // 替换范围外,上屏文字于是塞进第一个列表项,而不是替换整篇。
+ it('preserves the endpoints of a non-collapsed (AllSelection) range', () => {
+ const doc = stateWith('hello').doc;
+ expect(clampEditorTextRangeToDoc({ from: 0, to: doc.content.size }, doc)).toEqual({
+ from: 0,
+ to: doc.content.size,
+ });
+ });
+
+ it('keeps a mapped non-collapsed range spanning the whole document', () => {
+ const state = stateWith('hello');
+ const size = state.doc.content.size;
+ // 无关的 doc 变更(此处在区间内插入)不该让整篇替换范围被收进段落内。
+ const tr = state.tr.insertText('X', 3);
+ const mapped = mapEditorTextRange({ from: 0, to: size }, tr);
+
+ expect(mapped!.from).toBe(0);
+ expect(mapped!.to).toBe(tr.doc.content.size);
+ });
+});
+
+// 上屏范围必须从事务推导:替换区间可以从 block 边界开始(全选后听写就是
+// 0..content.size),ProseMirror 把 inline 文本 fit 进段落后字形落在边界之后。用插入
+// 前的 from 记录会让润色回填读到截断文本而丢弃润色,预览与词典学习 watch 也一起错位。
+describe('resolveInsertedTextRange', () => {
+ it('reports where the text landed after a whole-document replacement', () => {
+ const state = stateWith('旧的内容');
+ const to = state.doc.content.size;
+ const tr = state.tr.insertText('上屏文字', 0, to);
+ const range = resolveInsertedTextRange(tr, 0, '上屏文字'.length);
+
+ expect(tr.doc.childCount).toBe(1);
+ expect(range).toEqual({ start: 1, end: 1 + '上屏文字'.length });
+ expect(tr.doc.textBetween(range.start, range.end)).toBe('上屏文字');
+ });
+
+ it('reports the inserted span for an ordinary collapsed insertion', () => {
+ const state = stateWith('abc');
+ const tr = state.tr.insertText('XY', 2, 2);
+ const range = resolveInsertedTextRange(tr, 2, 2);
+
+ expect(range).toEqual({ start: 2, end: 4 });
+ expect(tr.doc.textBetween(range.start, range.end)).toBe('XY');
+ });
});
diff --git a/apps/desktop/src/renderer/voice-input/editorRangeMapping.ts b/apps/desktop/src/renderer/voice-input/editorRangeMapping.ts
index 74657d8904..57bd7be4c0 100644
--- a/apps/desktop/src/renderer/voice-input/editorRangeMapping.ts
+++ b/apps/desktop/src/renderer/voice-input/editorRangeMapping.ts
@@ -1,10 +1,82 @@
-import type { Transaction } from '@tiptap/pm/state';
+import type { Node as PMNode } from '@tiptap/pm/model';
+import { TextSelection, type Transaction } from '@tiptap/pm/state';
export type EditorTextRange = {
from: number;
to: number;
};
+/**
+ * Snap a position onto the nearest place that can hold inline content.
+ *
+ * Dictation positions must always address inline content: the transcript is
+ * inserted with `tr.insertText`, and the live draft/caret decorations are inline
+ * widgets. A position whose parent is NOT a textblock (0, or a boundary between
+ * two blocks) makes ProseMirror wrap the inserted text in a NEW paragraph — the
+ * transcript then lands one line below, leaving an empty paragraph in front of
+ * it — and renders the widgets at doc level, where the browser gives them their
+ * own line. Both read as "dictation added a stray blank line".
+ *
+ * Anchors reach such a position whenever the composer document is rebuilt
+ * wholesale while dictation is live (an external draft restore replaces the full
+ * document), because mapping an anchor across a full replacement pushes it out
+ * to the block boundary. Clamping to `doc.content.size` alone does not help:
+ * that upper bound is itself a block boundary.
+ */
+export function clampToInlinePosition(doc: PMNode, position: number): number {
+ const clamped = Math.max(0, Math.min(position, doc.content.size));
+ const $pos = doc.resolve(clamped);
+ if ($pos.parent.isTextblock) return clamped;
+ return TextSelection.near($pos, 1).from;
+}
+
+/**
+ * Clamp a stored range into valid, ordered positions of `doc`.
+ *
+ * Only a COLLAPSED anchor is snapped onto an inline position. A non-collapsed
+ * range carries replacement semantics that the endpoints are part of: dictation
+ * started over `AllSelection` (Ctrl/Cmd+A) spans `0..doc.content.size`, and
+ * snapping those endpoints inward would leave the outer nodes — a bullet/ordered
+ * list wrapper, say — outside the replacement, so the transcript would land
+ * inside the first list item instead of replacing the whole composer. Such a
+ * range is only bounds-checked.
+ */
+export function clampEditorTextRangeToDoc(range: EditorTextRange, doc: PMNode): EditorTextRange {
+ const lower = Math.max(0, Math.min(Math.min(range.from, range.to), doc.content.size));
+ const upper = Math.max(0, Math.min(Math.max(range.from, range.to), doc.content.size));
+ if (lower !== upper) return { from: lower, to: upper };
+ const snapped = clampToInlinePosition(doc, lower);
+ return { from: snapped, to: snapped };
+}
+
+/**
+ * Where the text an `insertText(text, from, to)` transaction just wrote ended up.
+ *
+ * The pre-insertion `from` is NOT that place. A replacement range may legally
+ * start at a block boundary (dictation over `AllSelection` spans
+ * `0..doc.content.size`), and ProseMirror then fits the inline text INTO a
+ * textblock — the glyphs land one position after that boundary. Recording the
+ * pre-insertion endpoint would offset everything keyed to this range:
+ * `applyRefinedText` would read a truncated `currentText` and drop the
+ * refinement, and refinement previews plus dictionary-learning watches would
+ * point at the wrong span.
+ *
+ * Mapping the range's START with association `-1` keeps it in front of the
+ * inserted slice; snapping that onto an inline position lands exactly on the
+ * first inserted character, however the slice was fitted.
+ */
+export function resolveInsertedTextRange(
+ transaction: Transaction,
+ replacedFrom: number,
+ textLength: number,
+): { start: number; end: number } {
+ const start = clampToInlinePosition(
+ transaction.doc,
+ transaction.mapping.map(replacedFrom, -1),
+ );
+ return { start, end: Math.min(start + textLength, transaction.doc.content.size) };
+}
+
/**
* Move a stored range through a document change, so offsets captured earlier
* keep pointing at the same content.
@@ -17,6 +89,11 @@ export type EditorTextRange = {
* inverted; keep it collapsed after the insertion rather than letting a
* downstream min/max clamp swap it back into a range spanning that text.
*
+ * A mapped COLLAPSED anchor is snapped back onto an inline position: a
+ * full-document replacement maps it out to a block boundary, which is not a
+ * place dictation may insert at (see `clampToInlinePosition`). Non-collapsed
+ * ranges keep their endpoints — see `clampEditorTextRangeToDoc`.
+ *
* Lives in its own module so it can be tested without pulling in the voice
* input hook and its Electron bridge.
*/
@@ -27,5 +104,5 @@ export function mapEditorTextRange(
if (!range) return null;
const from = transaction.mapping.map(range.from, 1);
const to = transaction.mapping.map(range.to, -1);
- return from > to ? { from, to: from } : { from, to };
+ return clampEditorTextRangeToDoc(from > to ? { from, to: from } : { from, to }, transaction.doc);
}
diff --git a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
index 29c8c764fa..b28b8771ad 100644
--- a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
+++ b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { Editor } from '@tiptap/core';
+import type { Node as PMNode } from '@tiptap/pm/model';
import type { Transaction } from '@tiptap/pm/state';
import { useTranslation } from 'react-i18next';
import type {
@@ -59,7 +60,12 @@ import { resolveVoiceInputStartGuards } from './startGuards';
import { getVoiceInputWorkletUrl } from './workletUrl';
import { buildRefinementPreviewText } from './refinementPreviewText';
import { isVoiceInputEventScopeActive, shouldHandleVoiceInputEvent } from './eventScope';
-import { mapEditorTextRange, type EditorTextRange } from './editorRangeMapping';
+import {
+ clampEditorTextRangeToDoc,
+ mapEditorTextRange,
+ resolveInsertedTextRange,
+ type EditorTextRange,
+} from './editorRangeMapping';
import { isVoiceInputServiceConnectionError, VOICE_INPUT_ERROR_CODE_KEYS } from './overlayErrors';
import {
VOICE_INPUT_DICTIONARY_LEARNING_TRACK_TIMEOUT_MS,
@@ -530,11 +536,12 @@ export function useVoiceInput(
};
}, []);
- const clampEditorTextRange = useCallback((range: EditorTextRange, docSize: number): EditorTextRange => {
- const from = Math.max(0, Math.min(Math.min(range.from, range.to), docSize));
- const to = Math.max(0, Math.min(Math.max(range.from, range.to), docSize));
- return { from, to };
- }, []);
+ // 钳制到「能承载 inline 内容」的位置,而不是只钳到 doc.content.size:后者本身就是
+ // 一个 block 边界,在那里 insertText 会另起一个段落,上屏文字前凭空多一个空行。
+ const clampEditorTextRange = useCallback(
+ (range: EditorTextRange, doc: PMNode): EditorTextRange => clampEditorTextRangeToDoc(range, doc),
+ [],
+ );
const clearDictionaryLearningWatchTimer = useCallback((watch: DictionaryLearningWatch | undefined) => {
if (watch?.pendingAdviceTimer !== undefined) {
@@ -611,7 +618,7 @@ export function useVoiceInput(
const { doc } = current.state;
const range = clampEditorTextRange(
{ from: currentWatch.start, to: currentWatch.end },
- doc.content.size,
+ doc,
);
const afterText = doc.textBetween(range.from, range.to, '\n', '\n');
if (!afterText || afterText === currentWatch.baselineText) {
@@ -677,7 +684,7 @@ export function useVoiceInput(
.flatMap((watch) => {
const start = transaction.mapping.map(watch.start, -1);
const end = transaction.mapping.map(watch.end, -1);
- const range = clampEditorTextRange({ from: start, to: end }, transaction.doc.content.size);
+ const range = clampEditorTextRange({ from: start, to: end }, transaction.doc);
const currentText = transaction.doc.textBetween(range.from, range.to, '\n', '\n');
if (!currentText) {
finalizeDictionaryLearningWatch(watch.segmentId, 'clear_input_box');
@@ -762,7 +769,7 @@ export function useVoiceInput(
const { doc, selection } = current.state;
const range = clampEditorTextRange(
insertionRangeRef.current ?? { from: selection.from, to: selection.to },
- doc.content.size,
+ doc,
);
return {
...baseContext,
@@ -808,20 +815,22 @@ export function useVoiceInput(
current.commands.focus();
const { state, dispatch } = current.view;
const range = insertionRangeRef.current
- ? clampEditorTextRange(insertionRangeRef.current, state.doc.content.size)
+ ? clampEditorTextRange(insertionRangeRef.current, state.doc)
: { from: state.selection.from, to: state.selection.to };
insertionRangeRef.current = null;
- const start = range.from;
applyingVoiceTextRef.current = true;
try {
- dispatch(state.tr.insertText(text, range.from, range.to));
+ const transaction = state.tr.insertText(text, range.from, range.to);
+ // 上屏范围必须从事务推导,不能用插入前的 from:替换区间可以合法地从 block
+ // 边界开始(全选后听写就是 0..content.size),ProseMirror 会把 inline 文本
+ // fit 进段落,字形实际落在边界之后。用旧 from 记录会让润色回填、润色预览与
+ // 词典学习 watch 整体错位(润色会因读到截断文本而被丢弃)。
+ const inserted = resolveInsertedTextRange(transaction, range.from, text.length);
+ dispatch(transaction);
+ return inserted;
} finally {
applyingVoiceTextRef.current = false;
}
- return {
- start,
- end: start + text.length,
- };
}, [clampEditorTextRange]);
const applyRefinedText = useCallback((event: Extract<VoiceInputRendererEvent, { type: 'refined' }>): boolean => {
@@ -995,10 +1004,13 @@ export function useVoiceInput(
const range = segmentId ? submittedRangesRef.current.get(segmentId) : undefined;
const current = editorRef.current;
if (range && current && !current.isDestroyed) {
- const docSize = current.state.doc.content.size;
- if (range.start <= docSize) {
+ const currentDoc = current.state.doc;
+ if (range.start <= currentDoc.content.size) {
const baseText = event.segment.basedOnText ?? range.submittedText;
- draftDisplayRangeRef.current = clampEditorTextRange({ from: range.start, to: range.end }, docSize);
+ draftDisplayRangeRef.current = clampEditorTextRange(
+ { from: range.start, to: range.end },
+ currentDoc,
+ );
setDraftText(buildRefinementPreviewText(baseText, event.text));
setDraftSource('refinement');
}