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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(sheets-formula-ui): selecion error on formula-editor (#4632)
zhangw1f961b8a82f8
diff --git a/examples/src/sheets-multi/main.tsx b/examples/src/sheets-multi/main.tsxindex 0b9a759991..6d7ba2408e 100644--- a/examples/src/sheets-multi/main.tsx+++ b/examples/src/sheets-multi/main.tsx@@ -24,6 +24,7 @@ import { UniverRenderEnginePlugin } from '@univerjs/engine-render';import { DEFAULT_WORKBOOK_DATA_DEMO } from '@univerjs/mockdata';import { UniverSheetsPlugin } from '@univerjs/sheets';import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';+import { UniverSheetsFormulaUIPlugin } from '@univerjs/sheets-formula-ui';import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';import { UniverSheetsNumfmtUIPlugin } from '@univerjs/sheets-numfmt-ui';import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';@@ -62,14 +63,15 @@ function factory(id: string) {// sheets pluginuniver.registerPlugin(UniverSheetsPlugin);univer.registerPlugin(UniverSheetsUIPlugin);-+ univer.registerPlugin(UniverSheetsFormulaUIPlugin);// sheet feature pluginsuniver.registerPlugin(UniverSheetsNumfmtPlugin);univer.registerPlugin(UniverSheetsNumfmtUIPlugin);univer.registerPlugin(UniverSheetsFormulaPlugin);+ const data = Tools.deepClone(DEFAULT_WORKBOOK_DATA_DEMO);// create univer sheet instance- univer.createUnit(UniverInstanceType.UNIVER_SHEET, Tools.deepClone(DEFAULT_WORKBOOK_DATA_DEMO));+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, data);};}diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-selection.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-selection.tsindex 83704eb3df..73ce17b4e8 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-selection.ts+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-selection.ts@@ -24,6 +24,7 @@ import { useDependency, useEvent } from '@univerjs/ui';import { useEffect, useRef, useState } from 'react';import { filter, map } from 'rxjs';import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';+import { useStateRef } from './use-state-ref';function getCurrentBodyDataStreamAndOffset(accssor: IAccessor) {const univerInstanceService = accssor.get(IUniverInstanceService);@@ -54,14 +55,14 @@ export function useFormulaSelecting(opts: { editorId: string; isFocus: boolean;const [isSelecting, innerSetIsSelecting] = useState<FormulaSelectingType>(FormulaSelectingType.NOT_SELECT);const lexerTreeBuilder = useDependency(LexerTreeBuilder);const isDisabledByPointer = useRef(true);- const isSelectingRef = useRef(isSelecting);- isSelectingRef.current = isSelecting;const refSelectionsRenderService = sheetRenderer?.with(RefSelectionsRenderService);+ const isSelectingRef = useStateRef(isSelecting);const setIsSelecting = useEvent((v: FormulaSelectingType) => {if (refSelectionsRenderService) {refSelectionsRenderService.setSkipLastEnabled(v === FormulaSelectingType.NEED_ADD);}+ isSelectingRef.current = v;innerSetIsSelecting(v);});@@ -102,14 +103,14 @@ export function useFormulaSelecting(opts: { editorId: string; isFocus: boolean;});return () => sub.unsubscribe();- }, [docSelectionManagerService.textSelection$, docSelectionRenderService, editorId, injector, lexerTreeBuilder]);+ }, [docSelectionManagerService.textSelection$, docSelectionRenderService, editorId, injector, lexerTreeBuilder, setIsSelecting]);useEffect(() => {if (!isFocus) {setIsSelecting(FormulaSelectingType.NOT_SELECT);isDisabledByPointer.current = true;}- }, [isFocus]);+ }, [isFocus, setIsSelecting]);useEffect(() => {if (!disableOnClick) return;@@ -119,7 +120,7 @@ export function useFormulaSelecting(opts: { editorId: string; isFocus: boolean;});return () => sub?.unsubscribe();- }, [disableOnClick, renderer?.mainComponent?.onPointerDown$]);+ }, [disableOnClick, renderer?.mainComponent?.onPointerDown$, setIsSelecting]);- return { isSelecting };+ return { isSelecting, isSelectingRef };}diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.tsindex 034dc61c5a..81ecd6bd02 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts@@ -16,38 +16,57 @@/* eslint-disable max-lines-per-function */-import type { Workbook } from '@univerjs/core';+import type { IRange, Workbook } from '@univerjs/core';import type { Editor } from '@univerjs/docs-ui';import type { ISelectionWithCoord, ISetSelectionsOperationParams } from '@univerjs/sheets';+import type { RefObject } from 'react';import type { IRefSelection } from '../../range-selector/hooks/use-highlight';-import type { INode } from '../../range-selector/utils/filter-reference-node';import { DisposableCollection, ICommandService, IUniverInstanceService, ThemeService } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';-import { deserializeRangeWithSheet, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';+import { deserializeRangeWithSheet, LexerTreeBuilder, sequenceNodeType } from '@univerjs/engine-formula';import { IRenderManagerService } from '@univerjs/engine-render';import { IRefSelectionsService, SetSelectionsOperation } from '@univerjs/sheets';import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { useDependency, useEvent, useObservable } from '@univerjs/ui';-import { useEffect, useMemo, useRef } from 'react';+import { useEffect, useMemo } from 'react';import { merge } from 'rxjs';-import { debounceTime, distinctUntilChanged, map } from 'rxjs/operators';+import { debounceTime } from 'rxjs/operators';import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';import { calcHighlightRanges } from '../../range-selector/hooks/use-highlight';-import { findIndexFromSequenceNodes } from '../../range-selector/utils/find-index-from-sequence-nodes';+import { findIndexFromSequenceNodes, findRefSequenceIndex } from '../../range-selector/utils/find-index-from-sequence-nodes';import { getOffsetFromSequenceNodes } from '../../range-selector/utils/get-offset-from-sequence-nodes';import { sequenceNodeToText } from '../../range-selector/utils/sequence-node-to-text';import { unitRangesToText } from '../../range-selector/utils/unit-ranges-to-text';import { useStateRef } from '../hooks/use-state-ref';import { FormulaSelectingType } from './use-formula-selection';+const prepareSelectionChangeContext = (opts: { editor?: Editor; lexerTreeBuilder: LexerTreeBuilder }) => {+ const { editor, lexerTreeBuilder } = opts;+ const currentDocSelections = editor?.getSelectionRanges();+ if (currentDocSelections?.length !== 1) {+ return;+ }+ const docRange = currentDocSelections[0];+ const offset = docRange.startOffset - 1;+ const dataStream = (editor?.getDocumentData().body?.dataStream ?? '\r\n').slice(0, -2);+ const sequenceNodes = lexerTreeBuilder.sequenceNodesBuilder(dataStream.slice(1)) ?? [];+ const nodeIndex = findIndexFromSequenceNodes(sequenceNodes, offset, false);+ const updatingRefIndex = findRefSequenceIndex(sequenceNodes, nodeIndex);+ return {+ nodeIndex,+ updatingRefIndex,+ sequenceNodes,+ offset,+ };+};+const noop = (() => { }) as any;export const useSheetSelectionChange = (isNeed: boolean,isFocus: boolean,- isSelecting: FormulaSelectingType,+ isSelectingRef: RefObject<FormulaSelectingType>,unitId: string,subUnitId: string,- sequenceNodes: INode[],refSelectionRef: React.MutableRefObject<IRefSelection[]>,isSupportAcrossSheet: boolean,listenSelectionSet: boolean,@@ -57,9 +76,9 @@ export const useSheetSelectionChange = (const renderManagerService = useDependency(IRenderManagerService);const univerInstanceService = useDependency(IUniverInstanceService);const commandService = useDependency(ICommandService);- const sequenceNodesRef = useStateRef(sequenceNodes);const docSelectionManagerService = useDependency(DocSelectionManagerService);const themeService = useDependency(ThemeService);+ const lexerTreeBuilder = useDependency(LexerTreeBuilder);const workbook = univerInstanceService.getUnit<Workbook>(unitId);const getSheetNameById = useEvent((sheetId: string) => workbook?.getSheetBySheetId(sheetId)?.getName() ?? '');@@ -70,132 +89,131 @@ export const useSheetSelectionChange = (const refSelectionsRenderService = render?.with(RefSelectionsRenderService);const sheetSkeletonManagerService = render?.with(SheetSkeletonManagerService);const refSelectionsService = useDependency(IRefSelectionsService);- const isScalingRef = useRef(false);- const isSelectingRef = useRef(isSelecting);- isSelectingRef.current = isSelecting;- const scalingOptionRef = useRef<{ result: string; offset: number }>(undefined);+ // eslint-disable-next-line complexity+ const onSelectionsChange = useEvent((selections: IRange[], isEnd: boolean) => {+ const ctx = prepareSelectionChangeContext({ editor, lexerTreeBuilder });+ if (!ctx) return;+ const { nodeIndex, updatingRefIndex, sequenceNodes, offset } = ctx;+ if (isSelectingRef.current === FormulaSelectingType.NEED_ADD) {+ if (offset !== 0) {+ if (nodeIndex === -1 && sequenceNodes.length) {+ return;+ }+ const range = selections[selections.length - 1];+ const lastNodes = sequenceNodes.splice(nodeIndex + 1);+ const rangeSheetId = range.sheetId ?? subUnitId;+ const unitRangeName = {+ range,+ unitId: range.unitId ?? unitId,+ sheetName: getSheetNameById(rangeSheetId),+ };+ const isAcrossSheet = rangeSheetId !== subUnitId;+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && isAcrossSheet, sheetName);+ sequenceNodes.push({ token: refRanges[0], nodeType: sequenceNodeType.REFERENCE } as any);+ const newSequenceNodes = [...sequenceNodes, ...lastNodes];+ const result = sequenceNodeToText(newSequenceNodes);+ handleRangeChange(result, getOffsetFromSequenceNodes(sequenceNodes), isEnd);+ } else {+ const range = selections[selections.length - 1];+ const rangeSheetId = range.sheetId ?? subUnitId;+ const unitRangeName = {+ range,+ unitId: range.unitId ?? unitId,+ sheetName: getSheetNameById(rangeSheetId),+ };+ const isAcrossSheet = rangeSheetId !== subUnitId;+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && isAcrossSheet);+ sequenceNodes.unshift({ token: refRanges[0], nodeType: sequenceNodeType.REFERENCE } as any);+ const result = sequenceNodeToText(sequenceNodes);+ handleRangeChange(result, refRanges[0].length, isEnd);+ }+ } else {+ const orderedSelections = [...selections];+ if (updatingRefIndex !== -1) {+ const last = orderedSelections.pop();+ last && orderedSelections.splice(updatingRefIndex, 0, last);+ }+ // 更新全部的 ref Selection+ let currentRefIndex = 0;+ const newTokens = sequenceNodes.map((item) => {+ if (typeof item === 'string') {+ return item;+ }+ if (item.nodeType === sequenceNodeType.REFERENCE) {+ const nodeRange = deserializeRangeWithSheet(item.token);+ if (!nodeRange.sheetName) {+ nodeRange.sheetName = sheetName;+ }++ if (isSupportAcrossSheet) {+ // 直接跳过非当前表的 node 节点+ if (contextRef.current.activeSheet?.getName() !== nodeRange.sheetName) {+ return item.token;+ }+ }+ const selection = orderedSelections[currentRefIndex];+ currentRefIndex++;+ if (!selection) {+ return '';+ }+ const rangeSheetId = selection.sheetId ?? subUnitId;+ const unitRangeName = {+ range: selection,+ unitId: selection.unitId ?? unitId,+ sheetName: getSheetNameById(rangeSheetId),+ };+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet, sheetName);+ return refRanges[0];+ }+ return item.token;+ });++ let currentText = '';+ let newOffset;+ newTokens.forEach((item, index) => {+ currentText += item;+ if (index === nodeIndex) {+ newOffset = currentText.length;+ }+ });+ const theLastList: string[] = [];+ for (let index = currentRefIndex; index <= selections.length - 1; index++) {+ const selection = selections[index];+ const rangeSheetId = selection.sheetId ?? subUnitId;+ const unitRangeName = {+ range: selection,+ unitId: selection.unitId ?? unitId,+ sheetName: getSheetNameById(rangeSheetId),+ };+ const isAcrossSheet = rangeSheetId !== subUnitId;+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && isAcrossSheet, sheetName);+ theLastList.push(refRanges[0]);+ }+ const preNode = sequenceNodes[sequenceNodes.length - 1];+ const isPreNodeRef = preNode && (typeof preNode === 'string' ? false : preNode.nodeType === sequenceNodeType.REFERENCE);+ const result = `${currentText}${theLastList.length && isPreNodeRef ? ',' : ''}${theLastList.join(',')}`;+ handleRangeChange(result, !theLastList.length && newOffset ? newOffset : result.length, isEnd);+ }+ });useEffect(() => {if (refSelectionsRenderService && isNeed) {let isFirst = true;- // eslint-disable-next-line complexity+const handleSelectionsChange = (selections: ISelectionWithCoord[], isEnd: boolean) => {if (isFirst) {isFirst = false;return;}- const currentDocSelections = editor?.getSelectionRanges();- if (currentDocSelections?.length !== 1) {- return;- }- const docRange = currentDocSelections[0];- const offset = docRange.startOffset - 1;- const sequenceNodes = [...sequenceNodesRef.current];- const nodeIndex = findIndexFromSequenceNodes(sequenceNodes, offset, false);-- if (isSelectingRef.current === FormulaSelectingType.NEED_ADD) {- if (offset !== 0) {- if (nodeIndex === -1 && sequenceNodes.length) {- return;- }- const range = selections[selections.length - 1];- const lastNodes = sequenceNodes.splice(nodeIndex + 1);- const rangeSheetId = range.rangeWithCoord.sheetId ?? subUnitId;- const unitRangeName = {- range: range.rangeWithCoord,- unitId: range.rangeWithCoord.unitId ?? unitId,- sheetName: getSheetNameById(rangeSheetId),- };- const isAcrossSheet = rangeSheetId !== subUnitId;- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && isAcrossSheet, sheetName);- sequenceNodes.push({ token: refRanges[0], nodeType: sequenceNodeType.REFERENCE } as any);- const newSequenceNodes = [...sequenceNodes, ...lastNodes];- const result = sequenceNodeToText(newSequenceNodes);- handleRangeChange(result, getOffsetFromSequenceNodes(sequenceNodes), isEnd);- } else {- const range = selections[selections.length - 1];- const rangeSheetId = range.rangeWithCoord.sheetId ?? subUnitId;- const unitRangeName = {- range: range.rangeWithCoord,- unitId: range.rangeWithCoord.unitId ?? unitId,- sheetName: getSheetNameById(rangeSheetId),- };- const isAcrossSheet = rangeSheetId !== subUnitId;- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && isAcrossSheet);- sequenceNodes.unshift({ token: refRanges[0], nodeType: sequenceNodeType.REFERENCE } as any);- const result = sequenceNodeToText(sequenceNodes);- handleRangeChange(result, refRanges[0].length, isEnd);- }- } else {- // 更新全部的 ref Selection- let currentRefIndex = 0;- const newTokens = sequenceNodes.map((item) => {- if (typeof item === 'string') {- return item;- }- if (item.nodeType === sequenceNodeType.REFERENCE) {- const nodeRange = deserializeRangeWithSheet(item.token);- if (!nodeRange.sheetName) {- nodeRange.sheetName = sheetName;- }-- if (isSupportAcrossSheet) {- // 直接跳过非当前表的 node 节点- if (contextRef.current.activeSheet?.getName() !== nodeRange.sheetName) {- return item.token;- }- }- const selection = selections[currentRefIndex];- currentRefIndex++;- if (!selection) {- return '';- }- const rangeSheetId = selection.rangeWithCoord.sheetId ?? subUnitId;- const unitRangeName = {- range: selection.rangeWithCoord,- unitId: selection.rangeWithCoord.unitId ?? unitId,- sheetName: getSheetNameById(rangeSheetId),- };- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet, sheetName);- return refRanges[0];- }- return item.token;- });- let currentText = '';- let newOffset;- newTokens.forEach((item, index) => {- currentText += item;- if (index === nodeIndex) {- newOffset = currentText.length;- }- });- const theLastList: string[] = [];- for (let index = currentRefIndex; index <= selections.length - 1; index++) {- const selection = selections[index];- const rangeSheetId = selection.rangeWithCoord.sheetId ?? subUnitId;- const unitRangeName = {- range: selection.rangeWithCoord,- unitId: selection.rangeWithCoord.unitId ?? unitId,- sheetName: getSheetNameById(rangeSheetId),- };- const isAcrossSheet = rangeSheetId !== subUnitId;- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && isAcrossSheet, sheetName);- theLastList.push(refRanges[0]);- }- const preNode = sequenceNodes[sequenceNodes.length - 1];- const isPreNodeRef = preNode && (typeof preNode === 'string' ? false : preNode.nodeType === sequenceNodeType.REFERENCE);- const result = `${currentText}${theLastList.length && isPreNodeRef ? ',' : ''}${theLastList.join(',')}`;- handleRangeChange(result, !theLastList.length && newOffset ? newOffset : result.length, isEnd);- }+ onSelectionsChange(selections.map((i) => i.rangeWithCoord), isEnd);};+const disposableCollection = new DisposableCollection();disposableCollection.add(refSelectionsRenderService.selectionMoving$.subscribe((selections) => {- if (isScalingRef.current) return;handleSelectionsChange(selections, false);}));disposableCollection.add(refSelectionsRenderService.selectionMoveEnd$.subscribe((selections) => {- if (isScalingRef.current) return;handleSelectionsChange(selections, true);}));@@ -203,96 +221,40 @@ export const useSheetSelectionChange = (disposableCollection.dispose();};}- }, [refSelectionsRenderService, editor, isSupportAcrossSheet, isNeed, sequenceNodesRef, subUnitId, unitId, getSheetNameById, sheetName, handleRangeChange, contextRef]);+ }, [isNeed, onSelectionsChange, refSelectionsRenderService]);useEffect(() => {if (isFocus && refSelectionsRenderService && editor) {const disposableCollection = new DisposableCollection();- const handleSequenceNodeReplace = (token: string, index: number) => {- let currentIndex = 0;- let offset = 0;- let isFinish = false;- const { sheetName } = contextRef.current;-- const newSequenceNodes = sequenceNodesRef.current.map((node) => {- if (typeof node === 'string') {- if (!isFinish) {- offset += node.length;- }- return node;- } else if (node.nodeType === sequenceNodeType.REFERENCE) {- const unitRange = deserializeRangeWithSheet(node.token);- if (!unitRange.unitId) {- unitRange.unitId = unitId;- }- if (!unitRange.sheetName) {- unitRange.sheetName = sheetName;- }- if (isSupportAcrossSheet) {- // 直接跳过非当前表的 node 节点- if (contextRef.current.activeSheet?.getName() !== unitRange.sheetName) {- if (!isFinish) {- offset += node.token.length;- }- return node;- }- }- if (currentIndex === index) {- isFinish = true;- const cloneNode = { ...node, token };- if (isSupportAcrossSheet) {- if (unitRange.sheetName !== sheetName) {- cloneNode.token = serializeRangeWithSheet(unitRange.sheetName, deserializeRangeWithSheet(token).range);- } else {- cloneNode.token = token;- }- } else {- cloneNode.token = token;- }- offset += cloneNode.token.length;- currentIndex++;- return cloneNode;- }- if (!isFinish) {- offset += node.token.length;- }- currentIndex++;- return node;- }- if (!isFinish) {- offset += node.token.length;- }- return node;- });- const result = sequenceNodeToText(newSequenceNodes);- handleRangeChange(result, -1, true);- scalingOptionRef.current = { result, offset };- };const reListen = () => {disposableCollection.dispose();const controls = refSelectionsRenderService.getSelectionControls();controls.forEach((control, index) => {- disposableCollection.add(merge(control.selectionMoving$, control.selectionScaling$).pipe(- map((e) => {- return serializeRange(e);- }),- distinctUntilChanged(),- debounceTime(100)- ).subscribe((rangeText) => {- isScalingRef.current = true;- handleSequenceNodeReplace(rangeText, index);- }));- });+ disposableCollection.add(+ control.selectionScaling$+ .subscribe((newRange) => {+ const selections = refSelectionsRenderService.getSelectionDataWithStyle().map((i) => i.rangeWithCoord);+ const current = selections[index];+ newRange.sheetId = current.sheetId;+ newRange.unitId = current.unitId;+ selections[index] = newRange;+ onSelectionsChange(selections, false);+ })+ );- disposableCollection.add(refSelectionsRenderService.selectionMoveEnd$.subscribe((selections) => {- isScalingRef.current = false;- if (scalingOptionRef.current) {- const { result, offset } = scalingOptionRef.current;- handleRangeChange(result, offset || -1, true);- scalingOptionRef.current = undefined;- }- }));+ disposableCollection.add(+ control.selectionMoving$+ .subscribe((newRange) => {+ const selections = refSelectionsRenderService.getSelectionDataWithStyle().map((i) => i.rangeWithCoord);+ const current = selections[index];+ newRange.sheetId = current.sheetId;+ newRange.unitId = current.unitId;+ selections[index] = newRange;+ onSelectionsChange(selections, true);+ })+ );+ });};const dispose = merge(editor.input$,@@ -308,10 +270,13 @@ export const useSheetSelectionChange = (disposableCollection.dispose();};}- }, [isFocus, refSelectionsRenderService, editor, refSelectionsService.selectionSet$, contextRef, sequenceNodesRef, handleRangeChange, isSupportAcrossSheet, unitId]);+ }, [editor, isFocus, onSelectionsChange, refSelectionsRenderService, refSelectionsService.selectionSet$]);++ refSelectionsRenderService?.getSelectionDataWithStyle();useEffect(() => {if (listenSelectionSet) {+ // selection changed by keyboradconst d = commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id !== SetSelectionsOperation.id) {return;@@ -321,40 +286,17 @@ export const useSheetSelectionChange = (if (params.extra !== 'formula-editor') {return;}- const { selections } = params;- if (selections.length) {- const last = selections[selections.length - 1];+ if (params.selections.length) {+ const last = params.selections[params.selections.length - 1];if (last) {- const range = last.range;- const sheetId = subUnitId;- const unitRangeName = {- range,- unitId: params.unitId === unitId ? '' : params.unitId,- sheetName: params.subUnitId === sheetId ? '' : getSheetNameById(sheetId),- };- const sequenceNodes = [...sequenceNodesRef.current];- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet, sheetName);- const result = refRanges[0];- let lastNode = sequenceNodes[sequenceNodes.length - 1];- if (typeof lastNode === 'object' && lastNode.nodeType === sequenceNodeType.REFERENCE) {- lastNode = { ...lastNode };- lastNode.token = result;- lastNode.endIndex = lastNode.startIndex + result.length;- sequenceNodes[sequenceNodes.length - 1] = lastNode;- const refStr = sequenceNodeToText(sequenceNodes);- handleRangeChange(refStr, getOffsetFromSequenceNodes(sequenceNodes), true);+ const isAdd = isSelectingRef.current === FormulaSelectingType.NEED_ADD;+ const selections: IRange[] = (refSelectionsRenderService?.getSelectionDataWithStyle() ?? []).map((i) => i.rangeWithCoord);+ if (isAdd) {+ selections.push(last.range);} else {- const start = getOffsetFromSequenceNodes(sequenceNodes);- sequenceNodes.push({- nodeType: sequenceNodeType.REFERENCE,- token: result,- startIndex: start,- endIndex: start + result.length,- });-- const refStr = sequenceNodeToText(sequenceNodes);- handleRangeChange(refStr, getOffsetFromSequenceNodes(sequenceNodes), true);+ selections[selections.length - 1] = last.range;}+ onSelectionsChange(selections, true);}}});@@ -363,7 +305,7 @@ export const useSheetSelectionChange = (d.dispose();};}- }, [commandService, getSheetNameById, handleRangeChange, isSupportAcrossSheet, listenSelectionSet, sequenceNodesRef, sheetName, subUnitId, unitId]);+ }, [commandService, editor, isSelectingRef, lexerTreeBuilder, listenSelectionSet, onSelectionsChange, refSelectionsRenderService]);useEffect(() => {if (!editor) {@@ -388,5 +330,5 @@ export const useSheetSelectionChange = (});return () => sub.unsubscribe();- }, [docSelectionManagerService.textSelection$, editor, refSelectionRef, refSelectionsRenderService, refSelectionsService, sequenceNodesRef, sheetSkeletonManagerService, subUnitId, themeService, unitId, univerInstanceService]);+ }, [docSelectionManagerService.textSelection$, editor, refSelectionRef, refSelectionsRenderService, refSelectionsService, sheetSkeletonManagerService, subUnitId, themeService, unitId, univerInstanceService]);};diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex 9f4ee484a0..f2a6f9cb2c 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -15,14 +15,13 @@*/import type { DocumentDataModel, IDisposable, ITextRange } from '@univerjs/core';-import type { Editor } from '@univerjs/docs-ui';+import type { Editor, IKeyboardEventConfig } from '@univerjs/docs-ui';import type { KeyCode, MetaKeys } from '@univerjs/ui';import type { ReactNode } from 'react';import type { IRefSelection } from '../range-selector/hooks/use-highlight';-import type { IKeyboardEventConfig } from '../range-selector/hooks/use-keyboard-event';import type { FormulaSelectingType } from './hooks/use-formula-selection';import { BuildTextUtils, createInternalEditorID, generateRandomId, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';-import { DocBackScrollRenderController, DocSelectionRenderService, IEditorService } from '@univerjs/docs-ui';+import { DocBackScrollRenderController, DocSelectionRenderService, IEditorService, useKeyboardEvent, useResize } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { EMBEDDING_FORMULA_EDITOR } from '@univerjs/sheets-ui';import { useDependency, useEvent, useObservable, useUpdateEffect } from '@univerjs/ui';@@ -31,12 +30,11 @@ import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'reimport { useFocus } from '../range-selector/hooks/use-focus';import { useFormulaToken } from '../range-selector/hooks/use-formula-token';import { useDocHight, useSheetHighlight } from '../range-selector/hooks/use-highlight';-import { useKeyboardEvent } from '../range-selector/hooks/use-keyboard-event';import { useLeftAndRightArrow } from '../range-selector/hooks/use-left-and-right-arrow';import { useRefactorEffect } from '../range-selector/hooks/use-refactor-effect';import { useResetSelection } from '../range-selector/hooks/use-reset-selection';-import { useResize } from '../range-selector/hooks/use-resize';import { useSwitchSheet } from '../range-selector/hooks/use-switch-sheet';+import { findIndexFromSequenceNodes, findRefSequenceIndex } from '../range-selector/utils/find-index-from-sequence-nodes';import { HelpFunction } from './help-function/HelpFunction';import { useFormulaSelecting } from './hooks/use-formula-selection';import { useSheetSelectionChange } from './hooks/use-sheet-selection-change';@@ -132,7 +130,7 @@ export function FormulaEditor(props: IFormulaEditorProps) {const formulaText = BuildTextUtils.transform.getPlainText(document?.getBody()?.dataStream ?? '');const formulaWithoutEqualSymbol = useMemo(() => getFormulaText(formulaText), [formulaText]);const sequenceNodes = useMemo(() => getFormulaToken(formulaWithoutEqualSymbol), [formulaWithoutEqualSymbol, getFormulaToken]);- const { isSelecting } = useFormulaSelecting({ unitId, subUnitId, editorId, isFocus, disableOnClick: disableSelectionOnClick });+ const { isSelecting, isSelectingRef } = useFormulaSelecting({ unitId, subUnitId, editorId, isFocus, disableOnClick: disableSelectionOnClick });const highTextRef = useRef('');const renderManagerService = useDependency(IRenderManagerService);const renderer = renderManagerService.getRenderById(editorId);@@ -151,9 +149,7 @@ export function FormulaEditor(props: IFormulaEditorProps) {const highlightDoc = useDocHight('=');const highlightSheet = useSheetHighlight(unitId, subUnitId);const highlight = useEvent((text: string, isNeedResetSelection: boolean = true, isEnd?: boolean, newSelections?: ITextRange[]) => {- if (!editorRef.current) {- return;- }+ if (!editorRef.current) return;highTextRef.current = text;const sequenceNodes = getFormulaToken(text[0] === '=' ? text.slice(1) : '');const ranges = highlightDoc(@@ -165,15 +161,38 @@ export function FormulaEditor(props: IFormulaEditorProps) {refSelections.current = ranges;if (isEnd) {+ const currentDocSelections = newSelections ?? editor?.getSelectionRanges();+ if (currentDocSelections?.length !== 1) {+ return;+ }+ const docRange = currentDocSelections[0];+ const offset = docRange.startOffset - 1;+ const nodeIndex = findIndexFromSequenceNodes(sequenceNodes, offset, false);+ const refIndex = findRefSequenceIndex(sequenceNodes, nodeIndex);+ // make sure current editing selection is at the end+ if (refIndex >= 0) {+ const target = ranges.splice(refIndex, 1)[0];+ target && ranges.push(target);+ }+highlightSheet(isFocus ? ranges : [], editorRef.current);}});+ // re highlight when focus+ useEffect(() => {+ if (isFocus) {+ highlight(formulaText, false, true);+ }+ }, [isFocus]);++ // re highlight when formula text changeduseEffect(() => {if (isFocus) {+ if (highTextRef.current === formulaText) return;highlight(formulaText, false, true);}- }, [formulaText, isFocus, highlight]);+ }, [formulaText]);useVerify(isFocus, onVerify, formulaText);const focus = useFocus(editor);@@ -253,10 +272,9 @@ export function FormulaEditor(props: IFormulaEditorProps) {useSheetSelectionChange(isFocus && Boolean(isSelecting && docFocusing),isFocus,- isSelecting,+ isSelectingRef,unitId,subUnitId,- sequenceNodes,refSelections,isSupportAcrossSheet,Boolean(selectingMode),diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-highlight.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-highlight.tsindex e178e92a28..da0963e15b 100644--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-highlight.ts+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-highlight.ts@@ -26,7 +26,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';import { IRefSelectionsService, setEndForRange } from '@univerjs/sheets';import { IDescriptionService } from '@univerjs/sheets-formula';import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';-import { useDependency } from '@univerjs/ui';+import { useDependency, useEvent } from '@univerjs/ui';import { useCallback, useEffect, useMemo } from 'react';import { genFormulaRefSelectionStyle } from '../../../common/selection';import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';@@ -129,7 +129,8 @@ export function useSheetHighlight(unitId: string, subUnitId: string) {const refSelectionsRenderService = render?.with(RefSelectionsRenderService);const sheetSkeletonManagerService = render?.with(SheetSkeletonManagerService);- const highlightSheet = useCallback((refSelections: IRefSelection[], editor?: Editor) => {+ const highlightSheet = useEvent((refSelections: IRefSelection[], editor?: Editor) => {+ if (refSelectionsRenderService?.selectionMoving) return;const selectionWithStyle = calcHighlightRanges({unitId,subUnitId,@@ -149,7 +150,7 @@ export function useSheetHighlight(unitId: string, subUnitId: string) {} else {refSelectionsService.setSelections(selectionWithStyle);}- }, [refSelectionsRenderService, refSelectionsService, sheetSkeletonManagerService, themeService, unitId, subUnitId, univerInstanceService]);+ });useEffect(() => {return () => {diff --git a/packages/sheets-formula-ui/src/views/range-selector/utils/find-index-from-sequence-nodes.ts b/packages/sheets-formula-ui/src/views/range-selector/utils/find-index-from-sequence-nodes.tsindex 67b354e0f9..d2ce3c9778 100644--- a/packages/sheets-formula-ui/src/views/range-selector/utils/find-index-from-sequence-nodes.ts+++ b/packages/sheets-formula-ui/src/views/range-selector/utils/find-index-from-sequence-nodes.ts@@ -15,6 +15,7 @@*/import type { ISequenceNode } from '@univerjs/engine-formula';+import { sequenceNodeType } from '@univerjs/engine-formula';export const findIndexFromSequenceNodes = (sequenceNode: (string | ISequenceNode)[], targetIndex: number, isEqual = true) => {let result = -1;@@ -38,3 +39,16 @@ export const findIndexFromSequenceNodes = (sequenceNode: (string | ISequenceNode}, { currentIndex: 0, isFinish: false });return result;};++export const findRefSequenceIndex = (sequenceNode: (string | ISequenceNode)[], targetIndex: number) => {+ const last = sequenceNode[targetIndex];+ let result = -1;+ if (!last || typeof last === 'string' || last.nodeType !== sequenceNodeType.REFERENCE) return -1;+ for (let i = 0; i <= targetIndex; i++) {+ const currentNode = sequenceNode[i];+ if (typeof currentNode !== 'string' && currentNode.nodeType === sequenceNodeType.REFERENCE) {+ result++;+ }+ }+ return result;+};