Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(editor): the cursor position is not correct after pasting (#3960)

Gpound.liu71c7cf410cda
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useHighlight.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useHighlight.ts
index 4e49c75846..bbfd194a81 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useHighlight.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useHighlight.ts
@@ -158,9 +158,15 @@ export function useDocHight(editorId: string, sequenceNodes: (string | ISequence
rangesSet(refSelections);
}
// Switching between uppercase and lowercase will trigger a reflow, causing the cursor to be misplaced. Let's refresh the cursor position here.
- const selection = editor.getSelectionRanges();
+ const selections = editor.getSelectionRanges();
+ // After 'buildTextRuns' , the content changes, most of it is deleted, and the cursor position needs to be corrected
+ const maxOffset = cloneBody.dataStream.length - 2;
+ selections.forEach((selection) => {
+ selection.startOffset = Math.max(0, Math.min(selection.startOffset, maxOffset));
+ selection.endOffset = Math.max(0, Math.min(selection.endOffset, maxOffset));
+ });
const cloneData = { ...data, body: cloneBody };
- editor.setDocumentData(cloneData, selection);
+ editor.setDocumentData(cloneData, selections);
}, [editorId, sequenceNodes, colorMap]);
return ranges;
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
index c0912eaf73..fc6390cf38 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
@@ -142,10 +142,16 @@ export function useDocHight(editorId: string, sequenceNodes: (string | ISequence
rangesSet(refSelections);
}
// Switching between uppercase and lowercase will trigger a reflow, causing the cursor to be misplaced. Let's refresh the cursor position here.
- const selection = editor.getSelectionRanges();
+ const selections = editor.getSelectionRanges();
+ // After 'buildTextRuns' , the content changes, most of it is deleted, and the cursor position needs to be corrected
+ const maxOffset = cloneBody.dataStream.length - 2;
+ selections.forEach((selection) => {
+ selection.startOffset = Math.max(0, Math.min(selection.startOffset, maxOffset));
+ selection.endOffset = Math.max(0, Math.min(selection.endOffset, maxOffset));
+ });
const cloneData = { ...data, body: cloneBody };
- editor.setDocumentData(cloneData, selection);
+ editor.setDocumentData(cloneData, selections);
}, [editorId, sequenceNodes, colorMap]);
return ranges;