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(rangeMerge): supprt range merge (#707)

Gpound.liu6dc623c8e43d
diff --git a/packages/sheets-numfmt/src/__tests__/utils.test.ts b/packages/sheets-numfmt/src/__tests__/utils.test.ts
index f68015cfe1..952e567b4b 100644
--- a/packages/sheets-numfmt/src/__tests__/utils.test.ts
+++ b/packages/sheets-numfmt/src/__tests__/utils.test.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import type { IRange } from '@univerjs/core';
+import { RemoveNumfmtMutation, SetNumfmtMutation } from '@univerjs/sheets';
import { describe, expect, it } from 'vitest';
import { currencySymbols } from '../base/const/CURRENCY-SYMBOLS';
@@ -24,7 +26,10 @@ import {
isPatternEqualWithoutDecimal,
setPatternDecimal,
} from '../utils/decimal';
+import { mergeNumfmtMutations } from '../utils/mutation';
+const cellToRange = (row: number, col: number) =>
+ ({ startRow: row, endRow: row, startColumn: col, endColumn: col }) as IRange;
describe('test numfmt utils function', () => {
it('getCurrencyType', () => {
expect(getCurrencyType(`_(${currencySymbols[3]} 123123`)).toBe(currencySymbols[3]);
@@ -54,4 +59,64 @@ describe('test numfmt utils function', () => {
expect(setPatternDecimal('0.0', 4)).toBe('0.0000'); // the positive color ignored
expect(setPatternDecimal('0.0', 0)).toBe('0'); // the positive color ignored
});
+
+ it('mergeNumfmtMutations', () => {
+ const result = mergeNumfmtMutations([
+ {
+ id: SetNumfmtMutation.id,
+ params: {
+ values: {
+ a: { ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)] },
+ },
+ refMap: { a: { pattern: '', type: '' } },
+ },
+ },
+ {
+ id: RemoveNumfmtMutation.id,
+ params: {
+ ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)],
+ },
+ },
+ {
+ id: SetNumfmtMutation.id,
+ params: {
+ values: {
+ a: { ranges: [cellToRange(4, 6), cellToRange(4, 5)] },
+ },
+ refMap: { a: { pattern: '', type: '' } },
+ },
+ },
+ ]);
+
+ expect(result[0].id === RemoveNumfmtMutation.id).toBeTruthy();
+ expect(result[1].id === SetNumfmtMutation.id).toBeTruthy();
+ expect((result as any)[0].params.ranges).toEqual([
+ {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 4,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 5,
+ },
+ ]);
+ expect((result as any)[1].params.values.a.ranges).toEqual([
+ {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 4,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 6,
+ },
+ ]);
+ });
});
diff --git a/packages/sheets-numfmt/src/commands/commands/set.numfmt.command.ts b/packages/sheets-numfmt/src/commands/commands/set.numfmt.command.ts
index 28d44ac848..3ec519418b 100644
--- a/packages/sheets-numfmt/src/commands/commands/set.numfmt.command.ts
+++ b/packages/sheets-numfmt/src/commands/commands/set.numfmt.command.ts
@@ -31,6 +31,7 @@ import type {
import {
factoryRemoveNumfmtUndoMutation,
factorySetNumfmtUndoMutation,
+ rangeMerge,
RemoveNumfmtMutation,
SetNumfmtMutation,
transformCellsToRange,
@@ -72,6 +73,10 @@ export const SetNumfmtCommand: ICommand<ISetNumfmtCommandParams> = {
const redos: Array<IMutationInfo<IRemoveNumfmtMutationParams | ISetNumfmtMutationParams>> = [];
const undos: Array<IMutationInfo<IRemoveNumfmtMutationParams | ISetNumfmtMutationParams>> = [];
if (setCells.length) {
+ Object.keys(setRedos.values).forEach((key) => {
+ const v = setRedos.values[key];
+ v.ranges = rangeMerge(v.ranges);
+ });
redos.push({
id: SetNumfmtMutation.id,
params: setRedos,
@@ -80,6 +85,7 @@ export const SetNumfmtCommand: ICommand<ISetNumfmtCommandParams> = {
undos.push(...undo);
}
if (removeCells.length) {
+ removeRedos.ranges = rangeMerge(removeRedos.ranges);
redos.push({
id: RemoveNumfmtMutation.id,
params: removeRedos,
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts
index 489d2b3dc7..ff460fc4e7 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts
@@ -28,6 +28,7 @@ import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService } from '@univerjs/
import { Inject, Injector } from '@wendellhu/redi';
import { SHEET_NUMFMT_PLUGIN } from '../base/const/PLUGIN_NAME';
+import { mergeNumfmtMutations } from '../utils/mutation';
@OnLifecycle(LifecycleStages.Rendered, NumfmtAutoFillController)
export class NumfmtAutoFillController extends Disposable {
@@ -130,8 +131,8 @@ export class NumfmtAutoFillController extends Disposable {
totalRedos.push(...redos);
});
return {
- undos: totalUndos,
- redos: totalRedos,
+ undos: mergeNumfmtMutations(totalUndos),
+ redos: mergeNumfmtMutations(totalRedos),
};
};
const hook: IAutoFillHook = {
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
index 7333718cb2..3efad96b48 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts
@@ -37,6 +37,8 @@ import {
factoryRemoveNumfmtUndoMutation,
INTERCEPTOR_POINT,
INumfmtService,
+ rangeMerge,
+ RemoveNumfmtMutation,
SelectionManagerService,
SetNumfmtMutation,
SheetInterceptorService,
@@ -227,9 +229,10 @@ export class NumfmtController extends Disposable implements INumfmtController {
redos.ranges.push({ startColumn: col, endColumn: col, startRow: row, endRow: row });
});
});
+ redos.ranges = rangeMerge(redos.ranges);
const undos = factoryRemoveNumfmtUndoMutation(self._injector, redos);
return {
- redos: [{ id: SetNumfmtMutation.id, params: redos }],
+ redos: [{ id: RemoveNumfmtMutation.id, params: redos }],
undos,
};
}
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts
index 0bfdfbfcd2..a050e63422 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts
@@ -29,6 +29,7 @@ import {
factoryRemoveNumfmtUndoMutation,
factorySetNumfmtUndoMutation,
INumfmtService,
+ rangeMerge,
RemoveNumfmtMutation,
SetNumfmtMutation,
transformCellsToRange,
@@ -151,6 +152,13 @@ export class NumfmtCopyPasteController extends Disposable {
});
});
const setRedos = transformCellsToRange(workbookId, worksheetId, cells);
+
+ Object.keys(setRedos.values).forEach((key) => {
+ const v = setRedos.values[key];
+ v.ranges = rangeMerge(v.ranges);
+ });
+
+ removeRedos.ranges = rangeMerge(removeRedos.ranges);
const undos = [
...factorySetNumfmtUndoMutation(this._injector, setRedos),
...factoryRemoveNumfmtUndoMutation(this._injector, removeRedos),
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.ref-range.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.ref-range.controller.ts
index 84f9044a31..8a6c803862 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.ref-range.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.ref-range.controller.ts
@@ -46,6 +46,7 @@ import {
handleIRemoveRow,
handleMoveRange,
INumfmtService,
+ rangeMerge,
RefRangeService,
RemoveNumfmtMutation,
runRefRangeMutations,
@@ -58,6 +59,8 @@ import { Inject, Injector } from '@wendellhu/redi';
import { merge, Observable } from 'rxjs';
import { bufferTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
+import { mergeNumfmtMutations } from '../utils/mutation';
+
const numfmtMutation = [SetNumfmtMutation.id, RemoveNumfmtMutation.id];
@OnLifecycle(LifecycleStages.Rendered, NumfmtRefRangeController)
export class NumfmtRefRangeController extends Disposable {
@@ -125,7 +128,7 @@ export class NumfmtRefRangeController extends Disposable {
const id = `${index + 1}`;
const item = patternMap[key];
refMap[id] = { pattern: item.pattern, type: item.type };
- values[id] = { ranges: item.ranges };
+ values[id] = { ranges: rangeMerge(item.ranges) };
});
return {
...firstOne,
@@ -145,63 +148,21 @@ export class NumfmtRefRangeController extends Disposable {
const firstOne = list[0];
return {
...firstOne,
- ranges,
+ ranges: rangeMerge(ranges),
};
}
private _mergeRefMutations() {
this._refRangeService.interceptor.intercept(this._refRangeService.interceptor.getInterceptPoints().MERGE_REDO, {
handler: (list, _c, next) => {
- const result = list?.filter((item) => !numfmtMutation.includes(item.id)) || [];
- const numfmtSetMutation = (list?.filter((item) => item.id === SetNumfmtMutation.id) || []).map(
- (item) => item.params
- ) as unknown as ISetNumfmtMutationParams[];
- const numfmtRemoveMutation = (list?.filter((item) => item.id === RemoveNumfmtMutation.id) || []).map(
- (item) => item.params
- ) as unknown as IRemoveNumfmtMutationParams[];
-
- if (numfmtRemoveMutation.length) {
- const params = this._mergeNumfmtRemoveMutation(numfmtRemoveMutation);
- result.push({ id: RemoveNumfmtMutation.id, params });
- }
- if (numfmtSetMutation.length) {
- const params = this._mergeNumfmtSetMutation(numfmtSetMutation);
- result.push({ id: SetNumfmtMutation.id, params });
+ if (!list) {
+ return next(list);
}
+ const result = list.filter((item) => !numfmtMutation.includes(item.id));
+ result.push(...mergeNumfmtMutations(list));
return next(result);
},
});
- // 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;
- // Object.keys(params.values).forEach((id) => {
- // if (values[id]) {
- // values[id].ranges.push(...params.values[id].ranges);
- // }
- // });
- // });
- // return list;
- // }
- // }
- // return next(list);
- // },
- // })
- // );
}
private _registerRefRange() {
@@ -235,12 +196,7 @@ export class NumfmtRefRangeController extends Disposable {
.getSheetId();
const model = this._numfmtService.getModel(workbookId, worksheetId);
const disposableMap: Map<string, IDisposable> = new Map();
- const register = (
- commandInfo: EffectRefRangeParams,
- preValues: Array<{ redos: IMutationInfo[]; undos: IMutationInfo[] }>,
- row: number,
- col: number
- ) => {
+ const register = (commandInfo: EffectRefRangeParams, row: number, col: number) => {
const targetRange = {
startRow: row,
startColumn: col,
@@ -353,9 +309,8 @@ export class NumfmtRefRangeController extends Disposable {
endRow: row,
endColumn: col,
};
- const disposable = this._refRangeService.registerRefRange(
- targetRange,
- (commandInfo, preValues) => register(commandInfo, preValues, row, col)
+ const disposable = this._refRangeService.registerRefRange(targetRange, (commandInfo) =>
+ register(commandInfo, row, col)
);
disposableMap.set(`${row}_${col}`, disposable);
disposableCollection.add(disposable);
@@ -425,8 +380,7 @@ export class NumfmtRefRangeController extends Disposable {
};
const disposable = this._refRangeService.registerRefRange(
targetRange,
- (commandInfo, preValues) =>
- register(commandInfo, preValues, row, col)
+ (commandInfo) => register(commandInfo, row, col)
);
disposableMap.set(key, disposable);
disposableCollection.add(disposable);
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.sheet.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.sheet.controller.ts
index 01ee02ebdd..5c5d12404b 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.sheet.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.sheet.controller.ts
@@ -20,6 +20,7 @@ import type { IRemoveNumfmtMutationParams, IRemoveSheetCommandParams } from '@un
import {
factoryRemoveNumfmtUndoMutation,
INumfmtService,
+ rangeMerge,
RemoveNumfmtMutation,
RemoveSheetCommand,
SheetInterceptorService,
@@ -57,7 +58,7 @@ export class NumfmtSheetController extends Disposable {
const redoParams: IRemoveNumfmtMutationParams = {
workbookId,
worksheetId,
- ranges,
+ ranges: rangeMerge(ranges),
};
const undoParams = factoryRemoveNumfmtUndoMutation(this._injector, redoParams);
return {
diff --git a/packages/sheets-numfmt/src/utils/mutation.ts b/packages/sheets-numfmt/src/utils/mutation.ts
new file mode 100644
index 0000000000..03f58a2340
--- /dev/null
+++ b/packages/sheets-numfmt/src/utils/mutation.ts
@@ -0,0 +1,76 @@
+/**
+ * Copyright 2023 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 type { IMutationInfo } from '@univerjs/core';
+import type { IRemoveNumfmtMutationParams, ISetNumfmtMutationParams } from '@univerjs/sheets';
+import { rangeMerge, RemoveNumfmtMutation, SetNumfmtMutation } from '@univerjs/sheets';
+
+export const mergeNumfmtMutations = (list: IMutationInfo[]) => {
+ const removeMutation = list
+ .filter((item) => item.id === RemoveNumfmtMutation.id)
+ .map((item) => item.params) as unknown as IRemoveNumfmtMutationParams[];
+ const setMutation = list
+ .filter((item) => item.id === SetNumfmtMutation.id)
+ .map((item) => item.params) as unknown as ISetNumfmtMutationParams[];
+ const result: IMutationInfo[] = [];
+
+ if (removeMutation[0]) {
+ const params = removeMutation.reduce(
+ (res, cur) => {
+ res.ranges.push(...cur.ranges);
+ return res;
+ },
+ {
+ ranges: [],
+ workbookId: setMutation[0].workbookId,
+ worksheetId: setMutation[0].worksheetId,
+ } as IRemoveNumfmtMutationParams
+ );
+ params.ranges = rangeMerge(params.ranges);
+ result.push({ id: RemoveNumfmtMutation.id, params });
+ }
+ if (setMutation[0]) {
+ const params = setMutation.reduce(
+ (res, cur) => {
+ Object.keys(cur.values).forEach((key) => {
+ const curValue = cur.values[key];
+ const curRef = cur.refMap[key];
+ if (res.values[key]) {
+ res.values[key].ranges.push(...curValue.ranges);
+ } else {
+ res.values[key] = {
+ ranges: curValue.ranges,
+ };
+ res.refMap[key] = curRef;
+ }
+ });
+ return res;
+ },
+ {
+ values: {},
+ refMap: {},
+ workbookId: setMutation[0].workbookId,
+ worksheetId: setMutation[0].worksheetId,
+ } as ISetNumfmtMutationParams
+ );
+ Object.keys(params.values).forEach((key) => {
+ const v = params.values[key];
+ v.ranges = rangeMerge(v.ranges);
+ });
+ result.push({ id: SetNumfmtMutation.id, params });
+ }
+ return result;
+};
diff --git a/packages/sheets/src/basics/__tests__/rangeMerge.spec.ts b/packages/sheets/src/basics/__tests__/rangeMerge.spec.ts
new file mode 100644
index 0000000000..83923c8dfa
--- /dev/null
+++ b/packages/sheets/src/basics/__tests__/rangeMerge.spec.ts
@@ -0,0 +1,201 @@
+/**
+ * Copyright 2023 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 type { IRange } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+
+import { rangeMerge } from '../rangeMerge';
+
+const cellToRange = (row: number, col: number) =>
+ ({ startColumn: col, endColumn: col, endRow: row, startRow: row }) as IRange;
+describe('test rangeMerge', () => {
+ it('simple row', () => {
+ const testRange: IRange[] = [cellToRange(2, 2), cellToRange(3, 2), cellToRange(4, 2)];
+ const result = rangeMerge(testRange);
+ expect(result).toEqual([{ startColumn: 2, endColumn: 2, startRow: 2, endRow: 4 }] as IRange[]);
+ });
+ it('simple col', () => {
+ const testRange: IRange[] = [cellToRange(2, 2), cellToRange(2, 3), cellToRange(2, 4)];
+ const result = rangeMerge(testRange);
+ expect(result).toEqual([{ startColumn: 2, endColumn: 4, startRow: 2, endRow: 2 }] as IRange[]);
+ });
+
+ it('simple col and simple row', () => {
+ const testRange: IRange[] = [
+ cellToRange(2, 2),
+ cellToRange(2, 3),
+ cellToRange(2, 4),
+ cellToRange(2, 2),
+ cellToRange(3, 2),
+ cellToRange(4, 2),
+ ];
+ const result = rangeMerge(testRange);
+ expect(result).toEqual([
+ { startColumn: 2, endColumn: 4, startRow: 2, endRow: 2 },
+ { startColumn: 2, endColumn: 2, startRow: 3, endRow: 4 },
+ ] as IRange[]);
+ });
+
+ it('multiple range', () => {
+ const testRange1 = rangeMerge([cellToRange(2, 2), cellToRange(2, 3), cellToRange(2, 4)]);
+ const testRange2 = rangeMerge([cellToRange(3, 2), cellToRange(3, 3), cellToRange(3, 4)]);
+ const testRange3 = rangeMerge([cellToRange(4, 5), cellToRange(4, 6), cellToRange(4, 7)]);
+ //1 1 1
+ //2 2 2
+ //0 0 0 1 1 1
+ const result = rangeMerge([...testRange1, ...testRange3, ...testRange2]);
+ expect(result).toEqual([
+ {
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 4,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 7,
+ },
+ ]);
+ //1 1 1 1
+ //2 2 2 1
+ //0 0 0 1 1 1
+ const result2 = rangeMerge([...testRange1, ...testRange3, ...testRange2, cellToRange(2, 5), cellToRange(3, 5)]);
+ expect(result2).toEqual([
+ {
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 5,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 7,
+ },
+ ]);
+ //0 0 0 0 0 0
+ //0 0 0 0 0 0
+ //0 0 1 1 1 1
+ //0 0 2 0 2 2
+ //0 0 0 0 3 3 1 1
+ const result3 = rangeMerge([
+ cellToRange(2, 2),
+ cellToRange(2, 3),
+ cellToRange(2, 4),
+ cellToRange(2, 5),
+ cellToRange(3, 2),
+ cellToRange(3, 4),
+ cellToRange(3, 5),
+ cellToRange(4, 4),
+ cellToRange(4, 5),
+ cellToRange(4, 6),
+ cellToRange(4, 7),
+ ]);
+ expect(result3).toEqual([
+ {
+ startRow: 2,
+ endRow: 4,
+ startColumn: 4,
+ endColumn: 5,
+ },
+ {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 2,
+ endColumn: 3,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 6,
+ endColumn: 7,
+ },
+ {
+ startRow: 3,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 2,
+ },
+ ]);
+ });
+
+ it('hollow range', () => {
+ const result = rangeMerge([
+ { startRow: 2, endRow: 3, startColumn: 2, endColumn: 10 },
+ { startRow: 4, endRow: 6, startColumn: 2, endColumn: 4 },
+ { startRow: 4, endRow: 6, startColumn: 8, endColumn: 10 },
+ { startRow: 7, endRow: 10, startColumn: 2, endColumn: 10 },
+ ]);
+ console.log(JSON.stringify(result, null, 2));
+ expect(result).toEqual([
+ {
+ startRow: 7,
+ endRow: 10,
+ startColumn: 2,
+ endColumn: 10,
+ },
+ {
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 10,
+ },
+ {
+ startRow: 4,
+ endRow: 6,
+ startColumn: 2,
+ endColumn: 4,
+ },
+ {
+ startRow: 4,
+ endRow: 6,
+ startColumn: 8,
+ endColumn: 10,
+ },
+ ]);
+ });
+
+ // it('performance 10 rows and 250 columns', () => {
+ // // column sparse matrices have better performance
+ // const now = performance.now();
+ // rangeMerge([{ startRow: 0, endRow: 10, startColumn: 0, endColumn: 250 }]);
+ // const end = performance.now();
+ // const result = end - now;
+ // console.log(result, ':ms');
+ // expect(result).toBeLessThanOrEqual(5000); // 4002
+ // });
+
+ // it('performance 100 rows and 100 columns', () => {
+ // const now = performance.now();
+ // rangeMerge([{ startRow: 0, endRow: 100, startColumn: 0, endColumn: 100 }]);
+ // const end = performance.now();
+ // const result = end - now;
+ // console.log(result, ':ms');
+ // expect(result).toBeLessThanOrEqual(5000); // 4640
+ // });
+
+ // it('performance 1000 rows and 10 columns', () => {
+ // const now = performance.now();
+ // rangeMerge([{ startRow: 0, endRow: 1000, startColumn: 0, endColumn: 10 }]);
+ // const end = performance.now();
+ // const result = end - now;
+ // console.log(result, ':ms');
+ // expect(result).toBeLessThanOrEqual(4000); // 3483
+ // });
+});
diff --git a/packages/sheets/src/basics/rangeMerge.ts b/packages/sheets/src/basics/rangeMerge.ts
new file mode 100644
index 0000000000..71d9325e09
--- /dev/null
+++ b/packages/sheets/src/basics/rangeMerge.ts
@@ -0,0 +1,118 @@
+/**
+ * Copyright 2023 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 type { IRange } from '@univerjs/core';
+import { ObjectMatrix, Range } from '@univerjs/core';
+
+const createTopMatrix = (ranges: IRange[]) => {
+ const matrix = new ObjectMatrix<number>();
+ ranges.forEach((range) => {
+ Range.foreach(range, (row, col) => {
+ matrix.setValue(row, col, 1);
+ });
+ });
+ matrix.forValue((row, col) => {
+ const theLastRowValue = matrix.getValue(row - 1, col);
+ if (theLastRowValue) {
+ matrix.setValue(row, col, theLastRowValue + 1);
+ }
+ });
+ return matrix;
+};
+const findMaximalRectangle = (topMatrix: ObjectMatrix<number>) => {
+ const res: {
+ area: number;
+ range?: IRange;
+ } = {
+ area: 0,
+ };
+ const checkArea = (area: number, range: IRange) => {
+ if (res.area < area) {
+ res.area = area;
+ res.range = range;
+ return true;
+ }
+ return false;
+ };
+
+ topMatrix.forValue((row, col, lineArea) => {
+ let cols = 1;
+ let rows = lineArea;
+ checkArea(cols * rows, {
+ startRow: row - rows + 1,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ });
+ const _range = {
+ startRow: row - rows + 1,
+ endRow: row,
+ startColumn: 0,
+ endColumn: col,
+ };
+ for (let k = col - 1; k >= 0; k--) {
+ if (!topMatrix.getValue(row, k)) break;
+ else {
+ rows = Math.min(topMatrix.getValue(row, k) || 0, rows);
+ cols++;
+ const area = rows * cols;
+ _range.startColumn = k;
+ _range.startRow = row - rows + 1;
+ checkArea(area, _range);
+ }
+ }
+ });
+ return res;
+};
+
+const filterLeftMatrix = (topMatrix: ObjectMatrix<number>, range: IRange) => {
+ Range.foreach(range, (row, col) => {
+ topMatrix.realDeleteValue(row, col);
+ let theNextRow = row + 1;
+ let theNextRowValue = topMatrix.getValue(theNextRow, col) || 0;
+ while (theNextRowValue > 1) {
+ topMatrix.setValue(theNextRow, col, theNextRowValue - 1);
+ theNextRow += 1;
+ theNextRowValue = topMatrix.getValue(theNextRow, col) || 0;
+ }
+ });
+ return topMatrix;
+};
+
+const findAllRectangle = (topMatrix: ObjectMatrix<number>) => {
+ const resultList = [];
+ let result = findMaximalRectangle(topMatrix);
+ while (result.area > 0) {
+ if (result.range) {
+ resultList.push(result.range);
+ filterLeftMatrix(topMatrix, result.range);
+ }
+ result = findMaximalRectangle(topMatrix);
+ }
+ return resultList;
+};
+
+/**
+ * Some operations generate sparse ranges such as paste/autofill/ref-range, and this function merge some small ranges into some large ranges to reduce transmission size.
+ * Time Complexity: O(mn) , where m and n are rows and columns. It takes O(mn) to compute the markMatrix and O(n) to apply the histogram algorithm to each column.
+ * ps. column sparse matrices have better performance
+ * @param {IRange[]} ranges
+ * @returns {IRange[]}
+ */
+export const rangeMerge = (ranges: IRange[]) => {
+ const topMatrix = createTopMatrix(ranges);
+ return findAllRectangle(topMatrix);
+};
diff --git a/packages/sheets/src/commands/mutations/numfmt-mutation.ts b/packages/sheets/src/commands/mutations/numfmt-mutation.ts
index a60ac83673..a2f6af17e2 100644
--- a/packages/sheets/src/commands/mutations/numfmt-mutation.ts
+++ b/packages/sheets/src/commands/mutations/numfmt-mutation.ts
@@ -18,6 +18,7 @@ import type { ICommand, IMutationInfo, IRange } from '@univerjs/core';
import { CommandType, Range } from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
+import { rangeMerge } from '../../basics/rangeMerge';
import { createUniqueKey, groupByKey } from '../../basics/utils';
import type { FormatType } from '../../services/numfmt/type';
import { INumfmtService } from '../../services/numfmt/type';
@@ -48,6 +49,11 @@ export const factorySetNumfmtUndoMutation = (accessor: IAccessor, option: ISetNu
});
const result: Array<IMutationInfo<ISetNumfmtMutationParams | IRemoveNumfmtMutationParams>> = [];
if (cells) {
+ const params = transformCellsToRange(workbookId, worksheetId, cells);
+ Object.keys(params.values).forEach((key) => {
+ const v = params.values[key];
+ v.ranges = rangeMerge(v.ranges);
+ });
result.push({
id: SetNumfmtMutation.id,
params: transformCellsToRange(workbookId, worksheetId, cells),
@@ -148,7 +154,12 @@ export const factoryRemoveNumfmtUndoMutation = (accessor: IAccessor, option: IRe
}
});
});
- return [{ id: SetNumfmtMutation.id, params: transformCellsToRange(workbookId, worksheetId, cells) }];
+ const params = transformCellsToRange(workbookId, worksheetId, cells);
+ Object.keys(params.values).forEach((key) => {
+ const v = params.values[key];
+ v.ranges = rangeMerge(v.ranges);
+ });
+ return [{ id: SetNumfmtMutation.id, params }];
};
export type ISetCellsNumfmt = Array<{ pattern: string; type: FormatType; row: number; col: number }>;
export const transformCellsToRange = (
@@ -174,7 +185,6 @@ export const transformCellsToRange = (
}
values[key].ranges.push(cellToRange(item.row, item.col));
});
- // TODO@gggpound: ranges to be merge.
});
return { workbookId, worksheetId, refMap, values };
};
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index db1360ae9a..39e84813a0 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -62,6 +62,7 @@ export {
// #region commands
+export { rangeMerge } from './basics/rangeMerge';
export { ClearSelectionAllCommand } from './commands/commands/clear-selection-all.command';
export { ClearSelectionContentCommand } from './commands/commands/clear-selection-content.command';
export { ClearSelectionFormatCommand } from './commands/commands/clear-selection-format.command';
diff --git a/packages/sheets/src/services/ref-range/ref-range.service.ts b/packages/sheets/src/services/ref-range/ref-range.service.ts
index efda80b319..b870f5518f 100644
--- a/packages/sheets/src/services/ref-range/ref-range.service.ts
+++ b/packages/sheets/src/services/ref-range/ref-range.service.ts
@@ -33,10 +33,7 @@ import { SheetInterceptorService } from '../sheet-interceptor/sheet-interceptor.
import type { EffectRefRangeParams } from './type';
import { EffectRefRangId } from './type';
-type RefRangCallback = (
- params: EffectRefRangeParams,
- preValues: Array<{ redos: IMutationInfo[]; undos: IMutationInfo[] }>
-) => {
+type RefRangCallback = (params: EffectRefRangeParams) => {
redos: IMutationInfo[];
undos: IMutationInfo[];
};
@@ -163,7 +160,7 @@ export class RefRangeService extends Disposable {
const result = cbList
.reduce(
(result, currentFn) => {
- const v = currentFn(command, result);
+ const v = currentFn(command);
result.push(v);
return result;
},