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(formula): fix formula editor reference selection issues (#7111)
wpxp123456176070f35cfe
diff --git a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.tsindex 68e38195db..c05e6349cd 100644--- a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts+++ b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IDisposable, IRangeWithCoord, Nullable, Workbook } from '@univerjs/core';+import type { IDisposable, IRange, IRangeWithCoord, Nullable, Workbook } from '@univerjs/core';import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';import type { ISelectionStyle, ISelectionWithCoord, ISelectionWithStyle, SheetsSelectionsService, WorkbookSelectionModel } from '@univerjs/sheets';import { DisposableCollection, IContextService, Inject, Injector, RANGE_TYPE, Rectangle, ThemeService, toDisposable } from '@univerjs/core';@@ -23,6 +23,25 @@ import { attachSelectionWithCoord, convertSelectionDataToRange, IRefSelectionsSeimport { BaseSelectionRenderService, checkInHeaderRanges, genNormalSelectionStyle, getAllSelection, getCoordByOffset, getSheetObject, SelectionControl, SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { IShortcutService } from '@univerjs/ui';+export function getActiveSelectionControlIndex(+ selectionControls: SelectionControl[],+ activeSelectionControl: Nullable<SelectionControl>+): number {+ const activeControlIndex = activeSelectionControl ? selectionControls.indexOf(activeSelectionControl) : -1;+ return activeControlIndex === -1 ? selectionControls.length - 1 : activeControlIndex;+}++export function isSelectionRangeChanged(previous: Nullable<IRange>, current: Nullable<IRange>): boolean {+ if (!previous || !current) {+ return false;+ }++ return previous.startRow !== current.startRow ||+ previous.startColumn !== current.startColumn ||+ previous.endRow !== current.endRow ||+ previous.endColumn !== current.endColumn;+}+/*** This service extends the existing `SelectionRenderService` to provide the rendering of prompt selections* when user is editing ref ranges in formulas.@@ -378,6 +397,14 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService impleconst currentCell = activeSelectionControl?.model.currentCell;const expandByShiftKey = evt.shiftKey && currentCell;+ const rangeBeforePointerDown = expandByShiftKey && activeSelectionControl+ ? {+ startRow: activeSelectionControl.model.startRow,+ startColumn: activeSelectionControl.model.startColumn,+ endRow: activeSelectionControl.model.endRow,+ endColumn: activeSelectionControl.model.endColumn,+ }+ : null;const remainLastEnable = this._remainLastEnabled &&!evt.ctrlKey &&!evt.shiftKey &&@@ -403,13 +430,20 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple// In normal situation, pointerdown ---> Create new SelectionControl,activeSelectionControl = this.newSelectionControl(scene, skeleton, selectionWithStyle);}- // clear highlight except last one.- for (let i = 0; i < this.getSelectionControls().length - 1; i++) {- this.getSelectionControls()[i].clearHighlight();+ // Clear highlight except the active selection. The active ref may not be the last one.+ const selectionControls = this.getSelectionControls();+ const activeControlIndex = getActiveSelectionControlIndex(selectionControls, activeSelectionControl);+ for (let i = 0; i < selectionControls.length; i++) {+ if (i !== activeControlIndex && selectionControls[i].model.currentCell) {+ selectionControls[i].clearHighlight();+ }}//#endregionthis._selectionMoveStart$.next(this.getSelectionDataWithStyle());+ if (expandByShiftKey && activeSelectionControl && isSelectionRangeChanged(rangeBeforePointerDown, activeSelectionControl.model)) {+ this._selectionMoving$.next(this.getSelectionDataWithStyle());+ }scene.disableObjectsEvent();this._clearUpdatingListeners();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 fda59d62d9..f595a16fa7 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@@ -48,6 +48,10 @@ export enum FormulaSelectingType {EDIT_OTHER_WORKBOOK_REFERENCE = 4,}+export function shouldSkipReferenceEditingByPointer(isDisabledByPointer: boolean, disableOnClick?: boolean): boolean {+ return isDisabledByPointer && !disableOnClick;+}+// 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, subUnitId } = opts;@@ -109,9 +113,10 @@ export function useFormulaSelecting(opts: { editorId: string; isFocus: boolean;if (dataStream?.substring(0, 1) === '=' && (adding || editing)) {if (editing) {- if (isDisabledByPointer.current) {+ if (shouldSkipReferenceEditingByPointer(isDisabledByPointer.current, disableOnClick)) {return;}+ isDisabledByPointer.current = false;const { sheetName, unitId } = focusingNode.range;const currentUnitId = univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET)?.getUnitId();diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.tsindex 1c5f8c67b6..8d2032f16c 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts@@ -79,6 +79,7 @@ export function calcHighlightRanges(opts: {const skeleton = sheetSkeletonManagerService?.getSkeleton(currentSheetId);if (!skeleton) return;const endIndexes: number[] = [];+ const currentSelections = refSelectionsService.getCurrentSelections();for (let i = 0, len = refSelections.length; i < len; i++) {const refSelection = refSelections[i];const { themeColor, token, refIndex, endIndex } = refSelection;@@ -106,9 +107,10 @@ export function calcHighlightRanges(opts: {const range = setEndForRange(rawRange, worksheet.getRowCount(), worksheet.getColumnCount());range.unitId = unitId;range.sheetId = currentSheetId;+ const currentSelection = currentSelections[selectionWithStyle.length];selectionWithStyle.push({range,- primary: null,+ primary: currentSelection ? currentSelection.primary : undefined,style: genFormulaRefSelectionStyle(themeService, themeColor, refIndex.toString()),});endIndexes.push(endIndex);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 e25d24e017..cb086107db 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@@ -76,6 +76,53 @@ const prepareSelectionChangeContext = (opts: { editor?: Editor; lexerTreeBuilder};};+export function getSelectionsForFormulaRefUpdate(+ selections: IRange[],+ updatingRefIndex: number,+ isCtrlAddMode?: boolean+): { orderedSelections: IRange[]; insertedSelection?: IRange } {+ const orderedSelections = [...selections];+ if (updatingRefIndex === -1) {+ return { orderedSelections };+ }++ const insertedSelection = isCtrlAddMode ? orderedSelections.pop() : undefined;+ const activeSelection = orderedSelections.pop();+ if (activeSelection) {+ orderedSelections.splice(updatingRefIndex, 0, activeSelection);+ }++ return { orderedSelections, insertedSelection };+}++export function createSelectionChangeHandler<TSelection>(opts: {+ initialSelectionsCount: number;+ onSelectionsChange: (selections: TSelection[], isEnd: boolean, isCtrlAddMode?: boolean) => void;+}) {+ let prevSelectionsCount = opts.initialSelectionsCount;+ let pendingCtrlAddCount = 0;++ return (selections: TSelection[], isEnd: boolean, options?: { initial?: boolean }) => {+ if (options?.initial) {+ return;+ }++ const isCtrlAddMode = selections.length > prevSelectionsCount;+ if (isCtrlAddMode && !isEnd) {+ pendingCtrlAddCount = selections.length;+ return;+ }+ const shouldApplyPendingCtrlAdd = isEnd && selections.length === pendingCtrlAddCount;++ if (isEnd) {+ prevSelectionsCount = selections.length;+ pendingCtrlAddCount = 0;+ }++ opts.onSelectionsChange(selections, isEnd, isCtrlAddMode || shouldApplyPendingCtrlAdd);+ };+}+export const useSheetSelectionChange = (isNeed: boolean,isFocus: boolean,@@ -161,12 +208,19 @@ export const useSheetSelectionChange = (handleRangeChange(generateStringWithSequence(sequenceNodes), newOffset, isEnd);}} else {- const orderedSelections = [...selections];- // When isCtrlAddMode is true, skip the updatingRefIndex logic and do not adjust selection order- if (!isCtrlAddMode && updatingRefIndex !== -1) {- const last = orderedSelections.pop();- last && orderedSelections.splice(updatingRefIndex, 0, last);- }+ const { orderedSelections, insertedSelection } = getSelectionsForFormulaRefUpdate(selections, updatingRefIndex, isCtrlAddMode);+ const getRefRangeText = (range: IRange) => {+ const rangeSheetId = range.sheetId ?? subUnitId;+ const unitRangeName = {+ range,+ unitId: range.unitId ?? currentUnit!.getUnitId(),+ sheetName: getSheetNameById(range.unitId ?? currentUnit!.getUnitId(), rangeSheetId),+ };+ const isAcrossWorkbook = currentUnit?.getUnitId() !== unitId;+ const isAcrossSheet = rangeSheetId !== subUnitId;+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && (isAcrossSheet || isAcrossWorkbook), sheetName, isAcrossWorkbook);+ return refRanges[0];+ };// Update all ref Selectionslet currentRefIndex = 0;const newTokens = sequenceNodes.map((item) => {@@ -189,21 +243,18 @@ export const useSheetSelectionChange = (return item.token;}}+ const refIndex = currentRefIndex;const selection = orderedSelections[currentRefIndex];currentRefIndex++;if (!selection) {return '';}- const rangeSheetId = selection.sheetId ?? subUnitId;- const unitRangeName = {- range: selection,- unitId: selection.unitId ?? currentUnit!.getUnitId(),- sheetName: getSheetNameById(selection.unitId ?? currentUnit!.getUnitId(), rangeSheetId),- };- const isAcrossWorkbook = currentUnit?.getUnitId() !== unitId;- const isAcrossSheet = rangeSheetId !== subUnitId;- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && (isAcrossSheet || isAcrossWorkbook), sheetName, isAcrossWorkbook);- return refRanges[0];+ const refRangeText = getRefRangeText(selection);+ if (insertedSelection && refIndex === updatingRefIndex) {+ return `${refRangeText},${getRefRangeText(insertedSelection)}`;+ }++ return refRangeText;}return item.token;});@@ -217,18 +268,9 @@ export const useSheetSelectionChange = (}});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 ?? currentUnit!.getUnitId(),- sheetName: getSheetNameById(selection.unitId ?? currentUnit!.getUnitId(), rangeSheetId),- };- const isAcrossWorkbook = currentUnit?.getUnitId() !== unitId;- const isAcrossSheet = rangeSheetId !== subUnitId;- const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && (isAcrossSheet || isAcrossWorkbook), sheetName, isAcrossWorkbook);- theLastList.push(refRanges[0]);+ for (let index = currentRefIndex; index <= orderedSelections.length - 1; index++) {+ const selection = orderedSelections[index];+ theLastList.push(getRefRangeText(selection));}const preNode = sequenceNodes[sequenceNodes.length - 1];const isPreNodeRef = preNode && (typeof preNode === 'string' ? false : preNode.nodeType === sequenceNodeType.REFERENCE);@@ -239,39 +281,33 @@ export const useSheetSelectionChange = (useEffect(() => {if (refSelectionsRenderService && isNeed) {- let isFirst = true;- let prevSelectionsCount = 0;-- const handleSelectionsChange = (selections: ISelectionWithCoord[], isEnd: boolean) => {- if (isFirst) {- isFirst = false;- prevSelectionsCount = selections.length;- return;- }-- // Determine if it is ctrl add mode by comparing selection count- const isCtrlAddMode = selections.length > prevSelectionsCount;-- if (isEnd) {- prevSelectionsCount = selections.length;- }-- onSelectionsChange(selections.map((i) => i.rangeWithCoord), isEnd, isCtrlAddMode);- };+ const initialSelectionsCount = Math.max(+ refSelectionsRenderService.getSelectionDataWithStyle().length,+ refSelectionsService.getCurrentSelections().length,+ getRefSelections().length+ );+ const handleSelectionsChange = createSelectionChangeHandler<ISelectionWithCoord>({+ initialSelectionsCount,+ onSelectionsChange: (selections, isEnd, isCtrlAddMode) => {+ onSelectionsChange(selections.map((i) => i.rangeWithCoord), isEnd, isCtrlAddMode);+ },+ });+ let isInitialMoveEnd = true;const disposableCollection = new DisposableCollection();disposableCollection.add(refSelectionsRenderService.selectionMoving$.subscribe((selections) => {handleSelectionsChange(selections, false);}));disposableCollection.add(refSelectionsRenderService.selectionMoveEnd$.subscribe((selections) => {- handleSelectionsChange(selections, true);+ handleSelectionsChange(selections, true, { initial: isInitialMoveEnd });+ isInitialMoveEnd = false;}));return () => {disposableCollection.dispose();};}- }, [isNeed, onSelectionsChange, refSelectionsRenderService]);+ }, [getRefSelections, isNeed, onSelectionsChange, refSelectionsRenderService, refSelectionsService]);useEffect(() => {if (isFocus && refSelectionsRenderService && editor) {diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex 084ab49464..a05185e8d5 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -24,6 +24,8 @@ import type { IRefSelection } from './hooks/use-highlight';import {BuildTextUtils,createInternalEditorID,+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,DocumentFlavor,generateRandomId,HorizontalAlign,@@ -95,6 +97,32 @@ export interface IFormulaEditorRef {isClickOutSide: (e: MouseEvent) => boolean;}+interface IFormulaEditorSelectionSyncService {+ getEditor: (editorId: string) => Pick<Editor, 'setSelectionRanges'> | null | undefined | void;+}++export function syncCounterpartFormulaEditorSelection(+ editorService: IFormulaEditorSelectionSyncService,+ editorId: string,+ selections: ITextRange[] | undefined+): void {+ if (!selections?.length) {+ return;+ }++ const syncEditorId = editorId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY+ ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY+ : editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY+ ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY+ : null;++ if (!syncEditorId) {+ return;+ }++ editorService.getEditor(syncEditorId)?.setSelectionRanges(selections);+}+export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFormulaEditorRef>) => {const {errorText,@@ -329,6 +357,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFconst newSelections = offset !== -1 ? [{ startOffset: offset + 1, endOffset: offset + 1, collapsed: true }] : undefined;highlight(`=${refString}`, true, isEnd, newSelections);+ syncCounterpartFormulaEditorSelection(editorService, editorId, newSelections);if (isEnd) {focus();if (offset !== -1) {