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
feat(numfmt): reduce mutation transmission size (#685)
Gpound.liu312153f143c1
diff --git a/examples/sheets/src/main.ts b/examples/sheets/src/main.tsindex 4b1a6c9b0d..6c46f0d382 100644--- a/examples/sheets/src/main.ts+++ b/examples/sheets/src/main.ts@@ -7,7 +7,7 @@ import type { IUniverRPCMainThreadPluginConfig } from '@univerjs/rpc';import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';import { SheetsPlugin } from '@univerjs/sheets';import { FormulaUIPlugin } from '@univerjs/sheets-formula';-import { NumfmtPlugin } from '@univerjs/sheets-numfmt';+import { SheetsNumfmt } from '@univerjs/sheets-numfmt';import { SheetsUIPlugin } from '@univerjs/sheets-ui';import { UIPlugin } from '@univerjs/ui';import type { IUniscriptPluginConfig } from '@univerjs/uniscript';@@ -51,7 +51,7 @@ univer.registerPlugin(SheetsUIPlugin);// sheet feature plugins-univer.registerPlugin(NumfmtPlugin);+univer.registerPlugin(SheetsNumfmt);univer.registerPlugin(DebuggerPlugin);univer.registerPlugin(BaseFormulaEnginePlugin, {notExecuteFormula: true,diff --git a/packages/sheets-numfmt/src/commands/commands/set.numfmt.command.ts b/packages/sheets-numfmt/src/commands/commands/set.numfmt.command.tsindex 21f010e329..43c757352c 100644--- a/packages/sheets-numfmt/src/commands/commands/set.numfmt.command.ts+++ b/packages/sheets-numfmt/src/commands/commands/set.numfmt.command.ts@@ -1,7 +1,24 @@-import type { ICommand } from '@univerjs/core';-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';-import type { FormatType } from '@univerjs/sheets';-import { factorySetNumfmtUndoMutation, SetNumfmtMutation } from '@univerjs/sheets';+import type { ICommand, IMutationInfo } from '@univerjs/core';+import {+ CommandType,+ ICommandService,+ IUndoRedoService,+ IUniverInstanceService,+ sequenceExecute,+} from '@univerjs/core';+import type {+ FormatType,+ IRemoveNumfmtMutationParams,+ ISetCellsNumfmt,+ ISetNumfmtMutationParams,+} from '@univerjs/sheets';+import {+ factoryRemoveNumfmtUndoMutation,+ factorySetNumfmtUndoMutation,+ RemoveNumfmtMutation,+ SetNumfmtMutation,+ transformCellsToRange,+} from '@univerjs/sheets';import type { IAccessor } from '@wendellhu/redi';export interface ISetNumfmtCommandParams {@@ -23,14 +40,44 @@ export const SetNumfmtCommand: ICommand<ISetNumfmtCommandParams> = {const workbookId = workbook.getUnitId();const worksheet = workbook.getActiveSheet();const worksheetId = worksheet.getSheetId();- const redoOption = { ...params, workbookId, worksheetId };- const undoOption = factorySetNumfmtUndoMutation(accessor, redoOption);- const result = commandService.syncExecuteCommand(SetNumfmtMutation.id, redoOption);+ const setCells = params.values.filter((value) => !!value.pattern) as ISetCellsNumfmt;+ const removeCells = params.values.filter((value) => !value.pattern);+ const setRedos = transformCellsToRange(workbookId, worksheetId, setCells);+ const removeRedos: IRemoveNumfmtMutationParams = {+ workbookId,+ worksheetId,+ ranges: removeCells.map((cell) => ({+ startColumn: cell.col,+ startRow: cell.row,+ endColumn: cell.col,+ endRow: cell.row,+ })),+ };+ const redos: Array<IMutationInfo<IRemoveNumfmtMutationParams | ISetNumfmtMutationParams>> = [];+ const undos: Array<IMutationInfo<IRemoveNumfmtMutationParams | ISetNumfmtMutationParams>> = [];+ if (setCells.length) {+ redos.push({+ id: SetNumfmtMutation.id,+ params: setRedos,+ });+ const undo = factorySetNumfmtUndoMutation(accessor, setRedos);+ undos.push(...undo);+ }+ if (removeCells.length) {+ redos.push({+ id: RemoveNumfmtMutation.id,+ params: removeRedos,+ });+ const undo = factoryRemoveNumfmtUndoMutation(accessor, removeRedos);+ undos.push(...undo);+ }++ const result = sequenceExecute(redos, commandService).result;if (result) {undoRedoService.pushUndoRedo({unitID: workbookId,- undoMutations: [{ id: SetNumfmtMutation.id, params: undoOption }],- redoMutations: [{ id: SetNumfmtMutation.id, params: redoOption }],+ undoMutations: undos,+ redoMutations: redos,});}return result;diff --git a/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.tsindex d55ab8bac9..682129bbc6 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.auto-fill.controller.ts@@ -1,7 +1,12 @@import type { IMutationInfo, IRange } from '@univerjs/core';import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, Range, Rectangle } from '@univerjs/core';-import type { ISetNumfmtMutationParams } from '@univerjs/sheets';-import { factorySetNumfmtUndoMutation, INumfmtService, SetNumfmtMutation } from '@univerjs/sheets';+import type { ISetCellsNumfmt, ISetNumfmtMutationParams } from '@univerjs/sheets';+import {+ factorySetNumfmtUndoMutation,+ INumfmtService,+ SetNumfmtMutation,+ transformCellsToRange,+} from '@univerjs/sheets';import type { IAutoFillHook } from '@univerjs/sheets-ui';import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService } from '@univerjs/sheets-ui';import { Inject, Injector } from '@wendellhu/redi';@@ -46,7 +51,7 @@ export class NumfmtAutoFillController extends Disposable {endRow: targetStartCell.row,};- const values: ISetNumfmtMutationParams['values'] = [];+ const values: ISetCellsNumfmt = [];Range.foreach(relativeRange, (row, col) => {const sourcePositionRange = Rectangle.getPositionRange(@@ -85,23 +90,12 @@ export class NumfmtAutoFillController extends Disposable {if (values.length) {const redo: IMutationInfo<ISetNumfmtMutationParams> = {id: SetNumfmtMutation.id,- params: {- values,- workbookId,- worksheetId,- },- };- const undo = {- id: SetNumfmtMutation.id,- params: {- values: factorySetNumfmtUndoMutation(this._injector, redo.params),- workbookId,- worksheetId,- },+ params: transformCellsToRange(workbookId, worksheetId, values),};+ const undos = factorySetNumfmtUndoMutation(this._injector, redo.params);return {redos: [redo],- undos: [undo],+ undos,};}return { redos: [], undos: [] };diff --git a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.controller.tsindex 4f1ded8544..fd09d9ba21 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.controller.ts@@ -15,11 +15,11 @@ import {toDisposable,} from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';-import type { ISetNumfmtMutationParams } from '@univerjs/sheets';+import type { IRemoveNumfmtMutationParams, ISetNumfmtMutationParams } from '@univerjs/sheets';import {ClearSelectionAllCommand,ClearSelectionFormatCommand,- factorySetNumfmtUndoMutation,+ factoryRemoveNumfmtUndoMutation,INTERCEPTOR_POINT,INumfmtService,SelectionManagerService,@@ -202,23 +202,20 @@ export class NumfmtController extends Disposable implements INumfmtController {if (!selections?.length) {break;}- const redos: ISetNumfmtMutationParams = {+ const redos: IRemoveNumfmtMutationParams = {workbookId,worksheetId,- values: [],+ ranges: [],};selections.forEach((range) => {Range.foreach(range, (row, col) => {- redos.values.push({- row,- col,- });+ redos.ranges.push({ startColumn: col, endColumn: col, startRow: row, endRow: row });});});- const undos = factorySetNumfmtUndoMutation(self._injector, redos);+ const undos = factoryRemoveNumfmtUndoMutation(self._injector, redos);return {redos: [{ id: SetNumfmtMutation.id, params: redos }],- undos: [{ id: SetNumfmtMutation.id, params: undos }],+ undos,};}}@@ -288,11 +285,14 @@ export class NumfmtController extends Disposable implements INumfmtController {this._commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === SetNumfmtMutation.id) {const params = commandInfo.params as ISetNumfmtMutationParams;- params.values- .map((value) => ({ row: value.row, col: value.col }))- .forEach(({ row, col }) => {- renderCache.realDeleteValue(row, col);+ Object.keys(params.values).forEach((key) => {+ const v = params.values[key];+ v.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ renderCache.realDeleteValue(row, col);+ });});+ });}}));diff --git a/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.tsindex 9798577028..3f136df9a7 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts@@ -8,8 +8,15 @@ import {Range,Rectangle,} from '@univerjs/core';-import type { FormatType, ISetNumfmtMutationParams } from '@univerjs/sheets';-import { factorySetNumfmtUndoMutation, INumfmtService, SetNumfmtMutation } from '@univerjs/sheets';+import type { FormatType, IRemoveNumfmtMutationParams, ISetCellsNumfmt } from '@univerjs/sheets';+import {+ factoryRemoveNumfmtUndoMutation,+ factorySetNumfmtUndoMutation,+ INumfmtService,+ RemoveNumfmtMutation,+ SetNumfmtMutation,+ transformCellsToRange,+} from '@univerjs/sheets';import { COPY_TYPE, getRepeatRange, ISheetClipboardService } from '@univerjs/sheets-ui';import { Inject, Injector } from '@wendellhu/redi';@@ -100,12 +107,11 @@ export class NumfmtCopyPasteController extends Disposable {}const repeatRange = getRepeatRange(copyInfo.copyRange, pastedRange, true);- const redos: ISetNumfmtMutationParams = { workbookId, worksheetId, values: [] };+ const cells: ISetCellsNumfmt = [];+ const removeRedos: IRemoveNumfmtMutationParams = { workbookId, worksheetId, ranges: [] };// Clears the destination area data format- Range.foreach(pastedRange, (row, col) => {- redos.values.push({ row, col });- });+ removeRedos.ranges.push(pastedRange);// Set up according to the data collected. This will overlap with the cleanup, but that's okayrepeatRange.forEach((item) => {@@ -120,7 +126,7 @@ export class NumfmtCopyPasteController extends Disposable {},item.startRange);- redos.values.push({+ cells.push({row: range.startRow,col: range.startColumn,pattern: value.pattern,@@ -128,12 +134,18 @@ export class NumfmtCopyPasteController extends Disposable {});});});-- const undos: ISetNumfmtMutationParams = factorySetNumfmtUndoMutation(this._injector, redos);+ const setRedos = transformCellsToRange(workbookId, worksheetId, cells);+ const undos = [+ ...factorySetNumfmtUndoMutation(this._injector, setRedos),+ ...factoryRemoveNumfmtUndoMutation(this._injector, removeRedos),+ ];return {- redos: [{ id: SetNumfmtMutation.id, params: redos }],- undos: [{ id: SetNumfmtMutation.id, params: undos }],+ redos: [+ { id: RemoveNumfmtMutation.id, params: removeRedos },+ { id: SetNumfmtMutation.id, params: setRedos },+ ],+ undos,};}}diff --git a/packages/sheets-numfmt/src/controllers/numfmt.editor.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.editor.controller.tsindex 0074d57d59..ac6c743800 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.editor.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.editor.controller.ts@@ -1,4 +1,4 @@-import type { Nullable } from '@univerjs/core';+import type { IRange, Nullable } from '@univerjs/core';import {CellValueType,Disposable,@@ -8,13 +8,21 @@ import {toDisposable,} from '@univerjs/core';import numfmt from '@univerjs/engine-numfmt';-import type { INumfmtItemWithCache, ISetNumfmtMutationParams } from '@univerjs/sheets';+import type {+ INumfmtItemWithCache,+ IRemoveNumfmtMutationParams,+ ISetCellsNumfmt,+ ISetNumfmtMutationParams,+} from '@univerjs/sheets';import {+ factoryRemoveNumfmtUndoMutation,factorySetNumfmtUndoMutation,INumfmtService,+ RemoveNumfmtMutation,SetNumfmtMutation,SetRangeValuesCommand,SheetInterceptorService,+ transformCellsToRange,} from '@univerjs/sheets';import { IEditorBridgeService } from '@univerjs/sheets-ui';import { Inject, Injector } from '@wendellhu/redi';@@ -195,20 +203,51 @@ export class NumfmtEditorController extends Disposable {undos: [],};}- const redos: ISetNumfmtMutationParams = {- workbookId,- worksheetId,- values: list.map((item) => ({- pattern: item.value ? item.value.pattern : '',+ const cells: ISetCellsNumfmt = list+ .filter((item) => !!item.value?.pattern)+ .map((item) => ({row: item.row,col: item.col,- type: item.value?.type,- })),- };- const undos = factorySetNumfmtUndoMutation(self._injector, redos);+ pattern: item.value!.pattern,+ type: item.value!.type,+ }));+ const removeCells: IRange[] = list+ .filter((item) => !item.value?.pattern)+ .map((item) => ({+ startRow: item.row,+ endColumn: item.col,+ startColumn: item.col,+ endRow: item.row,+ }));+ const redos = [];+ const undos = [];+ if (cells) {+ const redo = {+ id: SetNumfmtMutation.id,+ params: transformCellsToRange(+ workbookId,+ worksheetId,+ cells+ ) as ISetNumfmtMutationParams,+ };+ redos.push(redo);+ undos.push(...factorySetNumfmtUndoMutation(self._injector, redo.params));+ }+ if (removeCells) {+ const redo = {+ id: RemoveNumfmtMutation.id,+ params: {+ workbookId,+ worksheetId,+ ranges: removeCells,+ } as IRemoveNumfmtMutationParams,+ };+ redos.push(redo);+ undos.push(...factoryRemoveNumfmtUndoMutation(self._injector, redo.params));+ }return {- redos: [{ id: SetNumfmtMutation.id, params: redos }],- undos: [{ id: SetNumfmtMutation.id, params: undos }],+ redos,+ undos: undos.reverse(),};}}diff --git a/packages/sheets-numfmt/src/controllers/numfmt.ref-range.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.ref-range.controller.tsindex 8d84fe3edf..ab1170632a 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.ref-range.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.ref-range.controller.ts@@ -1,4 +1,4 @@-import type { IMutationInfo } from '@univerjs/core';+import type { IMutationInfo, IRange } from '@univerjs/core';import {Disposable,DisposableCollection,@@ -6,11 +6,19 @@ import {IUniverInstanceService,LifecycleStages,OnLifecycle,+ Range,toDisposable,} from '@univerjs/core';-import type { EffectRefRangeParams, ISetNumfmtMutationParams } from '@univerjs/sheets';+import type {+ EffectRefRangeParams,+ FormatType,+ IRemoveNumfmtMutationParams,+ ISetCellsNumfmt,+ ISetNumfmtMutationParams,+} from '@univerjs/sheets';import {EffectRefRangId,+ factoryRemoveNumfmtUndoMutation,factorySetNumfmtUndoMutation,handleDeleteRangeMoveLeft,handleDeleteRangeMoveUp,@@ -23,8 +31,10 @@ import {handleMoveRange,INumfmtService,RefRangeService,+ RemoveNumfmtMutation,runRefRangeMutations,SetNumfmtMutation,+ transformCellsToRange,} from '@univerjs/sheets';import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import type { IDisposable } from '@wendellhu/redi';@@ -32,6 +42,7 @@ import { Inject, Injector } from '@wendellhu/redi';import { merge, Observable } from 'rxjs';import { bufferTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';+const numfmtMutation = [SetNumfmtMutation.id, RemoveNumfmtMutation.id];@OnLifecycle(LifecycleStages.Rendered, NumfmtRefRangeController)export class NumfmtRefRangeController extends Disposable {constructor(@@ -47,36 +58,134 @@ export class NumfmtRefRangeController extends Disposable {this._mergeRefMutations();}+ private _refToReal(values: ISetNumfmtMutationParams['values'], refMap: ISetNumfmtMutationParams['refMap']) {+ const patternMap: {+ [pattern: string]: {+ pattern: string;+ ranges: IRange[];+ type: FormatType;+ };+ } = {};++ Object.keys(values).forEach((id) => {+ const v = refMap[id];+ if (!v) {+ return;+ }+ const ranges = values[id].ranges;+ const pattern = v.pattern;+ const type = v.type;+ patternMap[pattern] = { ranges, pattern, type };+ });+ return patternMap;+ }++ private _mergeNumfmtSetMutation(list: ISetNumfmtMutationParams[]) {+ if (!list.length) {+ return [];+ }+ const firstOne = list[0];+ const patternMap: {+ [pattern: string]: {+ pattern: string;+ ranges: IRange[];+ type: FormatType;+ };+ } = {};+ const refMap: ISetNumfmtMutationParams['refMap'] = {};+ const values: ISetNumfmtMutationParams['values'] = {};+ list.forEach((item) => {+ const { refMap, values } = item;+ const value = this._refToReal(values, refMap);+ Object.keys(value).forEach((key) => {+ if (patternMap[key]) {+ patternMap[key].ranges.push(...value[key].ranges);+ } else {+ patternMap[key] = value[key];+ }+ });+ });+ Object.keys(patternMap).forEach((key, index) => {+ const id = `${index + 1}`;+ const item = patternMap[key];+ refMap[id] = { pattern: item.pattern, type: item.type };+ values[id] = { ranges: item.ranges };+ });+ return {+ ...firstOne,+ refMap,+ values,+ };+ }++ private _mergeNumfmtRemoveMutation(list: IRemoveNumfmtMutationParams[]) {+ if (!list.length) {+ return [];+ }+ const ranges: IRange[] = [];+ list.forEach((item) => {+ ranges.push(...item.ranges);+ });+ const firstOne = list[0];+ return {+ ...firstOne,+ ranges,+ };+ }+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);- },- })- );+ 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 });+ }+ 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() {@@ -162,70 +271,59 @@ export class NumfmtRefRangeController extends Disposable {}}const resultRange = runRefRangeMutations(operators, targetRange);- /**- * Each registry area is modified to generate a pair of delete and set operations,- * which should not generate delete operation if another registry area has previously generate set operations.- */- const isPreSetNumfmt = preValues- .reduce((list, item) => {- list.push(...item.redos);- return list;- }, [] as IMutationInfo[])- .filter((item) => item.id === SetNumfmtMutation.id)- .some((mutation) =>- (mutation.params as ISetNumfmtMutationParams).values!.some(- (item) => item.row === row && item.col === col && !!item.pattern- )- );- if (!resultRange && !isPreSetNumfmt) {- const redoParams: ISetNumfmtMutationParams = {- workbookId,- worksheetId,- values: [{ row, col }],++ const numfmtValue = this._numfmtService.getValue(workbookId, worksheetId, row, col);+ if (!resultRange && numfmtValue) {+ const removeRedo = {+ id: RemoveNumfmtMutation.id,+ params: {+ workbookId,+ worksheetId,+ ranges: [{ startColumn: col, startRow: row, endColumn: col, endRow: row }],+ },};- const undoParams = factorySetNumfmtUndoMutation(this._injector, redoParams);+ const undoRemove = factoryRemoveNumfmtUndoMutation(this._injector, removeRedo.params);return {- redos: [- {- id: SetNumfmtMutation.id,- params: redoParams,- },- ],- undos: [- {- id: SetNumfmtMutation.id,- params: undoParams,- },- ],+ redos: [removeRedo],+ undos: undoRemove,};}- const numfmtValue = this._numfmtService.getValue(workbookId, worksheetId, row, col);-if (numfmtValue && resultRange) {- const redoParams: ISetNumfmtMutationParams = {- workbookId,- worksheetId,- values: [- { ...numfmtValue, row: resultRange.startRow, col: resultRange.startColumn },- ],+ const redos: Array<+ IMutationInfo<IRemoveNumfmtMutationParams | ISetNumfmtMutationParams>+ > = [];+ const undos: Array<+ IMutationInfo<IRemoveNumfmtMutationParams | ISetNumfmtMutationParams>+ > = [];+ const setRedoCells: ISetCellsNumfmt = [+ {+ pattern: numfmtValue.pattern,+ type: numfmtValue.type,+ row: resultRange.startRow,+ col: resultRange.startColumn,+ },+ ];+ const setRedo = {+ id: SetNumfmtMutation.id,+ params: transformCellsToRange(workbookId, worksheetId, setRedoCells),};- if (!isPreSetNumfmt) {- redoParams.values.unshift({ row, col });- }- const undoParams = factorySetNumfmtUndoMutation(this._injector, redoParams);+ const undoSet = factorySetNumfmtUndoMutation(this._injector, setRedo.params);++ const removeRedo = {+ id: RemoveNumfmtMutation.id,+ params: {+ workbookId,+ worksheetId,+ ranges: [{ startColumn: col, startRow: row, endColumn: col, endRow: row }],+ },+ };+ const undoRemove = factoryRemoveNumfmtUndoMutation(this._injector, removeRedo.params);+ redos.push(setRedo, removeRedo);+ undos.push(...undoSet, ...undoRemove);+return {- redos: [- {- id: SetNumfmtMutation.id,- params: redoParams,- },- ],- undos: [- {- id: SetNumfmtMutation.id,- params: undoParams,- },- ],+ redos,+ undos: undos.reverse(),};}return { redos: [], undos: [] };@@ -250,11 +348,13 @@ export class NumfmtRefRangeController extends Disposable {// on changedisposableCollection.add(toDisposable(- new Observable<ISetNumfmtMutationParams>((subscribe) => {+ new Observable<ISetNumfmtMutationParams & IRemoveNumfmtMutationParams>((subscribe) => {disposableCollection.add(this._commandService.onCommandExecuted((commandInfo) => {- if (commandInfo.id === SetNumfmtMutation.id) {- subscribe.next(commandInfo.params as ISetNumfmtMutationParams);+ if (+ [SetNumfmtMutation.id, RemoveNumfmtMutation.id].includes(commandInfo.id)+ ) {+ subscribe.next(commandInfo.params as any);}}));@@ -265,7 +365,19 @@ export class NumfmtRefRangeController extends Disposable {commandInfo.workbookId === workbookId &&commandInfo.worksheetId === worksheetId),- map((commandInfo) => commandInfo.values),+ map((commandInfo) => {+ if (commandInfo.ranges) {+ return commandInfo.ranges;+ }+ if (commandInfo.values) {+ return Object.keys(commandInfo.values).reduce((list, key) => {+ const v = commandInfo.values[key];+ list.push(...v.ranges);+ return list;+ }, [] as IRange[]);+ }+ return [];+ }),bufferTime(300), // updating the listener moves to the next queuemap((values) =>values.reduce((pre, cur) => {@@ -275,28 +387,35 @@ export class NumfmtRefRangeController extends Disposable {),filter((values) => !!values.length))- .subscribe((values) => {- values.forEach((value) => {- const { row, col } = value;- const key = `${row}_${col}`;- const disposable = disposableMap.get(key);- disposableMap.delete(key);- disposable && disposable.dispose();- if (value.pattern) {- const targetRange = {- startRow: row,- startColumn: col,- endRow: row,- endColumn: col,- };- const disposable = this._refRangeService.registerRefRange(- targetRange,- (commandInfo, preValues) =>- register(commandInfo, preValues, row, col)+ .subscribe((ranges) => {+ ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ const key = `${row}_${col}`;+ const disposable = disposableMap.get(key);+ disposableMap.delete(key);+ disposable && disposable.dispose();+ const value = this._numfmtService.getValue(+ workbookId,+ worksheetId,+ row,+ col);- disposableMap.set(key, disposable);- disposableCollection.add(disposable);- }+ if (value) {+ const targetRange = {+ startRow: row,+ startColumn: col,+ endRow: row,+ endColumn: col,+ };+ const disposable = this._refRangeService.registerRefRange(+ targetRange,+ (commandInfo, preValues) =>+ register(commandInfo, preValues, 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.tsindex 70c21679e9..bb467b28bc 100644--- a/packages/sheets-numfmt/src/controllers/numfmt.sheet.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt.sheet.controller.ts@@ -1,10 +1,11 @@+import type { IRange } from '@univerjs/core';import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';-import type { IRemoveSheetCommandParams, ISetNumfmtMutationParams } from '@univerjs/sheets';+import type { IRemoveNumfmtMutationParams, IRemoveSheetCommandParams } from '@univerjs/sheets';import {- factorySetNumfmtUndoMutation,+ factoryRemoveNumfmtUndoMutation,INumfmtService,+ RemoveNumfmtMutation,RemoveSheetCommand,- SetNumfmtMutation,SheetInterceptorService,} from '@univerjs/sheets';import { Inject, Injector } from '@wendellhu/redi';@@ -33,19 +34,19 @@ export class NumfmtSheetController extends Disposable {if (!model) {return { redos: [], undos: [] };}- const values: Array<{ row: number; col: number }> = [];+ const ranges: IRange[] = [];model.forValue((row, col) => {- values.push({ row, col });+ ranges.push({ startColumn: col, endColumn: col, startRow: row, endRow: row });});- const redoParams: ISetNumfmtMutationParams = {+ const redoParams: IRemoveNumfmtMutationParams = {workbookId,worksheetId,- values,+ ranges,};- const undoParams = factorySetNumfmtUndoMutation(this._injector, redoParams);+ const undoParams = factoryRemoveNumfmtUndoMutation(this._injector, redoParams);return {- redos: [{ id: SetNumfmtMutation.id, params: redoParams }],- undos: [{ id: SetNumfmtMutation.id, params: undoParams }],+ redos: [{ id: RemoveNumfmtMutation.id, params: redoParams }],+ undos: undoParams,};}return { redos: [], undos: [] };diff --git a/packages/sheets-numfmt/src/numfmt-plugin.ts b/packages/sheets-numfmt/src/numfmt-plugin.tsindex 969c40b4cc..bd200beab1 100644--- a/packages/sheets-numfmt/src/numfmt-plugin.ts+++ b/packages/sheets-numfmt/src/numfmt-plugin.ts@@ -11,7 +11,7 @@ import { NumfmtSheetController } from './controllers/numfmt.sheet.controller';import { INumfmtController } from './controllers/type';import { UserHabitController } from './controllers/user-habit.controller';-export class NumfmtPlugin extends Plugin {+export class SheetsNumfmt extends Plugin {static override type = PluginType.Sheet;constructor(diff --git a/packages/sheets/src/basics/index.ts b/packages/sheets/src/basics/index.tsindex 5523cf31ff..d4be4ea9ad 100644--- a/packages/sheets/src/basics/index.ts+++ b/packages/sheets/src/basics/index.ts@@ -1,3 +1,4 @@export * from './const/index';export * from './interfaces/index';export * from './selection';+export { createUniqueKey, groupByKey } from './utils';diff --git a/packages/sheets/src/basics/utils.ts b/packages/sheets/src/basics/utils.tsnew file mode 100644index 0000000000..4689e9b703--- /dev/null+++ b/packages/sheets/src/basics/utils.ts@@ -0,0 +1,33 @@+export const groupByKey = <T = Record<string, unknown>>(arr: T[], key: string, blankKey = '') => {+ return arr.reduce(+ (result, current) => {+ const value = current && ((current as Record<string, unknown>)[key] as string);++ if (typeof value !== 'string') {+ console.log(current, `${key} is not string`);+ return result;+ }++ if (value) {+ if (!result[value]) {+ result[value] = [];+ }+ result[value].push(current);+ } else {+ result[blankKey].push(current);+ }+ return result;+ },+ {} as Record<string, T[]>+ );+};++export const createUniqueKey = (initValue = 0) => {+ let _initValue = initValue;+ /**+ * Increments 1 per call+ */+ return function getKey() {+ return _initValue++;+ };+};diff --git a/packages/sheets/src/commands/mutations/numfmt-mutation.ts b/packages/sheets/src/commands/mutations/numfmt-mutation.tsnew file mode 100644index 0000000000..2be0d2fc9a--- /dev/null+++ b/packages/sheets/src/commands/mutations/numfmt-mutation.ts@@ -0,0 +1,172 @@+import type { ICommand, IMutationInfo, IRange } from '@univerjs/core';+import { CommandType, Range } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';++import { createUniqueKey, groupByKey } from '../../basics/utils';+import type { FormatType } from '../../services/numfmt/type';+import { INumfmtService } from '../../services/numfmt/type';++export const factorySetNumfmtUndoMutation = (accessor: IAccessor, option: ISetNumfmtMutationParams) => {+ const numfmtService = accessor.get(INumfmtService);+ const { values, workbookId, worksheetId } = option;+ const cells: ISetCellsNumfmt = [];+ const removeCells: IRange[] = [];+ const model = numfmtService.getModel(workbookId, worksheetId) || undefined;+ Object.keys(values).forEach((id) => {+ const value = values[id];+ value.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ const oldNumfmt = numfmtService.getValue(workbookId, worksheetId, row, col, model);+ if (oldNumfmt) {+ cells.push({+ pattern: oldNumfmt.pattern,+ type: oldNumfmt.type,+ row,+ col,+ });+ } else {+ removeCells.push({ startColumn: col, endColumn: col, startRow: row, endRow: row });+ }+ });+ });+ });+ const result: Array<IMutationInfo<ISetNumfmtMutationParams | IRemoveNumfmtMutationParams>> = [];+ if (cells) {+ result.push({+ id: SetNumfmtMutation.id,+ params: transformCellsToRange(workbookId, worksheetId, cells),+ });+ }+ if (removeCells) {+ result.push({+ id: RemoveNumfmtMutation.id,+ params: {+ workbookId,+ worksheetId,+ ranges: removeCells,+ },+ });+ }+ return result;+};++export interface ISetNumfmtMutationParams {+ values: {+ [id: string]: {+ ranges: IRange[];+ };+ };+ refMap: {+ [id: string]: {+ pattern: string;+ type: FormatType;+ };+ };+ workbookId: string;+ worksheetId: string;+}++export const SetNumfmtMutation: ICommand<ISetNumfmtMutationParams> = {+ id: 'sheet.mutation.set.numfmt',+ type: CommandType.MUTATION,+ handler: (accessor: IAccessor, params) => {+ if (!params) {+ return false;+ }+ const { values, refMap } = params;+ const numfmtService = accessor.get(INumfmtService);+ const workbookId = params.workbookId;+ const sheetId = params.worksheetId;+ const setValues = Object.keys(values).reduce(+ (result, id) => {+ const value = refMap[id];+ const ranges = values[id].ranges;+ if (value) {+ result.push({+ ...value,+ ranges,+ });+ }+ return result;+ },+ [] as Array<{ pattern: string; type: FormatType; ranges: IRange[] }>+ );+ numfmtService.setValues(workbookId, sheetId, setValues);+ return true;+ },+};++export interface IRemoveNumfmtMutationParams {+ ranges: IRange[];+ workbookId: string;+ worksheetId: string;+}+export const RemoveNumfmtMutation: ICommand<IRemoveNumfmtMutationParams> = {+ id: 'sheet.mutation.remove.numfmt',+ type: CommandType.MUTATION,+ handler: (accessor: IAccessor, params) => {+ if (!params) {+ return false;+ }+ const { workbookId, worksheetId, ranges } = params;+ const numfmtService = accessor.get(INumfmtService);+ numfmtService.deleteValues(workbookId, worksheetId, ranges);+ return true;+ },+};+export const factoryRemoveNumfmtUndoMutation = (accessor: IAccessor, option: IRemoveNumfmtMutationParams) => {+ const numfmtService = accessor.get(INumfmtService);+ const { ranges, workbookId, worksheetId } = option;+ const cells: ISetCellsNumfmt = [];+ const model = numfmtService.getModel(workbookId, worksheetId) || undefined;+ ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ const oldNumfmt = numfmtService.getValue(workbookId, worksheetId, row, col, model);+ if (oldNumfmt) {+ cells.push({+ pattern: oldNumfmt.pattern,+ type: oldNumfmt.type,+ row,+ col,+ });+ }+ });+ });+ return [{ id: SetNumfmtMutation.id, params: transformCellsToRange(workbookId, worksheetId, cells) }];+};+export type ISetCellsNumfmt = Array<{ pattern: string; type: FormatType; row: number; col: number }>;+export const transformCellsToRange = (+ workbookId: string,+ worksheetId: string,+ cells: ISetCellsNumfmt+): ISetNumfmtMutationParams => {+ const group = groupByKey(cells, 'pattern');+ const refMap: ISetNumfmtMutationParams['refMap'] = {};+ const values: ISetNumfmtMutationParams['values'] = {};+ const getKey = createUniqueKey();+ Object.keys(group).forEach((pattern) => {+ const groupItem = group[pattern];+ const firstOne = groupItem[0];+ const key = getKey();+ refMap[key] = {+ pattern,+ type: firstOne.type,+ };+ groupItem.forEach((item) => {+ if (!values[key]) {+ values[key] = { ranges: [] };+ }+ values[key].ranges.push(cellToRange(item.row, item.col));+ });+ // TODO@gggpound: ranges to be merge.+ });+ return { workbookId, worksheetId, refMap, values };+};++const cellToRange = (row: number, col: number) =>+ ({+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ }) as IRange;diff --git a/packages/sheets/src/commands/mutations/set-numfmt-mutation.ts b/packages/sheets/src/commands/mutations/set-numfmt-mutation.tsdeleted file mode 100644index 5cc258daad..0000000000--- a/packages/sheets/src/commands/mutations/set-numfmt-mutation.ts+++ /dev/null@@ -1,53 +0,0 @@-import type { ICommand } from '@univerjs/core';-import { CommandType } from '@univerjs/core';-import type { IAccessor } from '@wendellhu/redi';--import type { FormatType } from '../../services/numfmt/type';-import { INumfmtService } from '../../services/numfmt/type';--export const factorySetNumfmtUndoMutation = (- accessor: IAccessor,- option: ISetNumfmtMutationParams-): ISetNumfmtMutationParams => {- const numfmtService = accessor.get(INumfmtService);- const undos: ISetNumfmtMutationParams = {- ...option,- values: option.values- .map((item) => {- const { row, col } = item;- const oldValue = numfmtService.getValue(option.workbookId, option.worksheetId, row, col);- if (oldValue) {- return { pattern: oldValue.pattern, type: oldValue.type, row, col };- }- return { row, col };- })- .reverse(),- };- return undos;-};--export interface ISetNumfmtMutationParams {- values: Array<{ pattern?: string; row: number; col: number; type?: FormatType }>;- workbookId: string;- worksheetId: string;-}--export const SetNumfmtMutation: ICommand<ISetNumfmtMutationParams> = {- id: 'sheet.mutation.set.numfmt',- type: CommandType.MUTATION,- handler: (accessor: IAccessor, params) => {- if (!params) {- return false;- }- const values = params.values;- const numfmtService = accessor.get(INumfmtService);- const workbookId = params.workbookId;- const sheetId = params.worksheetId;- numfmtService.setValues(- workbookId,- sheetId,- values.map((item) => ({ ...item, type: item.type! }))- );- return true;- },-};diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.tsindex f16e5e9534..202653752a 100644--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts@@ -74,12 +74,12 @@ import { InsertColMutation, InsertRowMutation } from '../commands/mutations/inseimport { InsertSheetMutation } from '../commands/mutations/insert-sheet.mutation';import { MoveRangeMutation } from '../commands/mutations/move-range.mutation';import { MoveColsMutation, MoveRowsMutation } from '../commands/mutations/move-rows-cols.mutation';+import { RemoveNumfmtMutation, SetNumfmtMutation } from '../commands/mutations/numfmt-mutation';import { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';import { RemoveSheetMutation } from '../commands/mutations/remove-sheet.mutation';import { RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';import { SetColHiddenMutation, SetColVisibleMutation } from '../commands/mutations/set-col-visible.mutation';import { SetFrozenMutation } from '../commands/mutations/set-frozen.mutation';-import { SetNumfmtMutation } from '../commands/mutations/set-numfmt-mutation';import { SetRangeValuesMutation } from '../commands/mutations/set-range-values.mutation';import { SetRowHiddenMutation, SetRowVisibleMutation } from '../commands/mutations/set-row-visible.mutation';import { SetTabColorMutation } from '../commands/mutations/set-tab-color.mutation';@@ -197,6 +197,7 @@ export class BasicWorksheetController extends Disposable implements IDisposableSetWorksheetRowIsAutoHeightMutation,SetWorksheetShowCommand,SetNumfmtMutation,+ RemoveNumfmtMutation,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));this._configService.setConfig(MAX_CELL_PER_SHEET_KEY, MAX_CELL_PER_SHEET_DEFAULT);diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 216e4e92b4..3421c48c6c 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -171,6 +171,18 @@ export { type IMoveRangeMutationParams } from './commands/mutations/move-range.mexport { type IMoveColumnsMutationParams } from './commands/mutations/move-rows-cols.mutation';export { type IMoveRowsMutationParams, MoveRowsMutation } from './commands/mutations/move-rows-cols.mutation';export { MoveColsMutation } from './commands/mutations/move-rows-cols.mutation';+export type {+ IRemoveNumfmtMutationParams,+ ISetCellsNumfmt,+ ISetNumfmtMutationParams,+} from './commands/mutations/numfmt-mutation';+export {+ factoryRemoveNumfmtUndoMutation,+ factorySetNumfmtUndoMutation,+ RemoveNumfmtMutation,+ SetNumfmtMutation,+ transformCellsToRange,+} from './commands/mutations/numfmt-mutation';export { RemoveColMutation, RemoveRowMutation } from './commands/mutations/remove-row-col.mutation';export { RemoveSheetMutation, RemoveSheetUndoMutationFactory } from './commands/mutations/remove-sheet.mutation';export { RemoveWorksheetMergeMutation } from './commands/mutations/remove-worksheet-merge.mutation';@@ -186,8 +198,6 @@ export {SetFrozenMutation,SetFrozenMutationFactory,} from './commands/mutations/set-frozen.mutation';-export type { ISetNumfmtMutationParams } from './commands/mutations/set-numfmt-mutation';-export { factorySetNumfmtUndoMutation, SetNumfmtMutation } from './commands/mutations/set-numfmt-mutation';export type { ISetRangeValuesMutationParams } from './commands/mutations/set-range-values.mutation';export { SetRangeValuesMutation } from './commands/mutations/set-range-values.mutation';export { SetRangeValuesUndoMutationFactory } from './commands/mutations/set-range-values.mutation';diff --git a/packages/sheets/src/services/__tests__/numfmt.service.test.ts b/packages/sheets/src/services/__tests__/numfmt.service.test.tsindex 7c2625bef1..1a34986d2d 100644--- a/packages/sheets/src/services/__tests__/numfmt.service.test.ts+++ b/packages/sheets/src/services/__tests__/numfmt.service.test.ts@@ -1,14 +1,15 @@import type { Univer } from '@univerjs/core';import { ICommandService, IUniverInstanceService } from '@univerjs/core';-import type { ISetNumfmtMutationParams } from '@univerjs/sheets';+import type { IRemoveNumfmtMutationParams, ISetNumfmtMutationParams } from '@univerjs/sheets';import type { Injector } from '@wendellhu/redi';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { SetNumfmtMutation } from '../../commands/mutations/set-numfmt-mutation';+import { RemoveNumfmtMutation, SetNumfmtMutation } from '../../commands/mutations/numfmt-mutation';import { NumfmtService } from '../numfmt/numfmt.service';import { INumfmtService } from '../numfmt/type';import { createTestBase } from './util';+const cellToRange = (row: number, col: number) => ({ startRow: row, endRow: row, startColumn: col, endColumn: col });describe('test numfmt service', () => {let univer: Univer;let get: Injector['get'];@@ -20,6 +21,7 @@ describe('test numfmt service', () => {get = testBed.get;commandService = get(ICommandService);commandService.registerCommand(SetNumfmtMutation);+ commandService.registerCommand(RemoveNumfmtMutation);});afterEach(() => {@@ -36,11 +38,17 @@ describe('test numfmt service', () => {const params: ISetNumfmtMutationParams = {workbookId,worksheetId,- values: [{ row: 1, col: 1, pattern: 'asdws' }],+ refMap: {+ 1: {+ pattern: 'asdws',+ type: 'sss' as any,+ },+ },+ values: { 1: { ranges: [cellToRange(1, 1)] } },};commandService.executeCommand(SetNumfmtMutation.id, params);const numfmtValue = numfmtService.getValue(workbookId, worksheetId, 1, 1);- expect(numfmtValue).toEqual({ pattern: 'asdws', type: undefined });+ expect(numfmtValue).toEqual({ pattern: 'asdws', type: 'sss' });const model = numfmtService.getModel(workbookId, worksheetId);expect(model?.getValue(1, 1)).toEqual({ i: '1' });});@@ -55,12 +63,23 @@ describe('test numfmt service', () => {const params: ISetNumfmtMutationParams = {workbookId,worksheetId,- values: [{ row: 1, col: 1, pattern: 'asdws' }],+ refMap: {+ 1: {+ pattern: 'asdws',+ type: 'sss' as any,+ },+ },+ values: { 1: { ranges: [cellToRange(1, 1)] } },+ };+ const deleteParams: IRemoveNumfmtMutationParams = {+ workbookId,+ worksheetId,+ ranges: [cellToRange(1, 1)],};commandService.executeCommand(SetNumfmtMutation.id, params);const numfmtValue = numfmtService.getValue(workbookId, worksheetId, 1, 1);- expect(numfmtValue).toEqual({ pattern: 'asdws' });- commandService.executeCommand(SetNumfmtMutation.id, { ...params, values: [{ row: 1, col: 1 }] });+ expect(numfmtValue).toEqual({ pattern: 'asdws', type: 'sss' });+ commandService.executeCommand(RemoveNumfmtMutation.id, deleteParams);const numfmtValueDelete = numfmtService.getValue(workbookId, worksheetId, 1, 1);expect(numfmtValueDelete).toEqual(null);});@@ -75,7 +94,13 @@ describe('test numfmt service', () => {const params: ISetNumfmtMutationParams = {workbookId,worksheetId,- values: [{ row: 1, col: 1, pattern: 'asdws' }],+ refMap: {+ 1: {+ pattern: 'asdws',+ type: 'sss' as any,+ },+ },+ values: { 1: { ranges: [cellToRange(1, 1)] } },};commandService.executeCommand(SetNumfmtMutation.id, params);const refModel = numfmtService.getRefModel(workbookId);@@ -95,10 +120,21 @@ describe('test numfmt service', () => {const params: ISetNumfmtMutationParams = {workbookId,worksheetId,- values: [{ row: 1, col: 1, pattern: 'asdws' }],+ refMap: {+ 1: {+ pattern: 'asdws',+ type: 'sss' as any,+ },+ },+ values: { 1: { ranges: [cellToRange(1, 1)] } },+ };+ const deleteParams: IRemoveNumfmtMutationParams = {+ workbookId,+ worksheetId,+ ranges: [cellToRange(1, 1)],};commandService.executeCommand(SetNumfmtMutation.id, params);- commandService.executeCommand(SetNumfmtMutation.id, { ...params, values: [{ row: 1, col: 1 }] });+ commandService.executeCommand(RemoveNumfmtMutation.id, deleteParams);const refModel = numfmtService.getRefModel(workbookId);expect(refModel?.getValue('asdws')?.count).toEqual(0);expect(refModel?.getValue('1')?.count).toEqual(0);@@ -114,13 +150,25 @@ describe('test numfmt service', () => {const params1: ISetNumfmtMutationParams = {workbookId,worksheetId: sheets[0].getSheetId(),- values: [{ row: 1, col: 1, pattern }],+ refMap: {+ 1: {+ pattern,+ type: 'sss' as any,+ },+ },+ values: { 1: { ranges: [cellToRange(1, 1)] } },};commandService.executeCommand(SetNumfmtMutation.id, params1);const params2: ISetNumfmtMutationParams = {workbookId,worksheetId: sheets[1].getSheetId(),- values: [{ row: 1, col: 1, pattern }],+ refMap: {+ 1: {+ pattern,+ type: 'sss' as any,+ },+ },+ values: { 1: { ranges: [cellToRange(1, 1)] } },};commandService.executeCommand(SetNumfmtMutation.id, params2);const refModel = numfmtService.getRefModel(workbookId);diff --git a/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts b/packages/sheets/src/services/__tests__/ref-range.setvice.spec.tsindex 0ce99d1306..99ea02853b 100644--- a/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts+++ b/packages/sheets/src/services/__tests__/ref-range.setvice.spec.ts@@ -127,24 +127,35 @@ describe('Test ref-range.service', () => {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))+ // [1,2,3],[1,2,3],[1,2,3]+ // after squash to be+ // [1,2,3,1,2,3,1,2,3]+ const disposeIntercept = refRangeService.interceptor.intercept(+ refRangeService.interceptor.getInterceptPoints().MERGE_REDO,+ {+ handler: (list, _c, next) => {+ const redo = list?.filter((item) => item.id === redoMutationId) || [];+ const result = list?.filter((item) => item.id !== redoMutationId) || [];+ if (redo.length) {+ result.push(+ redo.reduce(+ (_result, current) => {+ const params = current.params as any;+ _result.params.values.push(...params.values);+ return _result;+ },+ {+ id: redoMutationId,+ params: { values: [] },+ } as { id: string; params: { values: any[] } }+ ));- return list;}- }- return next(list);- },- });+ return next(result);+ },+ }+ );+const params: IMoveRangeCommandParams = {fromRange: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 2 },toRange: { startRow: 3, endRow: 5, startColumn: 2, endColumn: 2 },@@ -155,7 +166,7 @@ describe('Test ref-range.service', () => {expect((result as any).redos[0].params.values.length).toBe(9);// if dispose, the mutations will not be squash.- disposeIntercept.dispose();+ disposeIntercept();commandService.executeCommand(MoveRangeCommand.id, params);const resultWithoutInterceptor = sheetInterceptorService.onCommandExecute({ id: MoveRangeCommand.id, params });expect((resultWithoutInterceptor as any).redos.length).toBe(3);diff --git a/packages/sheets/src/services/numfmt/numfmt.service.ts b/packages/sheets/src/services/numfmt/numfmt.service.tsindex c7039be15b..b772a856ef 100644--- a/packages/sheets/src/services/numfmt/numfmt.service.ts+++ b/packages/sheets/src/services/numfmt/numfmt.service.ts@@ -1,4 +1,4 @@-import type { Nullable, ObjectMatrixPrimitiveType, Workbook } from '@univerjs/core';+import type { IRange, Nullable, ObjectMatrixPrimitiveType, Workbook } from '@univerjs/core';import {Disposable,ICommandService,@@ -8,6 +8,7 @@ import {LifecycleStages,ObjectMatrix,OnLifecycle,+ Range,RefAlias,toDisposable,} from '@univerjs/core';@@ -146,24 +147,6 @@ export class NumfmtService extends Disposable implements INumfmtService {}}- private _groupByKey<T = Record<string, unknown>>(arr: T[], key: string, blankKey = '') {- return arr.reduce(- (result, current) => {- const pattern = current && ((current as Record<string, unknown>)[key] as string);- if (pattern) {- if (!result[pattern]) {- result[pattern] = [];- }- result[pattern].push(current);- } else {- result[blankKey].push(current);- }- return result;- },- { [blankKey]: [] } as Record<string, T[]>- );- }-private _getUniqueRefId(unitID: string) {const refModel = this._refAliasModel.get(unitID);if (!refModel) {@@ -195,71 +178,58 @@ export class NumfmtService extends Disposable implements INumfmtService {return null;}+ deleteValues(workbookId: string, worksheetId: string, values: IRange[]) {+ let refModel = this._refAliasModel.get(workbookId)!;+ const model = this.getModel(workbookId, worksheetId);+ if (!refModel) {+ refModel = new RefAlias<IRefItem, 'i' | 'pattern'>([], ['pattern', 'i']);+ this._refAliasModel.set(workbookId, refModel);+ }+ values.forEach((range) => {+ Range.foreach(range, (row, col) => {+ const oldValue = this.getValue(workbookId, worksheetId, row, col, model);+ if (oldValue && oldValue.pattern) {+ const oldRefPattern = refModel.getValue(oldValue.pattern);+ if (oldRefPattern) {+ oldRefPattern.count--;+ }+ }+ this._setValue(workbookId, worksheetId, row, col, null);+ });+ });+ }+setValues(workbookId: string,worksheetId: string,- values: Array<{ row: number; col: number; pattern?: string; type: FormatType }>+ values: Array<{ ranges: IRange[]; pattern: string; type: FormatType }>) {- const ___delete___ = '___delete___';- const group = this._groupByKey(values, 'pattern', ___delete___);const model = this.getModel(workbookId, worksheetId);let refModel = this._refAliasModel.get(workbookId)!;if (!refModel) {refModel = new RefAlias<IRefItem, 'i' | 'pattern'>([], ['pattern', 'i']);this._refAliasModel.set(workbookId, refModel);}- Object.keys(group).forEach((pattern: string) => {- const values = group[pattern];- const length = values.length;- if (!length) {- return;+ values.forEach((value) => {+ let refPattern = refModel.getValue(value.pattern);+ if (!refPattern) {+ refPattern = {+ count: 0,+ i: this._getUniqueRefId(workbookId),+ pattern: value.pattern,+ type: values[0].type,+ };+ refModel.addValue(refPattern);}- let refPattern = refModel.getValue(pattern);- if (pattern === ___delete___) {- values.forEach((item) => {- const { row, col } = item;- const oldValue = this.getValue(workbookId, worksheetId, row, col, model);- if (oldValue && oldValue.pattern) {- const oldRefPattern = refModel.getValue(oldValue.pattern);- if (oldRefPattern) {- oldRefPattern.count--;- // if (oldRefPattern.count <= 0) {- // this._refAliasModel.deleteValue(oldValue.pattern);- // }- }- }- this._setValue(workbookId, worksheetId, row, col, null);- });- if (refPattern) {- const count = refPattern.count - length;- if (count > 0) {- refModel.setValue(pattern, 'count', count);- }- //else {- // this._refAliasModel.deleteValue(pattern);- // }- }- } else {- if (!refPattern) {- refPattern = {- count: 0,- i: this._getUniqueRefId(workbookId),- pattern,- type: values[0].type,- };- refModel.addValue(refPattern);- }- values.forEach((item) => {- const { row, col } = item;++ value.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {if (model) {const oldValue = this.getValue(workbookId, worksheetId, row, col, model);if (oldValue && oldValue.pattern) {const oldRefPattern = refModel.getValue(oldValue.pattern);if (oldRefPattern) {oldRefPattern.count--;- // if (oldRefPattern.count <= 0) {- // this._refAliasModel.deleteValue(oldValue.pattern);- // }}}}@@ -268,7 +238,7 @@ export class NumfmtService extends Disposable implements INumfmtService {});refPattern!.count++;});- }+ });});}diff --git a/packages/sheets/src/services/numfmt/type.ts b/packages/sheets/src/services/numfmt/type.tsindex f2b3db7f9d..33d7d70bf0 100644--- a/packages/sheets/src/services/numfmt/type.ts+++ b/packages/sheets/src/services/numfmt/type.ts@@ -1,4 +1,4 @@-import type { ICellData, Nullable, ObjectMatrix, ObjectMatrixPrimitiveType, RefAlias } from '@univerjs/core';+import type { ICellData, IRange, Nullable, ObjectMatrix, ObjectMatrixPrimitiveType, RefAlias } from '@univerjs/core';import { LifecycleStages, runOnLifecycle } from '@univerjs/core';import { createIdentifier } from '@wendellhu/redi';import type { Observable } from 'rxjs';@@ -46,8 +46,9 @@ export interface INumfmtService {setValues(workbookId: string,worksheetId: string,- values: Array<{ row: number; col: number; pattern?: string; type?: FormatType }>+ values: Array<{ ranges: IRange[]; pattern: string; type: FormatType }>): void;+ deleteValues(workbookId: string, worksheetId: string, values: IRange[]): void;getRefModel(workbookId: string): Nullable<RefAlias<IRefItem, 'i' | 'pattern'>>;modelReplace$: Observable<string>;}diff --git a/packages/sheets/src/services/ref-range/ref-range.service.ts b/packages/sheets/src/services/ref-range/ref-range.service.tsindex 92ada0ab54..f40d44c9d4 100644--- a/packages/sheets/src/services/ref-range/ref-range.service.ts+++ b/packages/sheets/src/services/ref-range/ref-range.service.ts@@ -1,13 +1,12 @@-import type { IInterceptor, IMutationInfo, IRange } from '@univerjs/core';+import type { IMutationInfo, IRange } from '@univerjs/core';import {- composeInterceptors,createInterceptorKey,Disposable,+ InterceptorManager,IUniverInstanceService,LifecycleStages,OnLifecycle,Rectangle,- remove,toDisposable,} from '@univerjs/core';import type { IDisposable } from '@wendellhu/redi';@@ -25,13 +24,16 @@ type RefRangCallback = (redos: IMutationInfo[];undos: IMutationInfo[];};-const refRangeCommandsMerge = createInterceptorKey<IMutationInfo[], IMutationInfo[]>('refRangeCommandsMerge');+const MERGE_REDO = createInterceptorKey<IMutationInfo[], null>('MERGE_REDO');+const MERGE_UNDO = createInterceptorKey<IMutationInfo[], null>('MERGE_UNDO');+/*** 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();+ interceptor = new InterceptorManager({ MERGE_REDO, MERGE_UNDO });+constructor(@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,@@ -39,13 +41,13 @@ export class RefRangeService extends Disposable {) {super();this._onRefRangeChange();- this.intercept({+ this.interceptor.intercept(this.interceptor.getInterceptPoints().MERGE_REDO, {priority: -1,- handler: (list, currentValue) => {- const _list = list || [];- _list.push(...currentValue);- return _list;- },+ handler: (list) => list,+ });+ this.interceptor.intercept(this.interceptor.getInterceptPoints().MERGE_UNDO, {+ priority: -1,+ handler: (list) => list,});}@@ -153,14 +155,25 @@ export class RefRangeService extends Disposable {).reduce((result, currentValue) => {- const intercept = this._fetchThroughInterceptors();- const redos = intercept(result.redos, currentValue.redos) || [];- const undos = intercept(result.undos, currentValue.undos) || [];- return { redos, undos };+ result.redos.push(...currentValue.redos);+ result.undos.push(...currentValue.undos);+ return result;},{ redos: [], undos: [] });- return result;+ const redos =+ this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_REDO)(+ result.redos,+ null+ ) || [];++ const undos =+ this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_UNDO)(+ result.undos,+ null+ ) || [];++ return { redos, undos };},});};@@ -233,38 +246,6 @@ 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) {