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): edit other sheet range error (#4673)
zhangwdec0fdb9e9e0
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 73ce17b4e8..fd4cea13ce 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@@ -14,15 +14,16 @@* limitations under the License.*/-import type { IAccessor } from '@univerjs/core';-import { Injector, IUniverInstanceService } from '@univerjs/core';+import type { IAccessor, IUnitRangeName, Workbook } from '@univerjs/core';+import type { ISequenceNode } from '@univerjs/engine-formula';+import { Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';import { DocSelectionRenderService } from '@univerjs/docs-ui';-import { isFormulaLexerToken, LexerTreeBuilder, matchRefDrawToken, matchToken, sequenceNodeType } from '@univerjs/engine-formula';+import { deserializeRangeWithSheetWithCache, isFormulaLexerToken, LexerTreeBuilder, matchRefDrawToken, matchToken, sequenceNodeType } from '@univerjs/engine-formula';import { IRenderManagerService } from '@univerjs/engine-render';import { useDependency, useEvent } from '@univerjs/ui';import { useEffect, useRef, useState } from 'react';-import { filter, map } from 'rxjs';+import { filter } from 'rxjs';import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';import { useStateRef } from './use-state-ref';@@ -42,11 +43,15 @@ export enum FormulaSelectingType {NOT_SELECT = 0,NEED_ADD = 1,CAN_EDIT = 2,+ // editing cross sheet reference+ EDIT_OTHER_SHEET_REFERENCE = 3,}+// eslint-disable-next-line max-lines-per-functionexport function useFormulaSelecting(opts: { editorId: string; isFocus: boolean; disableOnClick?: boolean; unitId: string; subUnitId: string }) {- const { editorId, isFocus, disableOnClick, unitId } = opts;+ const { editorId, isFocus, disableOnClick, unitId, subUnitId } = opts;const renderManagerService = useDependency(IRenderManagerService);+ const univerInstanceService = useDependency(IUniverInstanceService);const sheetRenderer = renderManagerService.getRenderById(unitId);const renderer = renderManagerService.getRenderById(editorId);const docSelectionRenderService = renderer?.with(DocSelectionRenderService);@@ -57,53 +62,80 @@ export function useFormulaSelecting(opts: { editorId: string; isFocus: boolean;const isDisabledByPointer = useRef(true);const refSelectionsRenderService = sheetRenderer?.with(RefSelectionsRenderService);const isSelectingRef = useStateRef(isSelecting);+ const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ const sourceSheet = workbook?.getSheetBySheetId(subUnitId);const setIsSelecting = useEvent((v: FormulaSelectingType) => {if (refSelectionsRenderService) {- refSelectionsRenderService.setSkipLastEnabled(v === FormulaSelectingType.NEED_ADD);+ refSelectionsRenderService.setSkipLastEnabled(v === FormulaSelectingType.NEED_ADD || v === FormulaSelectingType.EDIT_OTHER_SHEET_REFERENCE);}isSelectingRef.current = v;innerSetIsSelecting(v);});- useEffect(() => {- const sub = docSelectionManagerService.textSelection$- .pipe(- filter((param) => param.unitId === editorId),- map(() => {- const activeRange = docSelectionRenderService?.getActiveTextRange();- const index = activeRange?.collapsed ? activeRange.startOffset! : -1;- return index;- })- )- .subscribe((index) => {- const config = getCurrentBodyDataStreamAndOffset(injector);- if (!config) return;- const dataStream = config?.dataStream?.slice(0, -2);- const nodes = lexerTreeBuilder.sequenceNodesBuilder(dataStream) ?? [];- const char = dataStream[index - 1];- const nextChar = dataStream[index];- const focusingIndex = nodes.findIndex((node) => typeof node === 'object' && node.nodeType === sequenceNodeType.REFERENCE && index === node.endIndex + 2);- const adding = (char && matchRefDrawToken(char)) && (!nextChar || (isFormulaLexerToken(nextChar) && nextChar !== matchToken.OPEN_BRACKET));- const editing = focusingIndex > -1;-- if (dataStream?.substring(0, 1) === '=' && (adding || editing)) {- if (editing) {- if (isDisabledByPointer.current) {- return;- }- setIsSelecting(FormulaSelectingType.CAN_EDIT);- } else {- isDisabledByPointer.current = false;- setIsSelecting(FormulaSelectingType.NEED_ADD);- }+ // eslint-disable-next-line complexity+ const calculateSelectingType = useEvent(() => {+ if (!workbook) return;+ const currentSheet = workbook.getActiveSheet();+ const activeRange = docSelectionRenderService?.getActiveTextRange();+ const index = activeRange?.collapsed ? activeRange.startOffset! : -1;+ const config = getCurrentBodyDataStreamAndOffset(injector);+ if (!config) return;+ const dataStream = config?.dataStream?.slice(0, -2);+ const nodes = (lexerTreeBuilder.sequenceNodesBuilder(dataStream) ?? []).map((node) => {+ if (typeof node === 'object') {+ if (node.nodeType === sequenceNodeType.REFERENCE) {+ return {+ ...node,+ range: deserializeRangeWithSheetWithCache(node.token),+ };+ }++ return {+ ...node,+ range: undefined,+ };+ }++ return node;+ });+ const char = dataStream[index - 1];+ const nextChar = dataStream[index];+ const focusingNode = nodes.find((node) => typeof node === 'object' && node.nodeType === sequenceNodeType.REFERENCE && index === node.endIndex + 2) as unknown as (ISequenceNode & { range: IUnitRangeName });+ const adding = (char && matchRefDrawToken(char)) && (!nextChar || (isFormulaLexerToken(nextChar) && nextChar !== matchToken.OPEN_BRACKET));+ const editing = Boolean(focusingNode);++ if (dataStream?.substring(0, 1) === '=' && (adding || editing)) {+ if (editing) {+ if (isDisabledByPointer.current) {+ return;+ }+ if (+ (!focusingNode.range.sheetName && currentSheet.getSheetId() === sourceSheet?.getSheetId()) ||+ focusingNode.range.sheetName === currentSheet.getName()+ ) {+ setIsSelecting(FormulaSelectingType.CAN_EDIT);} else {- setIsSelecting(FormulaSelectingType.NOT_SELECT);+ setIsSelecting(FormulaSelectingType.EDIT_OTHER_SHEET_REFERENCE);}+ } else {+ isDisabledByPointer.current = false;+ setIsSelecting(FormulaSelectingType.NEED_ADD);+ }+ } else {+ setIsSelecting(FormulaSelectingType.NOT_SELECT);+ }+ });++ useEffect(() => {+ const sub = docSelectionManagerService.textSelection$+ .pipe(filter((param) => param.unitId === editorId))+ .subscribe(() => {+ calculateSelectingType();});return () => sub.unsubscribe();- }, [docSelectionManagerService.textSelection$, docSelectionRenderService, editorId, injector, lexerTreeBuilder, setIsSelecting]);+ }, [calculateSelectingType, docSelectionManagerService.textSelection$, editorId]);useEffect(() => {if (!isFocus) {@@ -122,5 +154,14 @@ export function useFormulaSelecting(opts: { editorId: string; isFocus: boolean;return () => sub?.unsubscribe();}, [disableOnClick, renderer?.mainComponent?.onPointerDown$, setIsSelecting]);+ useEffect(() => {+ if (!isFocus) return;+ const sub = workbook?.activeSheet$.subscribe(() => {+ calculateSelectingType();+ });++ return () => sub?.unsubscribe();+ }, [calculateSelectingType, isFocus, workbook?.activeSheet$]);+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 81ecd6bd02..606d8544c8 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@@ -23,7 +23,7 @@ import type { RefObject } from 'react';import type { IRefSelection } from '../../range-selector/hooks/use-highlight';import { DisposableCollection, ICommandService, IUniverInstanceService, ThemeService } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';-import { deserializeRangeWithSheet, LexerTreeBuilder, sequenceNodeType } from '@univerjs/engine-formula';+import { deserializeRangeWithSheet, generateStringWithSequence, LexerTreeBuilder, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';import { IRenderManagerService } from '@univerjs/engine-render';import { IRefSelectionsService, SetSelectionsOperation } from '@univerjs/sheets';import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';@@ -128,6 +128,16 @@ export const useSheetSelectionChange = (const result = sequenceNodeToText(sequenceNodes);handleRangeChange(result, refRanges[0].length, isEnd);}+ } else if (isSelectingRef.current === FormulaSelectingType.EDIT_OTHER_SHEET_REFERENCE) {+ const last = selections.pop();+ if (!last) return;+ const node = sequenceNodes[nodeIndex];+ if (typeof node === 'object' && node.nodeType === sequenceNodeType.REFERENCE) {+ const oldToken = node.token;+ node.token = sheetName === activeSheet?.getName() ? serializeRange(last) : serializeRangeWithSheet(activeSheet!.getName(), last);+ const newOffset = offset + (node.token.length - oldToken.length);+ handleRangeChange(generateStringWithSequence(sequenceNodes), newOffset, isEnd);+ }} else {const orderedSelections = [...selections];if (updatingRefIndex !== -1) {diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-left-and-right-arrow.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-left-and-right-arrow.tsindex fb577f901c..f121558fbf 100644--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-left-and-right-arrow.ts+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-left-and-right-arrow.ts@@ -83,7 +83,7 @@ export const useLeftAndRightArrow = (isNeed: boolean, shouldMoveSelection: Formudirection,jumpOver: JumpOver.moveGap,extra: 'formula-editor',- fromCurrentSelection: shouldMoveSelectionRef.current === FormulaSelectingType.NEED_ADD,+ fromCurrentSelection: shouldMoveSelectionRef.current === FormulaSelectingType.NEED_ADD || shouldMoveSelectionRef.current === FormulaSelectingType.EDIT_OTHER_SHEET_REFERENCE,});} else if (metaKey === MetaKeys.SHIFT) {commandService.executeCommand(ExpandSelectionCommand.id, {@@ -100,7 +100,7 @@ export const useLeftAndRightArrow = (isNeed: boolean, shouldMoveSelection: FormucommandService.executeCommand(MoveSelectionCommand.id, {direction,extra: 'formula-editor',- fromCurrentSelection: shouldMoveSelectionRef.current === FormulaSelectingType.NEED_ADD,+ fromCurrentSelection: shouldMoveSelectionRef.current === FormulaSelectingType.NEED_ADD || shouldMoveSelectionRef.current === FormulaSelectingType.EDIT_OTHER_SHEET_REFERENCE,});}} else {