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): fixed the issue where the formula in the range is messed up after the range reorder (#4959)
wpxp1234564c0e6654540a
diff --git a/packages/sheets-formula-ui/src/controllers/formula-reorder.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-reorder.controller.tsnew file mode 100644index 0000000000..ea27b3cd10--- /dev/null+++ b/packages/sheets-formula-ui/src/controllers/formula-reorder.controller.ts@@ -0,0 +1,137 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 type { ICellData, IMutationInfo, Nullable } from '@univerjs/core';+import type { IReorderRangeMutationParams } from '@univerjs/sheets';+import {+ Disposable,+ Inject,+ IUniverInstanceService,+ ObjectMatrix,+ Range,+ Tools,+} from '@univerjs/core';+import { FormulaDataModel, LexerTreeBuilder } from '@univerjs/engine-formula';+import { ReorderRangeCommand, SetRangeValuesMutation, SheetInterceptorService } from '@univerjs/sheets';++export class FormulaReorderController extends Disposable {+ constructor(+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,+ @Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder+ ) {+ super();++ this._initialize();+ }++ private _initialize() {+ this.disposeWithMe(this._sheetInterceptorService.interceptCommand({+ getMutations: (command) => {+ if (command.id === ReorderRangeCommand.id) {+ return this._reorderFormula(command.params as IReorderRangeMutationParams);+ }++ return {+ redos: [],+ undos: [],+ };+ },+ }));+ }++ private _reorderFormula(params: IReorderRangeMutationParams) {+ const redos: IMutationInfo[] = [];+ const undos: IMutationInfo[] = [];+ const { unitId, subUnitId, range, order } = params;+ const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);+ const worksheet = workbook?.getSheetBySheetId(subUnitId);++ if (!worksheet) {+ return {+ redos,+ undos,+ };+ }++ const cellMatrix = worksheet.getCellMatrix();+ const redoFormulaMatrix = new ObjectMatrix<Nullable<ICellData>>();+ const undoFormulaMatrix = new ObjectMatrix<Nullable<ICellData>>();++ let hasFormula = false;++ Range.foreach(range, (row, col) => {+ let targetRow = row;++ if (order.hasOwnProperty(row)) {+ targetRow = order[row];+ }++ const targetCell = cellMatrix.getValue(targetRow, col);++ if (targetCell?.f || targetCell?.si) {+ hasFormula = true;++ const formulaString = this._formulaDataModel.getFormulaStringByCell(targetRow, col, subUnitId, unitId) as string;+ const shiftedFormula = this._lexerTreeBuilder.moveFormulaRefOffset(+ formulaString,+ 0,+ row - targetRow+ );+ const newCell = Tools.deepClone(targetCell);+ newCell.f = shiftedFormula;+ newCell.si = null;++ redoFormulaMatrix.setValue(row, col, newCell);+ } else {+ redoFormulaMatrix.setValue(row, col, targetCell);+ }++ undoFormulaMatrix.setValue(row, col, cellMatrix.getValue(row, col));+ });++ if (!hasFormula) {+ return {+ redos,+ undos,+ };+ }++ redos.push({+ id: SetRangeValuesMutation.id,+ params: {+ unitId,+ subUnitId,+ cellValue: redoFormulaMatrix.getMatrix(),+ },+ });++ undos.push({+ id: SetRangeValuesMutation.id,+ params: {+ unitId,+ subUnitId,+ cellValue: undoFormulaMatrix.getMatrix(),+ },+ });++ return {+ redos,+ undos,+ };+ }+}diff --git a/packages/sheets-formula-ui/src/index.ts b/packages/sheets-formula-ui/src/index.tsindex 17aca7b537..3005c79b1e 100644--- a/packages/sheets-formula-ui/src/index.ts+++ b/packages/sheets-formula-ui/src/index.ts@@ -29,6 +29,8 @@ export { RefSelectionsRenderService } from './services/render-services/ref-selecexport { GlobalRangeSelectorService, type IShowRangeSelectorDialogOptions } from './services/range-selector.service';// #region - all commands+export { FormulaReorderController } from './controllers/formula-reorder.controller';+export { FORMULA_PROMPT_ACTIVATED } from './services/prompt.service';export { UniverSheetsFormulaUIPlugin } from './sheets-formula-ui.plugin';diff --git a/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts b/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.tsindex 034a18eece..ec5f259513 100644--- a/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts+++ b/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts@@ -32,6 +32,7 @@ import { FormulaAutoFillController } from './controllers/formula-auto-fill.contrimport { FormulaClipboardController } from './controllers/formula-clipboard.controller';import { FormulaEditorShowController } from './controllers/formula-editor-show.controller';import { FormulaRenderManagerController } from './controllers/formula-render.controller';+import { FormulaReorderController } from './controllers/formula-reorder.controller';import { FormulaUIController } from './controllers/formula-ui.controller';import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';import { GlobalRangeSelectorService } from './services/range-selector.service';@@ -77,6 +78,7 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {[FormulaClipboardController],[FormulaEditorShowController],[FormulaRenderManagerController],+ [FormulaReorderController],]);}@@ -101,6 +103,7 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {override onSteady(): void {this._injector.get(FormulaAutoFillController);+ this._injector.get(FormulaReorderController);}private _initUIPart(): void {diff --git a/packages/sheets-sort-ui/package.json b/packages/sheets-sort-ui/package.jsonindex c297133b8e..102c3fde37 100644--- a/packages/sheets-sort-ui/package.json+++ b/packages/sheets-sort-ui/package.json@@ -77,6 +77,7 @@},"devDependencies": {"@univerjs-infra/shared": "workspace:*",+ "@univerjs/sheets-formula-ui": "workspace:*","less": "^4.2.2","postcss": "^8.5.3","react": "18.3.1",diff --git a/packages/sheets-sort-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-sort-ui/src/commands/commands/__tests__/create-command-test-bed.tsnew file mode 100644index 0000000000..b040d737e7--- /dev/null+++ b/packages/sheets-sort-ui/src/commands/commands/__tests__/create-command-test-bed.ts@@ -0,0 +1,186 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';+import { ILogService, Inject, Injector, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Plugin, Tools, Univer, UniverInstanceType } from '@univerjs/core';+import { FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, IFormulaCurrentConfigService, IFormulaRuntimeService, LexerTreeBuilder } from '@univerjs/engine-formula';+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';+import { FormulaReorderController } from '@univerjs/sheets-formula-ui';+import { SheetsSortService } from '@univerjs/sheets-sort';+import { SheetsSortController } from '@univerjs/sheets-sort/controllers/sheets-sort.controller.js';+import zhCN from '../../../locale/zh-CN';+import { SheetsSortUIService } from '../../../services/sheets-sort-ui.service';++const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'sheet1',+ cellData: {+ 0: {+ 9: { // J1+ v: 1,+ },+ 10: { // K1+ v: 2,+ },+ 11: { // L1+ f: '=J1/K1',+ },+ },+ 1: {+ 9: { // J2+ v: 2,+ },+ 10: { // K2+ v: 2,+ },+ 11: { // L2+ f: '=J2/K2',+ },+ },+ 2: {+ 9: { // J3+ v: 3,+ },+ 10: { // K3+ v: 2,+ },+ 11: { // L3+ f: '=J3/K3',+ },+ },+ 3: {+ 9: { // J4+ v: 4,+ },+ 10: { // K4+ v: 2,+ },+ 11: { // L4+ f: '=J4/K4',+ },+ },+ 4: {+ 9: { // J5+ v: 5,+ },+ 10: { // K5+ v: 2,+ },+ 11: { // L5+ f: '=J5/K5',+ },+ },+ 5: {+ 9: { // J6+ v: 6,+ },+ 10: { // K6+ v: 2,+ },+ 11: { // L6+ f: '=J6/K6',+ },+ },+ 6: {+ 9: { // J7+ v: 7,+ },+ 10: { // K7+ v: 2,+ },+ 11: { // L7+ f: '=SUM(J7:K8)',+ },+ },+ 7: {+ 9: { // J8+ v: 1,+ },+ },+ },+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: [],+ styles: {},+};++export interface ITestBed {+ univer: Univer;+ get: Injector['get'];+ sheet: Workbook;+}++export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const injector = this._injector;+ injector.add([SheetsSelectionsService]);+ injector.add([SheetInterceptorService]);+ injector.add([FormulaDataModel]);+ injector.add([LexerTreeBuilder]);+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);+ injector.add([SheetsSortController]);+ injector.add([SheetsSortService]);+ injector.add([SheetsSortUIService]);+ injector.add([FormulaReorderController]);++ dependencies?.forEach((d) => injector.add(d));+ }++ override onReady(): void {+ this._injector.get(SheetsSortController);+ this._injector.get(FormulaReorderController);+ }+ }++ univer.registerPlugin(TestPlugin);+ const sheet = univer.createUniverSheet(Tools.deepClone(workbookData || TEST_WORKBOOK_DATA_DEMO));++ const univerInstanceService = injector.get(IUniverInstanceService);+ univerInstanceService.focusUnit('test');+ const logService = injector.get(ILogService);++ logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs++ const localeService = injector.get(LocaleService);+ localeService.load({ zhCN });++ return {+ univer,+ get: injector.get.bind(injector),+ sheet,+ };+}diff --git a/packages/sheets-sort-ui/src/commands/commands/__tests__/formula-reorder.spec.ts b/packages/sheets-sort-ui/src/commands/commands/__tests__/formula-reorder.spec.tsnew file mode 100644index 0000000000..8e7e68859e--- /dev/null+++ b/packages/sheets-sort-ui/src/commands/commands/__tests__/formula-reorder.spec.ts@@ -0,0 +1,137 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 type { ICellData, IDisposable, Injector, Nullable, Univer } from '@univerjs/core';+import type { IConfirmPartMethodOptions } from '@univerjs/ui';+import { ICommandService, IUniverInstanceService, RANGE_TYPE } from '@univerjs/core';+import { ReorderRangeCommand, ReorderRangeMutation, SetRangeValuesMutation, SheetsSelectionsService } from '@univerjs/sheets';+import { IConfirmService } from '@univerjs/ui';+import { Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SheetsSortUIService } from '../../../services/sheets-sort-ui.service';+import { createCommandTestBed } from './create-command-test-bed';++describe('Test "Sort Range Commands"', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;+ let sortService: SheetsSortUIService;+ let getValues: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Array<Array<Nullable<ICellData>>> | undefined;++ beforeEach(() => {+ const testBed = createCommandTestBed(undefined, [+ [+ IConfirmService,+ {+ useClass: class MockConfirmService implements IConfirmService {+ confirmOptions$: Subject<IConfirmPartMethodOptions[]> = new Subject();++ open(params: IConfirmPartMethodOptions): IDisposable {+ throw new Error('Method not implemented.');+ }++ confirm(params: IConfirmPartMethodOptions): Promise<boolean> {+ return Promise.resolve(true);+ }++ close(id: string): void {+ throw new Error('Method not implemented.');+ }+ },+ },+ ],+ ]);+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);+ commandService.registerCommand(ReorderRangeCommand);+ commandService.registerCommand(SetRangeValuesMutation);+ commandService.registerCommand(ReorderRangeMutation);++ sortService = get(SheetsSortUIService);++ getValues = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Array<Array<Nullable<ICellData>>> | undefined =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValues();+ });++ afterEach(() => univer.dispose());++ describe('sort range has formula', () => {+ it('desc case: ', async () => {+ // J1+ let J1Cell = getValues(0, 9, 0, 9)?.[0]?.[0];+ expect(J1Cell?.v).toStrictEqual(1);+ // L1+ let L1Cell = getValues(0, 11, 0, 11)?.[0]?.[0];+ expect(L1Cell?.f).toStrictEqual('=J1/K1');+ // L7+ let L7Cell = getValues(6, 11, 6, 11)?.[0]?.[0];+ expect(L7Cell?.f).toStrictEqual('=SUM(J7:K8)');++ const selectionManager = get(SheetsSelectionsService);+ selectionManager.addSelections([+ {+ range: {+ startRow: 0,+ startColumn: 9,+ endRow: 6,+ endColumn: 11,+ rangeType: RANGE_TYPE.NORMAL,+ },+ primary: {+ actualRow: 0,+ actualColumn: 9,+ startRow: 0,+ startColumn: 9,+ endRow: 6,+ endColumn: 11,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ },+ ]);++ const result = await sortService.triggerSortDirectly(false, false);+ expect(result).toBeTruthy();++ // J1+ J1Cell = getValues(0, 9, 0, 9)?.[0]?.[0];+ expect(J1Cell?.v).toStrictEqual(7);+ // L1+ L1Cell = getValues(0, 11, 0, 11)?.[0]?.[0];+ expect(L1Cell?.f).toStrictEqual('=SUM(J1:K2)');+ // L7+ L7Cell = getValues(6, 11, 6, 11)?.[0]?.[0];+ expect(L7Cell?.f).toStrictEqual('=J7/K7');+ });+ });+});diff --git a/packages/sheets/src/commands/commands/reorder-range.command.ts b/packages/sheets/src/commands/commands/reorder-range.command.tsindex 7057f5c789..6cc640209c 100644--- a/packages/sheets/src/commands/commands/reorder-range.command.ts+++ b/packages/sheets/src/commands/commands/reorder-range.command.ts@@ -65,16 +65,16 @@ export const ReorderRangeCommand: ICommand<IReorderRangeCommandParams> = {];const result = sequenceExecute(redos, commandService);- const reoderAfterIntercepted = sheetInterceptorService.afterCommandExecute({ id: ReorderRangeCommand.id, params });+ const reorderAfterIntercepted = sheetInterceptorService.afterCommandExecute({ id: ReorderRangeCommand.id, params });if (result.result) {- sequenceExecute(reoderAfterIntercepted.redos, commandService);+ sequenceExecute(reorderAfterIntercepted.redos, commandService);const undoRedoService = accessor.get(IUndoRedoService);undoRedoService.pushUndoRedo({unitID: unitId,- undoMutations: [...undos, ...reoderAfterIntercepted.undos],- redoMutations: [...redos, ...reoderAfterIntercepted.redos],+ undoMutations: [...undos, ...reorderAfterIntercepted.undos],+ redoMutations: [...redos, ...reorderAfterIntercepted.redos],});return true;}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6252393c60..0d9714a2c0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2783,6 +2783,9 @@ importers:'@univerjs-infra/shared':specifier: workspace:*version: link:../../common/shared+ '@univerjs/sheets-formula-ui':+ specifier: workspace:*+ version: link:../sheets-formula-uiless:specifier: ^4.2.2version: 4.2.2