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
feat(formua-editor): support cross sheet references (#3933)
Gpound.liu068f5123c84f
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.tsindex 26d90e02b5..4e49c75846 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@@ -17,7 +17,7 @@import type { Workbook } from '@univerjs/core';import type { ISequenceNode } from '@univerjs/engine-formula';import type { ISelectionStyle, ISelectionWithStyle } from '@univerjs/sheets';-import { ColorKit, IUniverInstanceService, ThemeService, useDependency } from '@univerjs/core';+import { ColorKit, IUniverInstanceService, ThemeService, useDependency, useObservable } from '@univerjs/core';import { IEditorService } from '@univerjs/docs-ui';import { deserializeRangeWithSheet } from '@univerjs/engine-formula';import { IRenderManagerService } from '@univerjs/engine-render';@@ -27,6 +27,7 @@ import { attachRangeWithCoord, SheetSkeletonManagerService } from '@univerjs/sheimport { useEffect, useState } from 'react';import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';import { buildTextRuns, useColor } from '../../range-selector/hooks/useHighlight';+import { useStateRef } from './useStateRef';interface IRefSelection {refIndex: number;@@ -51,34 +52,42 @@ export function useSheetHighlight(isNeed: boolean, unitId: string, subUnitId: stconst [ranges, rangesSet] = useState<ISelectionWithStyle[]>([]);+ const workbook = univerInstanceService.getUnit<Workbook>(unitId);+ const worksheet = workbook?.getSheetBySheetId(subUnitId);++ const activeSheet = useObservable(workbook?.activeSheet$);+ const contextRef = useStateRef({ activeSheet, sheetName: worksheet?.getName() });+useEffect(() => {const workbook = univerInstanceService.getUnit<Workbook>(unitId);- const worksheet = workbook?.getActiveSheet();const selectionWithStyle: ISelectionWithStyle[] = [];- if (!workbook || !worksheet || !isNeed) {+ const { activeSheet, sheetName } = contextRef.current;+ if (!workbook || !activeSheet || !isNeed) {rangesSet(selectionWithStyle);return;}- const currentSheetId = worksheet?.getSheetId();- const getSheetIdByName = (name: string) => workbook?.getSheetBySheetName(name)?.getSheetId();for (let i = 0, len = refSelections.length; i < len; i++) {const refSelection = refSelections[i];const { themeColor, token, refIndex } = refSelection;const unitRangeName = deserializeRangeWithSheet(token);- const { unitId: refUnitId, sheetName, range: rawRange } = unitRangeName;- if (refUnitId && unitId !== refUnitId) {+ if (!unitRangeName.unitId) {+ unitRangeName.unitId = unitId;+ }+ if (!unitRangeName.sheetName) {+ unitRangeName.sheetName = sheetName || '';+ }+ const { unitId: refUnitId, sheetName: rangeSheetName, range: rawRange } = unitRangeName;+ if (unitId !== refUnitId) {continue;}- const refSheetId = getSheetIdByName(sheetName);-- if (refSheetId && refSheetId !== currentSheetId) {+ if (rangeSheetName !== activeSheet.getName()) {continue;}- const range = setEndForRange(rawRange, worksheet.getRowCount(), worksheet.getColumnCount());+ const range = setEndForRange(rawRange, activeSheet.getRowCount(), activeSheet.getColumnCount());selectionWithStyle.push({range,diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.tsindex 0811fff6e5..1d97906f5a 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts@@ -21,10 +21,10 @@ import type { Editor } from '@univerjs/docs-ui';import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';import type { INode } from '../../range-selector/utils/filterReferenceNode';-import { DisposableCollection, IUniverInstanceService, useDependency } from '@univerjs/core';+import { DisposableCollection, IUniverInstanceService, useDependency, useObservable } from '@univerjs/core';import { deserializeRangeWithSheet, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';import { IRenderManagerService } from '@univerjs/engine-render';-import { useEffect, useRef } from 'react';+import { useEffect, useMemo, useRef } from 'react';import { merge } from 'rxjs';import { debounceTime, distinctUntilChanged, map, throttleTime } from 'rxjs/operators';import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';@@ -53,6 +53,9 @@ export const useSheetSelectionChange = (const workbook = univerInstanceService.getUnit<Workbook>(unitId);const getSheetNameById = (sheetId: string) => workbook?.getSheetBySheetId(sheetId)?.getName() ?? '';+ const sheetName = useMemo(() => getSheetNameById(subUnitId), [subUnitId]);+ const activeSheet = useObservable(workbook?.activeSheet$);+ const contextRef = useStateRef({ activeSheet, sheetName });const render = renderManagerService.getRenderById(unitId);const refSelectionsRenderService = render?.with(RefSelectionsRenderService);@@ -89,7 +92,8 @@ export const useSheetSelectionChange = (unitId: range.rangeWithCoord.unitId ?? unitId,sheetName: getSheetNameById(rangeSheetId),};- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet);+ const isAcrossSheet = rangeSheetId !== subUnitId;+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && isAcrossSheet);sequenceNodes.push({ token: refRanges[0], nodeType: sequenceNodeType.REFERENCE } as any);const newSequenceNodes = [...sequenceNodes, ...lastNodes];const result = sequenceNodeToText(newSequenceNodes);@@ -102,7 +106,8 @@ export const useSheetSelectionChange = (unitId: range.rangeWithCoord.unitId ?? unitId,sheetName: getSheetNameById(rangeSheetId),};- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet);+ 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);@@ -115,6 +120,17 @@ export const useSheetSelectionChange = (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) {@@ -140,7 +156,8 @@ export const useSheetSelectionChange = (unitId: selection.rangeWithCoord.unitId ?? unitId,sheetName: getSheetNameById(rangeSheetId),};- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet);+ const isAcrossSheet = rangeSheetId !== subUnitId;+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && isAcrossSheet);theLastList.push(refRanges[0]);}const preNode = sequenceNodes[sequenceNodes.length - 1];@@ -172,8 +189,8 @@ export const useSheetSelectionChange = (let currentIndex = 0;let offset = 0;let isFinish = false;- const workbook = univerInstanceService.getUnit<Workbook>(unitId);- const currentSheetName = workbook?.getActiveSheet()?.getName() || '';+ const { sheetName } = contextRef.current;+const newSequenceNodes = sequenceNodesRef.current.map((node) => {if (typeof node === 'string') {if (!isFinish) {@@ -181,20 +198,36 @@ export const useSheetSelectionChange = (}return node;} else if (node.nodeType === sequenceNodeType.REFERENCE) {- const unitRange = deserializeRangeWithSheet(token);- unitRange.unitId = unitRange.unitId === '' ? unitId : unitRange.unitId;- unitRange.sheetName = unitRange.sheetName === '' ? currentSheetName : unitRange.sheetName;+ 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) {- cloneNode.token = serializeRangeWithSheet(unitRange.sheetName, unitRange.range);+ if (unitRange.sheetName !== sheetName) {+ cloneNode.token = serializeRangeWithSheet(unitRange.sheetName, deserializeRangeWithSheet(token).range);+ } else {+ cloneNode.token = token;+ }} else {- cloneNode.token = serializeRange(unitRange.range);+ cloneNode.token = token;}offset += cloneNode.token.length;currentIndex++;-return cloneNode;}if (!isFinish) {diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex a018dee429..aab5342c4b 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -30,6 +30,7 @@ import { useRefactorEffect } from '../range-selector/hooks/useRefactorEffect';import { useRefocus } from '../range-selector/hooks/useRefocus';import { useResetSelection } from '../range-selector/hooks/useResetSelection';import { useResize } from '../range-selector/hooks/useResize';+import { useSwitchSheet } from '../range-selector/hooks/useSwitchSheet';import { HelpFunction } from './help-function/HelpFunction';import { useFormulaDescribe } from './hooks/useFormulaDescribe';import { useFormulaSearch } from './hooks/useFormulaSearch';@@ -59,6 +60,7 @@ const noop = () => { };export function FormulaEditor(props: IFormulaEditorProps) {const { errorText, initValue, unitId, subUnitId, isFocus: _isFocus = true, isSupportAcrossSheet = false,onFocus = noop,+ onBlur = noop,onChange,onVerify,actions,@@ -95,7 +97,7 @@ export function FormulaEditor(props: IFormulaEditorProps) {const editorId = useMemo(() => createInternalEditorID(`${EMBEDDING_FORMULA_EDITOR}-${generateRandomId(4)}`), []);const isError = useMemo(() => errorText !== undefined, [errorText]);- const { sequenceNodes } = useFormulaToken(formulaWithoutEqualSymbol);+ const { sequenceNodes, sequenceNodesSet } = useFormulaToken(formulaWithoutEqualSymbol);const refSelections = useDocHight(editorId, sequenceNodes);useVerify(isFocus, onVerify, formulaText);const focus = useFocus(editor);@@ -137,6 +139,7 @@ export function FormulaEditor(props: IFormulaEditorProps) {useLeftAndRightArrow(isFocus, editor);useSheetSelectionChange(isFocus, unitId, subUnitId, sequenceNodes, isSupportAcrossSheet, editor, handleSelectionChange);useRefocus();+ useSwitchSheet(isFocus, unitId, isSupportAcrossSheet, isFocusSet, onBlur, () => sequenceNodesSet((pre) => [...pre]));const { searchList, searchText, handlerFormulaReplace, reset: resetFormulaSearch } = useFormulaSearch(isFocus, sequenceNodes, editor);const { functionInfo, paramIndex, reset } = useFormulaDescribe(isFocus, formulaText, editor);diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useSwitchSheet.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useSwitchSheet.tsnew file mode 100644index 0000000000..221c806cdd--- /dev/null+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useSwitchSheet.ts@@ -0,0 +1,65 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, useDependency } from '@univerjs/core';+import { IEditorService } from '@univerjs/docs-ui';+import { IRenderManagerService } from '@univerjs/engine-render';+import { SetWorksheetActiveOperation } from '@univerjs/sheets';+import { useEffect } from 'react';+import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';++export const useSwitchSheet = (isNeed: boolean, unitId: string, isSupportAcrossSheet: boolean, isFocusSet: (v: boolean) => void, onBlur: () => void, refresh: () => void) => {+ const commandService = useDependency(ICommandService);+ const editorService = useDependency(IEditorService);+ const renderManagerService = useDependency(IRenderManagerService);+ const render = renderManagerService.getRenderById(unitId);+ const refSelectionsRenderService = render?.with(RefSelectionsRenderService);++ useEffect(() => {+ if (isNeed && refSelectionsRenderService) {+ if (isSupportAcrossSheet) {+ const d = commandService.onCommandExecuted((info) => {+ if (info.id === SetWorksheetActiveOperation.id) {+ const length = refSelectionsRenderService.getSelectionControls().length;+ for (let index = 1; index <= length; index++) {+ refSelectionsRenderService.clearLastSelection();+ }+ setTimeout(() => {+ refresh();+ }, 30);+ }+ });+ return () => {+ d.dispose();+ };+ } else {+ const d = commandService.beforeCommandExecuted((info) => {+ if (info.id === SetWorksheetActiveOperation.id) {+ isFocusSet(false);+ onBlur();+ // Refresh the component+ refresh();+ const editor = editorService.getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);+ editor?.focus();+ }+ });+ return () => {+ d.dispose();+ };+ }+ }+ }, [isNeed, refSelectionsRenderService]);+};diff --git a/packages/sheets-formula-ui/src/views/range-selector/index.tsx b/packages/sheets-formula-ui/src/views/range-selector/index.tsxindex cb20a634cb..c6fb67a816 100644--- a/packages/sheets-formula-ui/src/views/range-selector/index.tsx+++ b/packages/sheets-formula-ui/src/views/range-selector/index.tsx@@ -23,13 +23,12 @@ import { DocBackScrollRenderController, IEditorService } from '@univerjs/docs-uiimport { deserializeRangeWithSheet, LexerTreeBuilder, matchToken, sequenceNodeType } from '@univerjs/engine-formula';import { IRenderManagerService } from '@univerjs/engine-render';import { CloseSingle, DeleteSingle, IncreaseSingle, SelectRangeSingle } from '@univerjs/icons';-import { SetWorksheetActiveOperation } from '@univerjs/sheets';import { IDescriptionService } from '@univerjs/sheets-formula';import { RANGE_SELECTOR_SYMBOLS, SetCellEditVisibleOperation } from '@univerjs/sheets-ui';import cl from 'clsx';import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';-import { filter } from 'rxjs';+import { filter, noop } from 'rxjs';import { RefSelectionsRenderService } from '../../services/render-services/ref-selections.render-service';import { useEditorInput } from './hooks/useEditorInput';@@ -43,6 +42,7 @@ import { useRefocus } from './hooks/useRefocus';import { useResetSelection } from './hooks/useResetSelection';import { useResize } from './hooks/useResize';import { useSheetSelectionChange } from './hooks/useSheetSelectionChange';+import { useSwitchSheet } from './hooks/useSwitchSheet';import { useVerify } from './hooks/useVerify';import styles from './index.module.less';import { rangePreProcess } from './utils/rangePreProcess';@@ -247,6 +247,8 @@ export function RangeSelector(props: IRangeSelectorProps) {useRefocus();+ useSwitchSheet(!rangeDialogVisible && isFocus, unitId, isSupportAcrossSheet, isFocusSet, onBlur, () => sequenceNodesSet((pre) => [...pre]));+useEffect(() => {if (editor) {const dispose = editor.input$.subscribe((e) => {@@ -261,17 +263,7 @@ export function RangeSelector(props: IRangeSelectorProps) {}, [editor]);useEffect(() => {- const d1 = commandService.beforeCommandExecuted((info) => {- if (info.id === SetWorksheetActiveOperation.id && !isSupportAcrossSheet) {- isFocusSet(false);- onBlur();- // Refresh the component- sequenceNodesSet((pre) => [...pre]);- const editor = editorService.getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);- editor?.focus();- }- });- const d2 = commandService.onCommandExecuted((info) => {+ const d = commandService.onCommandExecuted((info) => {if (info.id === SetCellEditVisibleOperation.id) {rangeDialogVisibleSet(false);onRangeSelectorDialogVisibleChange(false);@@ -280,8 +272,7 @@ export function RangeSelector(props: IRangeSelectorProps) {}});return () => {- d1.dispose();- d2.dispose();+ d.dispose();};}, [isSupportAcrossSheet]);@@ -454,6 +445,8 @@ function RangeSelectorDialog(props: {useSheetSelectionChange(focusIndex >= 0, unitId, subUnitId, sequenceNodes, isSupportAcrossSheet, isOnlyOneRange, handleSheetSelectionChange);useRefactorEffect(focusIndex >= 0, unitId);useOnlyOneRange(unitId, isOnlyOneRange);+ useSwitchSheet(focusIndex >= 0, unitId, isSupportAcrossSheet, noop, noop, () => sequenceNodesSet((pre) => [...pre]));+// 如果只有一个空 range,那么默认自动添加 rangeuseEffect(() => {if (ranges.length === 0 || (ranges.length === 1 && !ranges[0])) {diff --git a/packages/sheets-formula-ui/src/views/range-selector/utils/unitRangesToText.ts b/packages/sheets-formula-ui/src/views/range-selector/utils/unitRangesToText.tsindex b973bd272a..3a46145ef8 100644--- a/packages/sheets-formula-ui/src/views/range-selector/utils/unitRangesToText.ts+++ b/packages/sheets-formula-ui/src/views/range-selector/utils/unitRangesToText.ts@@ -24,8 +24,8 @@ export function getSheetNameById(univerInstanceService: IUniverInstanceService,return univerInstanceService.getUnit<Workbook>(unitId)?.getSheetBySheetId(sheetId)?.getName() || '';}-export const unitRangesToText = (ranges: IUnitRangeName[], isSupportAcrossSheet: boolean = false) => {- if (!isSupportAcrossSheet) {+export const unitRangesToText = (ranges: IUnitRangeName[], isNeedSheetName: boolean = false) => {+ if (!isNeedSheetName) {return ranges.map((item) => serializeRange(item.range));} else {return ranges.map((item) => {diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsxindex eb022b5586..7d920212df 100644--- a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx@@ -70,9 +70,9 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {return;}- const unitId = workbook.getUnitId();+ const unitId = useMemo(() => workbook.getUnitId(), []);- const subUnitId = workbook.getActiveSheet().getSheetId();+ const subUnitId = useMemo(() => workbook.getActiveSheet().getSheetId(), []);const [nameValue, setNameValue] = useState(name);@@ -252,6 +252,7 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {unitId={unitId}subUnitId={subUnitId}isFocus={isFocusFormulaEditor}+ isSupportAcrossSheetonChange={(v = '') => {const formula = v || '';formulaEditorChange(formula);@@ -259,6 +260,7 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {onVerify={(res: boolean) => {setValidFormulaOrRange(res);}}+onFocus={() => isFocusFormulaEditorSet(true)}actions={formulaEditorActionsRef.current}/>