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(sheets-formula-ui): refresh formula bar for spill cells (#7664)

wpxp12345645adcd8beebd
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts
index bd22f8f1b4..efede9fc99 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts
@@ -15,12 +15,46 @@
*/
import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
-import { ILogService, Inject, Injector, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
+import {
+ ILogService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { EditorService, IEditorService } from '@univerjs/docs-ui';
-import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, HyperlinkEngineFormulaService, ICalculateFormulaService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, IHyperlinkEngineFormulaService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import {
+ CalculateFormulaService,
+ DefinedNamesService,
+ FormulaCurrentConfigService,
+ FormulaDataModel,
+ FormulaRuntimeService,
+ HyperlinkEngineFormulaService,
+ ICalculateFormulaService,
+ IDefinedNamesService,
+ IFormulaCurrentConfigService,
+ IFormulaRuntimeService,
+ IHyperlinkEngineFormulaService,
+ LexerTreeBuilder,
+} from '@univerjs/engine-formula';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { DefinedNameDataController, IRefSelectionsService, RangeProtectionRuleModel, SheetInterceptorService, SheetSkeletonService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import {
+ DefinedNameDataController,
+ IRefSelectionsService,
+ RangeProtectionRuleModel,
+ SheetInterceptorService,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+ WorkbookPermissionService,
+ WorksheetPermissionService,
+ WorksheetProtectionPointModel,
+ WorksheetProtectionRuleModel,
+} from '@univerjs/sheets';
import { EditorBridgeService, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
@@ -112,7 +146,12 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);
injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);
injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);
- injector.add([SheetSkeletonManagerService]);
+ const hasSheetSkeletonManagerService = dependencies?.some((dependency) =>
+ Array.isArray(dependency) && dependency[0] === SheetSkeletonManagerService
+ );
+ if (!hasSheetSkeletonManagerService) {
+ injector.add([SheetSkeletonManagerService]);
+ }
injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);
injector.add([IEditorService, { useClass: EditorService }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts
index c1558fa134..c832d67dd7 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-editor-show.controller.spec.ts
@@ -14,115 +14,262 @@
* limitations under the License.
*/
-import { BEFORE_CELL_EDIT, SetWorksheetRowAutoHeightMutation } from '@univerjs/sheets';
-import { Subject } from 'rxjs';
-import { describe, expect, it, vi } from 'vitest';
+import type { Injector, Univer } from '@univerjs/core';
+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
+import { ICommandService } from '@univerjs/core';
+import { FormulaDataModel } from '@univerjs/engine-formula';
+import { DeviceInputEventType } from '@univerjs/engine-render';
+import {
+ BEFORE_CELL_EDIT,
+ SetRangeValuesMutation,
+ SheetInterceptorService,
+} from '@univerjs/sheets';
+import { IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { FormulaEditorShowController } from '../formula-editor-show.controller';
+import { createCommandTestBed } from './create-command-test-bed';
-function createController() {
- let editInterceptor: any;
- let beforeCommandHandler: ((command: { id: string; params?: unknown }) => void) | undefined;
- let commandExecutedHandler: ((command: { id: string; params?: unknown }, options?: unknown) => void) | undefined;
- const currentSkeleton$ = new Subject<any>();
- const worksheet = {
- getSheetId: () => 'sheet-1',
- unitId: 'unit-1',
- getCell: vi.fn(() => ({ f: '=SUM(A1:A2)' })),
- };
- const skeleton = { worksheet };
-
- const controller = new FormulaEditorShowController(
- { unitId: 'unit-1' } as never,
- {
- writeCellInterceptor: {
- intercept: vi.fn((point, config) => {
- expect(point).toBe(BEFORE_CELL_EDIT);
- editInterceptor = config;
- return { dispose: vi.fn() };
- }),
+type EditLocation = NonNullable<ReturnType<IEditorBridgeService['getEditLocation']>>;
+
+let activeUniver: Univer | null = null;
+
+function createEditLocation(isInArrayFormulaRange = false): EditLocation {
+ return {
+ unitId: 'test',
+ sheetId: 'sheet1',
+ row: 1,
+ column: 1,
+ isInArrayFormulaRange,
+ } as EditLocation;
+}
+
+function createControllerTestBed(editLocation = createEditLocation()) {
+ let injector: Injector;
+ const renderContext = {
+ unitId: 'test',
+ scene: {
+ onTransformChange$: {
+ subscribeEvent: () => ({ dispose: vi.fn() }),
},
- } as never,
- { getSkeleton: vi.fn(() => skeleton) } as never,
- {
- getArrayFormulaRange: vi.fn(() => null),
- getArrayFormulaCellData: vi.fn(() => ({})),
- getFormulaStringByCell: vi.fn(() => '=SUM(A1:A2)'),
- } as never,
- { getColorFromTheme: vi.fn(() => '#fff') } as never,
- { getRenderUnitById: vi.fn(() => null) } as never,
- {
- currentSkeleton$,
- getCurrentSkeleton: vi.fn(() => skeleton),
- } as never,
- {
- onCommandExecuted: vi.fn((handler) => {
- commandExecutedHandler = handler;
- return { dispose: vi.fn() };
- }),
- beforeCommandExecuted: vi.fn((handler) => {
- beforeCommandHandler = handler;
- return { dispose: vi.fn() };
- }),
- } as never,
- { debug: vi.fn() } as never
- );
-
- currentSkeleton$.next({ skeleton, unitId: 'unit-1', sheetId: 'sheet-1' });
+ },
+ };
+ const createSheetSkeletonManagerService = () =>
+ injector.createInstance(SheetSkeletonManagerService, renderContext as never);
+ const createFormulaEditorShowController = () =>
+ injector.createInstance(FormulaEditorShowController, renderContext as never);
+ const testBed = createCommandTestBed(undefined, [
+ [
+ SheetSkeletonManagerService,
+ { useFactory: createSheetSkeletonManagerService },
+ ],
+ [
+ FormulaEditorShowController,
+ { useFactory: createFormulaEditorShowController },
+ ],
+ ]);
+ activeUniver = testBed.univer;
+ injector = testBed.univer.__getInjector();
+ testBed.sheet.addWorksheet('sheet2', 1, { id: 'sheet2', name: 'Sheet2', cellData: {} });
+
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(SetRangeValuesMutation);
+
+ const editorBridgeService = testBed.get(IEditorBridgeService);
+ vi.spyOn(editorBridgeService, 'getEditLocation').mockReturnValue(editLocation);
+ testBed.get(FormulaEditorShowController);
return {
- controller,
- editInterceptor: () => editInterceptor,
- beforeCommandHandler: () => beforeCommandHandler,
- commandExecutedHandler: () => commandExecutedHandler,
- worksheet,
+ commandService,
+ editorBridgeService,
+ formulaDataModel: testBed.get(FormulaDataModel),
+ get: testBed.get,
+ injector,
+ refreshEditCellState: vi.spyOn(editorBridgeService, 'refreshEditCellState'),
+ sheet: testBed.sheet,
+ sheetInterceptorService: testBed.get(SheetInterceptorService),
};
}
+function createSetRangeValuesParams(subUnitId = 'sheet1'): ISetRangeValuesMutationParams {
+ return {
+ unitId: 'test',
+ subUnitId,
+ cellValue: {
+ 0: {
+ 1: { v: 2 },
+ },
+ },
+ };
+}
+
+function setSpillCellData(formulaDataModel: FormulaDataModel): void {
+ formulaDataModel.setArrayFormulaCellData({
+ test: {
+ sheet1: {
+ 1: {
+ 1: { v: 2 },
+ },
+ },
+ },
+ });
+}
+
+afterEach(() => {
+ activeUniver?.dispose();
+ activeUniver = null;
+});
+
describe('FormulaEditorShowController', () => {
it('preserves the formula string when starting to edit a calculated formula cell', () => {
- const { controller, editInterceptor, worksheet } = createController();
- const originalCell = { v: 3 };
- const result = editInterceptor().handler(
- originalCell,
- {
- row: 0,
- col: 1,
- unitId: 'unit-1',
- subUnitId: 'sheet-1',
- worksheet,
- },
- vi.fn((cell) => cell)
+ const testBed = createControllerTestBed();
+ const worksheet = testBed.sheet.getSheetBySheetId('sheet1');
+ if (worksheet == null) {
+ throw new Error('Expected sheet1 to exist');
+ }
+
+ const result = testBed.sheetInterceptorService.writeCellInterceptor
+ .fetchThroughInterceptors(BEFORE_CELL_EDIT)(
+ { v: 3 },
+ {
+ row: 0,
+ col: 1,
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ worksheet,
+ workbook: testBed.sheet,
+ origin: worksheet.getCellRaw(0, 1),
+ }
+ );
+
+ expect(result).toEqual({ v: 3, f: '=SUM(A1)' });
+ });
+
+ it('passes an empty edit value through unchanged', () => {
+ const testBed = createControllerTestBed();
+ const worksheet = testBed.sheet.getSheetBySheetId('sheet1');
+ if (worksheet == null) {
+ throw new Error('Expected sheet1 to exist');
+ }
+
+ const result = testBed.sheetInterceptorService.writeCellInterceptor
+ .fetchThroughInterceptors(BEFORE_CELL_EDIT)(
+ null,
+ {
+ row: 0,
+ col: 1,
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ worksheet,
+ workbook: testBed.sheet,
+ origin: worksheet.getCellRaw(0, 1),
+ }
+ );
+
+ expect(result).toBeNull();
+ });
+
+ it('refreshes when the current cell becomes a spill cell', async () => {
+ const testBed = createControllerTestBed();
+ setSpillCellData(testBed.formulaDataModel);
+
+ const result = await testBed.commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ createSetRangeValuesParams(),
+ { applyFormulaCalculationResult: true }
);
- expect(result).toEqual({ v: 3, f: '=SUM(A1:A2)' });
+ expect(result).toBe(true);
+ expect(testBed.refreshEditCellState).toHaveBeenCalledOnce();
+ });
+
+ it('refreshes when the current cell was a spill cell before its array data was removed', async () => {
+ const testBed = createControllerTestBed(createEditLocation(true));
- controller.dispose();
+ const result = await testBed.commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ createSetRangeValuesParams(),
+ { applyFormulaCalculationResult: true }
+ );
+
+ expect(result).toBe(true);
+ expect(testBed.refreshEditCellState).toHaveBeenCalledOnce();
});
- it('passes empty edit values through and registers row-height refresh listener', () => {
- const { controller, editInterceptor, beforeCommandHandler } = createController();
- const next = vi.fn((cell) => cell);
-
- expect(editInterceptor().handler(null, {
- row: 0,
- col: 1,
- unitId: 'unit-1',
- subUnitId: 'sheet-1',
- worksheet: {},
- }, next)).toBeNull();
- expect(next).toHaveBeenCalledWith(null);
-
- beforeCommandHandler()?.({
- id: SetWorksheetRowAutoHeightMutation.id,
- params: {
- unitId: 'unit-1',
- subUnitId: 'sheet-1',
- rowsAutoHeightInfo: [{ row: 0 }],
- },
+ it('does not refresh for a formula result on a non-spill cell', async () => {
+ const testBed = createControllerTestBed();
+
+ const result = await testBed.commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ createSetRangeValuesParams(),
+ { applyFormulaCalculationResult: true }
+ );
+
+ expect(result).toBe(true);
+ expect(testBed.refreshEditCellState).not.toHaveBeenCalled();
+ });
+
+ it('does not refresh for an ordinary range value mutation', async () => {
+ const testBed = createControllerTestBed();
+ setSpillCellData(testBed.formulaDataModel);
+
+ const result = await testBed.commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ createSetRangeValuesParams()
+ );
+
+ expect(result).toBe(true);
+ expect(testBed.refreshEditCellState).not.toHaveBeenCalled();
+ });
+
+ it('does not refresh for a formula result on another sheet', async () => {
+ const testBed = createControllerTestBed();
+ setSpillCellData(testBed.formulaDataModel);
+
+ const result = await testBed.commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ createSetRangeValuesParams('sheet2'),
+ { applyFormulaCalculationResult: true }
+ );
+
+ expect(result).toBe(true);
+ expect(testBed.refreshEditCellState).not.toHaveBeenCalled();
+ });
+
+ it('does not refresh while the editor is visible', async () => {
+ const testBed = createControllerTestBed();
+ setSpillCellData(testBed.formulaDataModel);
+ testBed.editorBridgeService.changeVisible({
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ unitId: 'test',
});
- expect(beforeCommandHandler()).toBeDefined();
+ const result = await testBed.commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ createSetRangeValuesParams(),
+ { applyFormulaCalculationResult: true }
+ );
+
+ expect(result).toBe(true);
+ expect(testBed.refreshEditCellState).not.toHaveBeenCalled();
+ });
+
+ it('refreshes only for the controller associated with the result workbook', async () => {
+ const testBed = createControllerTestBed();
+ const otherWorkbookController = testBed.injector.createInstance(
+ FormulaEditorShowController,
+ { unitId: 'other' } as never
+ );
+ setSpillCellData(testBed.formulaDataModel);
+
+ const result = await testBed.commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ createSetRangeValuesParams(),
+ { applyFormulaCalculationResult: true }
+ );
- controller.dispose();
+ expect(result).toBe(true);
+ expect(testBed.refreshEditCellState).toHaveBeenCalledOnce();
+ otherWorkbookController.dispose();
});
});
diff --git a/packages/sheets-formula-ui/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-editor-show.controller.ts
index d214219483..ee33087a74 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-editor-show.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-editor-show.controller.ts
@@ -14,9 +14,22 @@
* limitations under the License.
*/
-import type { ICellDataForSheetInterceptor, ICommandInfo, IObjectMatrixPrimitiveType, IRange, IRowAutoHeightInfo, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import type {
+ ICellDataForSheetInterceptor,
+ ICommandInfo,
+ IObjectMatrixPrimitiveType,
+ IRange,
+ IRowAutoHeightInfo,
+ Nullable,
+ Workbook,
+ Worksheet,
+} from '@univerjs/core';
import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';
-import type { ISelectionWithStyle, ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';
+import type {
+ ISelectionWithStyle,
+ ISetRangeValuesMutationParams,
+ ISetWorksheetRowAutoHeightMutationParams,
+} from '@univerjs/sheets';
import {
ColorKit,
Disposable,
@@ -34,8 +47,16 @@ import {
SetFormulaCalculationResultMutation,
} from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { attachSelectionWithCoord, BEFORE_CELL_EDIT, SetWorksheetRowAutoHeightMutation, SheetInterceptorService, SheetSkeletonService } from '@univerjs/sheets';
import {
+ attachSelectionWithCoord,
+ BEFORE_CELL_EDIT,
+ SetRangeValuesMutation,
+ SetWorksheetRowAutoHeightMutation,
+ SheetInterceptorService,
+ SheetSkeletonService,
+} from '@univerjs/sheets';
+import {
+ IEditorBridgeService,
SELECTION_SHAPE_DEPTH,
SelectionControl,
SheetSkeletonManagerService,
@@ -57,7 +78,8 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@ICommandService private readonly _commandService: ICommandService,
- @ILogService private readonly _logService: ILogService
+ @ILogService private readonly _logService: ILogService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService
) {
super();
this._initSkeletonChangeListener();
@@ -157,6 +179,31 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
if (command.id === SetFormulaCalculationResultMutation.id || (command.id === SetArrayFormulaDataMutation.id && options && options.remove)) {
this._removeArrayFormulaRangeShape();
}
+
+ if (command.id !== SetRangeValuesMutation.id || options?.applyFormulaCalculationResult !== true || command.params == null) {
+ return;
+ }
+
+ const params = command.params as ISetRangeValuesMutationParams;
+ const editLocation = this._editorBridgeService.getEditLocation();
+ if (
+ editLocation == null
+ || params.unitId !== this._context.unitId
+ || params.unitId !== editLocation.unitId
+ || params.subUnitId !== editLocation.sheetId
+ || this._editorBridgeService.isVisible().visible
+ ) {
+ return;
+ }
+
+ const { row, column, isInArrayFormulaRange } = editLocation;
+ const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();
+ const isInArrayFormulaCell = arrayFormulaCellData?.[params.unitId]?.[params.subUnitId]?.[row]?.[column] != null;
+ if (isInArrayFormulaRange !== true && !isInArrayFormulaCell) {
+ return;
+ }
+
+ this._editorBridgeService.refreshEditCellState();
}));
this.disposeWithMe(
@@ -174,6 +221,7 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
private _displayArrayFormulaRangeShape(matrixRange: IObjectMatrixPrimitiveType<IRange>, row: number, col: number, unitId: string, subUnitId: string, worksheet: Worksheet, cellInfo: Nullable<ICellDataForSheetInterceptor>): Nullable<ICellDataForSheetInterceptor> {
// const sheetFormulaData = this._formulaDataModel.getSheetFormulaData(unitId, subUnitId);
+ let result = cellInfo;
new ObjectMatrix(matrixRange).forValue((rowIndex, columnIndex, range) => {
if (range == null) {
@@ -191,8 +239,8 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
return;
}
- if (cellInfo == null) {
- cellInfo = {
+ if (result == null) {
+ result = {
f: mainCellValue.f,
isInArrayFormulaRange: true,
};
@@ -203,7 +251,7 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
}
});
- return cellInfo;
+ return result;
}
private _createArrayFormulaRangeShape(arrayRange: IRange, unitId: string, subUnitId: string): void {