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.

feat(sheet): ref range support squash mutation (#600)

Gpound.liu864489cbcaf6
diff --git a/packages/base-sheets/src/services/__tests__/ref-range.setvice.spec.ts b/packages/base-sheets/src/services/__tests__/ref-range.setvice.spec.ts
new file mode 100644
index 0000000000..3240a5ada2
--- /dev/null
+++ b/packages/base-sheets/src/services/__tests__/ref-range.setvice.spec.ts
@@ -0,0 +1,159 @@
+import type { IRange, Univer, Workbook, Worksheet } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, SheetInterceptorService } from '@univerjs/core';
+import type { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { IMoveRangeCommandParams } from '../../commands/commands/move-range.command';
+import { MoveRangeCommand } from '../../commands/commands/move-range.command';
+import { MoveRangeMutation } from '../../commands/mutations/move-range.mutation';
+import { RefRangeService } from '../ref-range/ref-range.service';
+import { SelectionManagerService } from '../selection-manager.service';
+import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from './util';
+
+const originRange: IRange = {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 2,
+ endColumn: 2,
+};
+const getRangeByCell = (row: number, col: number): IRange => ({
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+});
+describe('Test ref-range.service', () => {
+ let univer: Univer;
+ let commandService: ICommandService;
+ let get: Injector['get'];
+ let sheetInterceptorService: SheetInterceptorService;
+ let refRangeService: RefRangeService;
+ let workbook: Workbook;
+ let worksheet: Worksheet;
+
+ beforeEach(() => {
+ const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [[SelectionManagerService], [RefRangeService]]);
+ get = testBed.get;
+ univer = testBed.univer;
+ sheetInterceptorService = get(SheetInterceptorService);
+ refRangeService = get(RefRangeService);
+ commandService = testBed.get(ICommandService);
+ [MoveRangeCommand, MoveRangeMutation].forEach((item) => commandService.registerCommand(item));
+
+ const univerInstanceService = get(IUniverInstanceService);
+ workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ worksheet = workbook.getActiveSheet();
+ });
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('test registerRefRange', () => {
+ const mockFn = vi.fn(() => ({ redos: [], undos: [] }));
+ refRangeService.registerRefRange(originRange, mockFn);
+ const params: IMoveRangeCommandParams = {
+ fromRange: { ...originRange },
+ toRange: { startRow: 4, endRow: 4, startColumn: 4, endColumn: 4 },
+ };
+ commandService.executeCommand(MoveRangeCommand.id, params);
+ expect(mockFn.mock.calls.length).toBe(1);
+ const callParams = (mockFn.mock.calls as any)[0][0];
+ expect(callParams?.id).toBe('sheet.command.move-range');
+ });
+
+ it('test registerRefRange 3', () => {
+ const redoMutationId = 'test-redo-mutation';
+ const undoMutationId = 'test-undo-mutation';
+
+ const mockFn1 = vi.fn(() => ({
+ redos: [{ id: redoMutationId, params: {} }],
+ undos: [{ id: undoMutationId, params: {} }],
+ }));
+ const mockFn2 = vi.fn(() => ({
+ redos: [{ id: redoMutationId, params }],
+ undos: [{ id: undoMutationId, params: {} }],
+ }));
+ const mockFn3 = vi.fn(() => ({
+ redos: [{ id: redoMutationId, params }],
+ undos: [{ id: undoMutationId, params: {} }],
+ }));
+ const mockFn4 = vi.fn(() => ({
+ redos: [{ id: redoMutationId, params }],
+ undos: [{ id: undoMutationId, params: {} }],
+ }));
+
+ refRangeService.registerRefRange(getRangeByCell(2, 2), mockFn1);
+ refRangeService.registerRefRange(getRangeByCell(3, 2), mockFn2);
+ refRangeService.registerRefRange(getRangeByCell(4, 2), mockFn3);
+ refRangeService.registerRefRange(getRangeByCell(1, 1), mockFn4);
+
+ const params: IMoveRangeCommandParams = {
+ fromRange: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 2 },
+ toRange: { startRow: 3, endRow: 5, startColumn: 2, endColumn: 2 },
+ };
+ commandService.executeCommand(MoveRangeCommand.id, params);
+
+ expect(mockFn1.mock.calls.length).toBe(1);
+ expect(mockFn2.mock.calls.length).toBe(1);
+ expect(mockFn3.mock.calls.length).toBe(1);
+ expect(mockFn4.mock.calls.length).toBe(0);
+ const result = sheetInterceptorService.onCommandExecute({ id: MoveRangeCommand.id, params });
+ expect(result.redos.length).toBe(3);
+ });
+
+ it('test merge mutation', () => {
+ const redoMutationId = 'test-redo-mutation';
+ const undoMutationId = 'test-undo-mutation';
+
+ const mockFn1 = vi.fn(() => ({
+ redos: [{ id: redoMutationId, params: { values: [1, 2, 3] } }],
+ undos: [{ id: undoMutationId, params: {} }],
+ }));
+ const mockFn2 = vi.fn(() => ({
+ redos: [{ id: redoMutationId, params: { values: [1, 2, 3] } }],
+ undos: [{ id: undoMutationId, params: {} }],
+ }));
+ const mockFn3 = vi.fn(() => ({
+ redos: [{ id: redoMutationId, params: { values: [1, 2, 3] } }],
+ undos: [{ id: undoMutationId, params: {} }],
+ }));
+
+ refRangeService.registerRefRange(getRangeByCell(2, 2), mockFn1);
+ refRangeService.registerRefRange(getRangeByCell(3, 2), mockFn2);
+ refRangeService.registerRefRange(getRangeByCell(4, 2), mockFn3);
+ // will squash mutations to one.
+ const disposeIntercept = refRangeService.intercept({
+ handler: (list, result, next) => {
+ if (list && list.length) {
+ const lastOne = list[list.length - 1] as any;
+ const firstOne = result[0] as any;
+ if (lastOne.id === redoMutationId && firstOne.id === redoMutationId) {
+ // [1,2,3],[1,2,3],[1,2,3]
+ // after squash to be
+ // [1,2,3,1,2,3,1,2,3]
+ result.map((item) =>
+ (item as any).params.values.forEach((v: number) => lastOne.params.values.push(v))
+ );
+ return list;
+ }
+ }
+ return next(list);
+ },
+ });
+ const params: IMoveRangeCommandParams = {
+ fromRange: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 2 },
+ toRange: { startRow: 3, endRow: 5, startColumn: 2, endColumn: 2 },
+ };
+ commandService.executeCommand(MoveRangeCommand.id, params);
+ const result = sheetInterceptorService.onCommandExecute({ id: MoveRangeCommand.id, params });
+ expect((result as any).redos.length).toBe(1);
+ expect((result as any).redos[0].params.values.length).toBe(9);
+
+ // if dispose, the mutations will not be squash.
+ disposeIntercept.dispose();
+ commandService.executeCommand(MoveRangeCommand.id, params);
+ const resultWithoutInterceptor = sheetInterceptorService.onCommandExecute({ id: MoveRangeCommand.id, params });
+ expect((resultWithoutInterceptor as any).redos.length).toBe(3);
+ expect((resultWithoutInterceptor as any).redos[0].params.values.length).toBe(3);
+ });
+});
diff --git a/packages/base-sheets/src/services/ref-range/__tests__/util.ts b/packages/base-sheets/src/services/ref-range/__tests__/util.ts
new file mode 100644
index 0000000000..09989079ba
--- /dev/null
+++ b/packages/base-sheets/src/services/ref-range/__tests__/util.ts
@@ -0,0 +1,91 @@
+import type { IWorkbookData } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+export const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ '0': {
+ '0': {
+ v: 'A1',
+ },
+ '1': {
+ v: 'A2',
+ },
+ },
+ },
+ },
+ sheet2: {
+ id: 'sheet2',
+ cellData: {
+ '0': {
+ '0': {
+ v: 'A1',
+ },
+ '1': {
+ v: 'A2',
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: ['sheet1'],
+ styles: {},
+};
+
+export function createTestBase(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+
+ let get: Injector['get'] | undefined;
+
+ /**
+ * This plugin hooks into Sheet's DI system to expose API to test scripts
+ */
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Sheet;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ get = this._injector.get.bind(this._injector);
+ }
+
+ override onStarting(injector: Injector): void {
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onDestroy(): void {
+ get = undefined;
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA_DEMO);
+
+ if (get === undefined) {
+ throw new Error('[TestPlugin]: not hooked on!');
+ }
+
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test');
+
+ const logService = get(ILogService);
+ logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+
+ return {
+ univer,
+ get,
+ sheet,
+ };
+}
diff --git a/packages/base-sheets/src/services/ref-range/ref-range.service.ts b/packages/base-sheets/src/services/ref-range/ref-range.service.ts
index 0fdfcc141e..6ad41dd8fb 100644
--- a/packages/base-sheets/src/services/ref-range/ref-range.service.ts
+++ b/packages/base-sheets/src/services/ref-range/ref-range.service.ts
@@ -1,10 +1,13 @@
-import type { IMutationInfo, IRange } from '@univerjs/core';
+import type { IInterceptor, IMutationInfo, IRange } from '@univerjs/core';
import {
+ composeInterceptors,
+ createInterceptorKey,
Disposable,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
Rectangle,
+ remove,
SheetInterceptorService,
toDisposable,
} from '@univerjs/core';
@@ -22,12 +25,13 @@ type RefRangCallback = (
redos: IMutationInfo[];
undos: IMutationInfo[];
};
-
+const refRangeCommandsMerge = createInterceptorKey<IMutationInfo[], IMutationInfo[]>('refRangeCommandsMerge');
/**
* Collect side effects caused by ref range change
*/
@OnLifecycle(LifecycleStages.Steady, RefRangeService)
export class RefRangeService extends Disposable {
+ private _interceptorsByName: Map<string, Array<IInterceptor<IMutationInfo[], IMutationInfo[]>>> = new Map();
constructor(
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@@ -35,6 +39,14 @@ export class RefRangeService extends Disposable {
) {
super();
this._onRefRangeChange();
+ this.intercept({
+ priority: -1,
+ handler: (list, currentValue) => {
+ const _list = list || [];
+ _list.push(...currentValue);
+ return _list;
+ },
+ });
}
private _refRangeManagerMap = new Map<string, Map<string, Set<RefRangCallback>>>();
@@ -141,14 +153,13 @@ export class RefRangeService extends Disposable {
)
.reduce(
(result, currentValue) => {
- result.redos.push(...currentValue.redos);
- result.undos.push(...currentValue.undos);
- return result;
+ const intercept = this._fetchThroughInterceptors();
+ const redos = intercept(result.redos, currentValue.redos) || [];
+ const undos = intercept(result.undos, currentValue.undos) || [];
+ return { redos, undos };
},
{ redos: [], undos: [] }
);
- // TODO@gggpound: The mutations need to be merge by mutation.id
-
return result;
},
});
@@ -178,6 +189,14 @@ export class RefRangeService extends Disposable {
return [];
};
+ /**
+ * Listens to an area and triggers a fall back when movement occurs
+ * @param {IRange} range the area that needs to be monitored
+ * @param {RefRangCallback} callback the callback function that is executed when the range changes
+ * @param {string} [_workbookId]
+ * @param {string} [_worksheetId]
+ * @memberof RefRangeService
+ */
registerRefRange = (
range: IRange,
callback: RefRangCallback,
@@ -214,6 +233,38 @@ export class RefRangeService extends Disposable {
}
});
};
+
+ private _fetchThroughInterceptors() {
+ const key = refRangeCommandsMerge as unknown as string;
+ const interceptors = this._interceptorsByName.get(key) as unknown as Array<typeof refRangeCommandsMerge>;
+ return composeInterceptors(interceptors || []);
+ }
+
+ /**
+ * Create a intercept to squash mutations
+ * @param {typeof refRangeCommandsMerge} interceptor
+ * const disposeIntercept = refRangeService.intercept({
+ handler: (mutations, currentMutation, next) => {
+ // todo something
+ return next(list);
+ },
+ })
+ * mutations mean the operation generated before.
+ * currentMutation mean the operation of the current iteration.
+ * @return {*}
+ * @memberof RefRangeService
+ */
+ intercept(interceptor: typeof refRangeCommandsMerge) {
+ const key = refRangeCommandsMerge as unknown as string;
+ const interceptors = this._interceptorsByName.get(key)! || [];
+ interceptors.push(interceptor);
+ this._interceptorsByName.set(
+ key,
+ interceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
+ );
+
+ return this.disposeWithMe(toDisposable(() => remove(this._interceptorsByName.get(key)!, interceptor)));
+ }
}
function getWorkbookId(univerInstanceService: IUniverInstanceService) {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 834a2a95b4..97c822c467 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -78,6 +78,7 @@ export * from './shared';
// #region sheet
+export { composeInterceptors, createInterceptorKey } from './services/sheet-interceptor/utils/interceptor';
export { Range } from './sheets/range';
export {
deserializeRangeWithSheet,
diff --git a/packages/core/src/services/sheet-interceptor/interceptor-const.ts b/packages/core/src/services/sheet-interceptor/interceptor-const.ts
index ba506d5d0a..696f856825 100644
--- a/packages/core/src/services/sheet-interceptor/interceptor-const.ts
+++ b/packages/core/src/services/sheet-interceptor/interceptor-const.ts
@@ -1,6 +1,5 @@
-import { IWorkbookData } from '../../types/interfaces';
-import { ICellData } from '../../types/interfaces/i-cell-data';
-import { ICommandInfo } from '../command/command.service';
+import type { ICellData } from '../../types/interfaces/i-cell-data';
+import type { ICommandInfo } from '../command/command.service';
import type { ISheetLocation } from './utils/interceptor';
import { createInterceptorKey } from './utils/interceptor';
@@ -8,12 +7,10 @@ const CELL_CONTENT = createInterceptorKey<ICellData, ISheetLocation>('CELL_CONTE
const BEFORE_CELL_EDIT = createInterceptorKey<ICellData, ISheetLocation>('BEFORE_CELL_EDIT');
const AFTER_CELL_EDIT = createInterceptorKey<ICellData, ISheetLocation>('AFTER_CELL_EDIT');
const PERMISSION = createInterceptorKey<boolean, ICommandInfo>('PERMISSION');
-const SAVE = createInterceptorKey<IWorkbookData, ISheetLocation['workbook']>('SAVE');
export const INTERCEPTOR_POINT = {
CELL_CONTENT,
BEFORE_CELL_EDIT,
AFTER_CELL_EDIT,
PERMISSION,
- SAVE,
};
diff --git a/packages/core/src/services/sheet-interceptor/utils/interceptor.ts b/packages/core/src/services/sheet-interceptor/utils/interceptor.ts
index af67e6087b..a05b0f3ad5 100644
--- a/packages/core/src/services/sheet-interceptor/utils/interceptor.ts
+++ b/packages/core/src/services/sheet-interceptor/utils/interceptor.ts
@@ -1,6 +1,6 @@
-import { Nullable } from '../../../common/type-utils';
-import { Workbook } from '../../../sheets/workbook';
-import { Worksheet } from '../../../sheets/worksheet';
+import type { Nullable } from '../../../common/type-utils';
+import type { Workbook } from '../../../sheets/workbook';
+import type { Worksheet } from '../../../sheets/worksheet';
export type InterceptorHandler<M = unknown, C = ISheetLocation> = (
value: Nullable<M>,
@@ -8,10 +8,10 @@ export type InterceptorHandler<M = unknown, C = ISheetLocation> = (
next: (value: Nullable<M>) => Nullable<M>
) => Nullable<M>;
-export type IInterceptor<M, C> = {
+export interface IInterceptor<M, C> {
priority?: number;
handler: InterceptorHandler<M, C>;
-};
+}
export interface ISheetLocation {
workbook: Workbook;
worksheet: Worksheet;
diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts
index 59e2961e0e..f36a87dfa8 100644
--- a/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts
+++ b/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts
@@ -32,7 +32,7 @@ import type { IAutoFillHook } from '@univerjs/ui-plugin-sheets';
import { APPLY_TYPE, getRepeatRange, IAutoFillService, SheetSkeletonManagerService } from '@univerjs/ui-plugin-sheets';
import { Inject, Injector } from '@wendellhu/redi';
import { combineLatest, Observable } from 'rxjs';
-import { distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
+import { debounceTime, distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
import { SHEET_NUMFMT_PLUGIN } from '../base/const/PLUGIN_NAME';
import { AddDecimalCommand } from '../commands/commands/add.decimal.command';
@@ -529,13 +529,23 @@ export class NumfmtController extends Disposable implements INumfmtController {
private _commandExecutedListener() {
this.disposeWithMe(
- this._commandService.onCommandExecuted((command) => {
- if (SetNumfmtCommand.id === command.id) {
- this._sheetSkeletonManagerService.reCalculate();
- // TODO: @Gggpound The command requires the parameters unitId and sheetId to be passed in.
- // this._renderManagerService.getRenderById(unitId)?.mainComponent?.makeDirty();
- }
- })
+ toDisposable(
+ new Observable<ISetNumfmtMutationParams>((subscribe) => {
+ const disposable = this._commandService.onCommandExecuted((command) => {
+ if (SetNumfmtMutation.id === command.id) {
+ subscribe.next(command.params as ISetNumfmtMutationParams);
+ }
+ });
+ return () => {
+ disposable.dispose();
+ };
+ })
+ .pipe(debounceTime(16))
+ .subscribe((params) => {
+ this._sheetSkeletonManagerService.reCalculate();
+ this._renderManagerService.getRenderById(params.workbookId)?.mainComponent?.makeDirty();
+ })
+ )
);
}
}
diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt.ref-range.controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt.ref-range.controller.ts
index c3e946f286..4722f30dbf 100644
--- a/packages/sheets-plugin-numfmt/src/controllers/numfmt.ref-range.controller.ts
+++ b/packages/sheets-plugin-numfmt/src/controllers/numfmt.ref-range.controller.ts
@@ -44,6 +44,39 @@ export class NumfmtRefRangeController extends Disposable {
) {
super();
this._registerRefRange();
+ this._mergeRefMutations();
+ }
+
+ private _mergeRefMutations() {
+ this.disposeWithMe(
+ this._refRangeService.intercept({
+ handler: (list, current, next) => {
+ if (!list || !list.length || !current.length) {
+ return next(list);
+ }
+ const theLastMutation = list[list.length - 1];
+ const theFirstMutation = current[0];
+ if (theLastMutation.id === SetNumfmtMutation.id && theFirstMutation.id === SetNumfmtMutation.id) {
+ const theLastMutationParams = theLastMutation.params as ISetNumfmtMutationParams;
+ const theFirstMutationParams = theFirstMutation.params as ISetNumfmtMutationParams;
+ if (
+ theLastMutationParams.workbookId === theFirstMutationParams.workbookId &&
+ theLastMutationParams.worksheetId === theFirstMutationParams.worksheetId
+ ) {
+ const values = theLastMutationParams.values;
+ current.forEach((mutation) => {
+ const params = mutation.params as ISetNumfmtMutationParams;
+ params.values.forEach((item) => {
+ values.push(item);
+ });
+ });
+ return list;
+ }
+ }
+ return next(list);
+ },
+ })
+ );
}
private _registerRefRange() {
@@ -193,7 +226,8 @@ export class NumfmtRefRangeController extends Disposable {
}
return { redos: [], undos: [] };
};
- if (model) {
+
+ model &&
model.forValue((row, col) => {
const targetRange = {
startRow: row,
@@ -208,7 +242,6 @@ export class NumfmtRefRangeController extends Disposable {
disposableMap.set(`${row}_${col}`, disposable);
disposableCollection.add(disposable);
});
- }
// on change
disposableCollection.add(