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): add numfmt service test case (#579)

Gpound.liudb4596dcbb51
diff --git a/packages/base-sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
index 2fa60805c3..83aa3320ce 100644
--- a/packages/base-sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
+++ b/packages/base-sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
@@ -151,7 +151,7 @@ describe('Test clear selection content commands', () => {
expect(await commandService.executeCommand(ClearSelectionFormatCommand.id)).toBeTruthy();
expect(getValue()).toStrictEqual({
v: 'A1',
- t: 4,
+ t: 1,
});
// undo
@@ -163,7 +163,7 @@ describe('Test clear selection content commands', () => {
expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
expect(getValue()).toStrictEqual({
v: 'A1',
- t: 4,
+ t: 1,
});
});
it('clear formats with merged cells', async () => {
@@ -230,7 +230,7 @@ describe('Test clear selection content commands', () => {
// clear formats
expect(getValue()).toStrictEqual({
v: 'A1',
- t: 4,
+ t: 1,
});
// remove merge
expect(getMerge()).toStrictEqual([]);
@@ -247,7 +247,7 @@ describe('Test clear selection content commands', () => {
expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
expect(getValue()).toStrictEqual({
v: 'A1',
- t: 4,
+ t: 1,
});
expect(getMerge()).toStrictEqual([]);
});
diff --git a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
index 3b844e1dc6..4508480cca 100644
--- a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -156,7 +156,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
cellMatrix?.setValue(row, col, {});
} else {
const oldVal = cellMatrix.getValue(row, col) || {};
- const type = newVal.t ? newVal.t : checkCellValueType(newVal.v);
+ const type = newVal.t ? newVal.t : checkCellValueType(newVal.v === undefined ? oldVal.v : newVal.v);
if (newVal.f !== undefined) {
oldVal.f = newVal.f;
diff --git a/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts b/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts
index 644a01f399..5dc56561f5 100644
--- a/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts
+++ b/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts
@@ -146,14 +146,17 @@ export class SheetInterceptorService extends Disposable {
const sheetDisposables = new DisposableCollection();
const cellInterceptorDisposable = viewModel.registerCellContentInterceptor({
getCell(row: number, col: number): Nullable<ICellData> {
- return self.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT)(undefined, {
- workbookId,
- worksheetId,
- row,
- col,
- worksheet,
- workbook,
- });
+ return self.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT)(
+ worksheet.getCellRaw(row, col),
+ {
+ workbookId,
+ worksheetId,
+ row,
+ col,
+ worksheet,
+ workbook,
+ }
+ );
},
});
sheetDisposables.add(cellInterceptorDisposable);
diff --git a/packages/sheets-plugin-numfmt/src/__tests__/createTestBase.ts b/packages/sheets-plugin-numfmt/src/__tests__/createTestBase.ts
new file mode 100644
index 0000000000..e00ef9c3e8
--- /dev/null
+++ b/packages/sheets-plugin-numfmt/src/__tests__/createTestBase.ts
@@ -0,0 +1,72 @@
+import { IUniverInstanceService, IWorkbookData, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import { Dependency, Inject, Injector } from '@wendellhu/redi';
+
+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',
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: [],
+ 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');
+
+ return {
+ univer,
+ get,
+ sheet,
+ };
+}
diff --git a/packages/sheets-plugin-numfmt/src/__tests__/numfmt.service.test.ts b/packages/sheets-plugin-numfmt/src/__tests__/numfmt.service.test.ts
new file mode 100644
index 0000000000..8ded8492b4
--- /dev/null
+++ b/packages/sheets-plugin-numfmt/src/__tests__/numfmt.service.test.ts
@@ -0,0 +1,97 @@
+import { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { SetNumfmtMutation, SetNumfmtMutationParams } from '../commands/mutations/set.numfmt.mutation';
+import { NumfmtService } from '../service/numfmt.service';
+import { INumfmtService } from '../service/type';
+import { createTestBase } from './createTestBase';
+
+describe('test numfmt service', () => {
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const testBed = createTestBase(undefined, [[INumfmtService, { useClass: NumfmtService }]]);
+ get = testBed.get;
+ commandService = get(ICommandService);
+ });
+
+ it('model set', () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ const numfmtService = get(INumfmtService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ const sheet = workbook.getActiveSheet();
+ const workbookId = workbook.getUnitId();
+ const worksheetId = sheet.getSheetId();
+ const params: SetNumfmtMutationParams = {
+ workbookId,
+ worksheetId,
+ values: [{ row: 1, col: 1, pattern: 'asdws' }],
+ };
+ commandService.executeCommand(SetNumfmtMutation.id, params);
+ const numfmtValue = numfmtService.getValue(workbookId, worksheetId, 1, 1);
+ expect(numfmtValue).toEqual({ pattern: 'asdws', type: undefined });
+ const model = numfmtService.getModel(workbookId, worksheetId);
+ expect(model?.getValue(1, 1)).toEqual({ pattern: '1' });
+ });
+
+ it('model delete', () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ const numfmtService = get(INumfmtService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ const sheet = workbook.getActiveSheet();
+ const workbookId = workbook.getUnitId();
+ const worksheetId = sheet.getSheetId();
+ const params: SetNumfmtMutationParams = {
+ workbookId,
+ worksheetId,
+ values: [{ row: 1, col: 1, pattern: 'asdws' }],
+ };
+ 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 }] });
+ const numfmtValueDelete = numfmtService.getValue(workbookId, worksheetId, 1, 1);
+ expect(numfmtValueDelete).toEqual(null);
+ });
+
+ it('ref model set', () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ const numfmtService = get(INumfmtService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ const sheet = workbook.getActiveSheet();
+ const workbookId = workbook.getUnitId();
+ const worksheetId = sheet.getSheetId();
+ const params: SetNumfmtMutationParams = {
+ workbookId,
+ worksheetId,
+ values: [{ row: 1, col: 1, pattern: 'asdws' }],
+ };
+ commandService.executeCommand(SetNumfmtMutation.id, params);
+ const refModel = numfmtService.getRefModel(workbookId);
+ expect(refModel?.getKeyMap('numfmtId')).toEqual(['1']);
+ expect(refModel?.getKeyMap('pattern')).toEqual(['asdws']);
+ expect(refModel?.getValue('asdws')?.count).toEqual(1);
+ expect(refModel?.getValue('1')?.count).toEqual(1);
+ });
+
+ it('model delete', () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ const numfmtService = get(INumfmtService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ const sheet = workbook.getActiveSheet();
+ const workbookId = workbook.getUnitId();
+ const worksheetId = sheet.getSheetId();
+ const params: SetNumfmtMutationParams = {
+ workbookId,
+ worksheetId,
+ values: [{ row: 1, col: 1, pattern: 'asdws' }],
+ };
+ commandService.executeCommand(SetNumfmtMutation.id, params);
+ commandService.executeCommand(SetNumfmtMutation.id, { ...params, values: [{ row: 1, col: 1 }] });
+ const refModel = numfmtService.getRefModel(workbookId);
+ expect(refModel?.getValue('asdws')?.count).toEqual(0);
+ expect(refModel?.getValue('1')?.count).toEqual(0);
+ });
+});
diff --git a/packages/sheets-plugin-numfmt/src/base/types/index.ts b/packages/sheets-plugin-numfmt/src/base/types/index.ts
index 9be354fe95..64ecb04a9d 100644
--- a/packages/sheets-plugin-numfmt/src/base/types/index.ts
+++ b/packages/sheets-plugin-numfmt/src/base/types/index.ts
@@ -3,10 +3,9 @@ export type BusinessComponentProps = {
defaultValue: number;
defaultPattern: string;
};
-export interface NumfmtItem {
+export type NumfmtItem = {
pattern: string;
- type: FormatType;
-}
+};
export type FormatType =
| 'currency'
diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts
index c9722f526f..35428e8114 100644
--- a/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts
+++ b/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts
@@ -24,6 +24,7 @@ import {
CellValueType,
Disposable,
DisposableCollection,
+ ICellData,
ICommandService,
IMutationInfo,
INTERCEPTOR_POINT,
@@ -32,6 +33,7 @@ import {
LocaleService,
LocaleType,
Nullable,
+ ObjectMatrix,
Range,
Rectangle,
SheetInterceptorService,
@@ -50,7 +52,6 @@ import { combineLatest, Observable } from 'rxjs';
import { bufferTime, distinctUntilChanged, filter, map, switchMap, tap } from 'rxjs/operators';
import { SHEET_NUMFMT_PLUGIN } from '../base/const/PLUGIN_NAME';
-import { NumfmtItem } from '../base/types';
import { AddDecimalCommand } from '../commands/commands/add.decimal.command';
import { SetCurrencyCommand } from '../commands/commands/set.currency.command';
import { SetNumfmtCommand, SetNumfmtCommandParams } from '../commands/commands/set.numfmt.command';
@@ -65,15 +66,26 @@ import { OpenNumfmtPanelOperator } from '../commands/operators/open.numfmt.panel
import { SheetNumfmtPanel, SheetNumfmtPanelProps } from '../components/index';
import { zhCn } from '../locale/zh-CN';
import { AddDecimalMenuItem, CurrencyMenuItem, FactoryOtherMenuItem, SubtractDecimalMenuItem } from '../menu/menu';
-import { INumfmtService } from '../service/type';
+import { INumfmtService, NumfmtItemWithCache } from '../service/type';
import { getPatternPreview, getPatternType } from '../utils/pattern';
import type { INumfmtController } from './type';
const createCollectEffectMutation = () => {
- type Config = { workbookId: string; worksheetId: string; row: number; col: number; value: Nullable<NumfmtItem> };
+ type Config = {
+ workbookId: string;
+ worksheetId: string;
+ row: number;
+ col: number;
+ value: Nullable<NumfmtItemWithCache>;
+ };
let list: Config[] = [];
- const add = (workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<NumfmtItem>) =>
- list.push({ workbookId, worksheetId, row, col, value });
+ const add = (
+ workbookId: string,
+ worksheetId: string,
+ row: number,
+ col: number,
+ value: Nullable<NumfmtItemWithCache>
+ ) => list.push({ workbookId, worksheetId, row, col, value });
const getEffects = () => list;
const clean = () => {
list = [];
@@ -88,7 +100,6 @@ export class NumfmtController extends Disposable implements INumfmtController {
// collect effect mutations when edit end and push this to commands stack in next commands progress
private _collectEffectMutation = createCollectEffectMutation();
private _previewPattern = '';
-
constructor(
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@Inject(ThemeService) private _themeService: ThemeService,
@@ -411,6 +422,7 @@ export class NumfmtController extends Disposable implements INumfmtController {
}
private _initInterceptorCellContent() {
+ const renderCache = new ObjectMatrix<{ result: ICellData; parameters: string | number }>();
this.disposeWithMe(
this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
handler: (cell, location, next) => {
@@ -430,8 +442,9 @@ export class NumfmtController extends Disposable implements INumfmtController {
}
let numfmtRes: string = '';
- if (numfmtValue._cache && numfmtValue._cache.parameters === originCellValue.v) {
- return numfmtValue._cache.result;
+ const cache = renderCache.getValue(location.row, location.col);
+ if (cache && cache.parameters === originCellValue.v) {
+ return { ...cell, ...cache.result };
}
const info = getPatternPreview(numfmtValue.pattern, Number(originCellValue.v));
@@ -442,7 +455,7 @@ export class NumfmtController extends Disposable implements INumfmtController {
return next(cell);
}
- const res = { ...cell, v: numfmtRes };
+ const res: ICellData = { v: numfmtRes };
if (info.color) {
const color = this._themeService.getCurrentTheme()[`${info.color}500`];
@@ -452,15 +465,39 @@ export class NumfmtController extends Disposable implements INumfmtController {
}
}
- numfmtValue._cache = {
+ renderCache.setValue(location.row, location.col, {
result: res,
parameters: originCellValue.v as number,
- };
+ });
- return res;
+ return { ...cell, ...res };
},
})
);
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id === SetNumfmtMutation.id) {
+ const params = commandInfo.params as SetNumfmtMutationParams;
+ params.values
+ .map((value) => ({ row: value.row, col: value.col }))
+ .forEach(({ row, col }) => {
+ renderCache.realDeleteValue(row, col);
+ });
+ }
+ })
+ );
+ this.disposeWithMe(
+ toDisposable(
+ this._sheetSkeletonManagerService.currentSkeleton$
+ .pipe(
+ map((skeleton) => skeleton?.sheetId),
+ distinctUntilChanged()
+ )
+ .subscribe(() => {
+ renderCache.reset();
+ })
+ )
+ );
}
private _initRealTimeRenderingInterceptor() {
@@ -496,7 +533,9 @@ export class NumfmtController extends Disposable implements INumfmtController {
selectionRanges: IRange[];
}>((subscribe) => {
const disposableCollection = new DisposableCollection();
- isOpen && subscribe.next({ selectionRanges, disposableCollection });
+ isOpen &&
+ selectionRanges.length &&
+ subscribe.next({ selectionRanges, disposableCollection });
return () => {
disposableCollection.dispose();
};
diff --git a/packages/sheets-plugin-numfmt/src/locale/en-US.ts b/packages/sheets-plugin-numfmt/src/locale/en-US.ts
index 57bbf1b6ca..ffd7fb390b 100644
--- a/packages/sheets-plugin-numfmt/src/locale/en-US.ts
+++ b/packages/sheets-plugin-numfmt/src/locale/en-US.ts
@@ -9,7 +9,7 @@ export const zhCn = {
accounting: '会计',
currency: '货币',
date: '日期',
- thousandthPercentile: '千分为符',
+ thousandthPercentile: '千分位符',
preview: '示例',
decimalLength: '小数位数',
currencyType: '货币类型',
diff --git a/packages/sheets-plugin-numfmt/src/locale/zh-CN.ts b/packages/sheets-plugin-numfmt/src/locale/zh-CN.ts
index 57bbf1b6ca..ffd7fb390b 100644
--- a/packages/sheets-plugin-numfmt/src/locale/zh-CN.ts
+++ b/packages/sheets-plugin-numfmt/src/locale/zh-CN.ts
@@ -9,7 +9,7 @@ export const zhCn = {
accounting: '会计',
currency: '货币',
date: '日期',
- thousandthPercentile: '千分为符',
+ thousandthPercentile: '千分位符',
preview: '示例',
decimalLength: '小数位数',
currencyType: '货币类型',
diff --git a/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts b/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts
index e673938942..f7e730f12d 100644
--- a/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts
+++ b/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts
@@ -1,6 +1,8 @@
import {
Disposable,
ICommandService,
+ ILogService,
+ IUniverInstanceService,
LifecycleStages,
Nullable,
ObjectMatrix,
@@ -10,17 +12,26 @@ import {
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { NumfmtItem } from '../base/types';
+import { FormatType, NumfmtItem } from '../base/types';
import { SetNumfmtMutation } from '../commands/mutations/set.numfmt.mutation';
-import type { INumfmtService, NumfmtItemWithCache } from './type';
+import type { INumfmtService, RefItem } from './type';
@OnLifecycle(LifecycleStages.Ready, NumfmtService)
export class NumfmtService extends Disposable implements INumfmtService {
- _numfmtModel: Map<string, ObjectMatrix<NumfmtItemWithCache>> = new Map();
+ /**
+ * Map<unitID ,<sheetId ,ObjectMatrix>>
+ * @type {Map<string, Map<string, ObjectMatrix<NumfmtItemWithCache>>>}
+ * @memberof NumfmtService
+ */
+ private _numfmtModel: Map<string, Map<string, ObjectMatrix<NumfmtItem>>> = new Map();
- _refAliasModel = new RefAlias<{ count: number; numfmtId: string; pattern: string }>([], ['pattern', 'numfmtId']);
+ private _refAliasModel: Map<string, RefAlias<RefItem, 'numfmtId' | 'pattern'>> = new Map();
- constructor(@Inject(ICommandService) private _commandService: ICommandService) {
+ constructor(
+ @Inject(ICommandService) private _commandService: ICommandService,
+ @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
+ @Inject(ILogService) private _logService: ILogService
+ ) {
super();
this._initModel();
this._initCommands();
@@ -40,31 +51,13 @@ export class NumfmtService extends Disposable implements INumfmtService {
[SetNumfmtMutation].forEach((config) => this.disposeWithMe(this._commandService.registerCommand(config)));
}
- getValue(
- workbookId: string,
- worksheetId: string,
- row: number,
- col: number,
- model?: ObjectMatrix<NumfmtItemWithCache>
- ) {
- const _model: Nullable<ObjectMatrix<NumfmtItemWithCache>> = model || this.getModel(workbookId, worksheetId);
- if (!_model) {
- return null;
- }
- const value = _model.getValue(row, col);
- if (value) {
- const realPattern = this._refAliasModel.getValue(value?.pattern)?.pattern || value?.pattern;
- return value ? { ...value, pattern: realPattern } : null;
- }
- return null;
- }
-
- setValue(workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<NumfmtItem>) {
+ private _setValue(workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<NumfmtItem>) {
let model = this.getModel(workbookId, worksheetId);
if (!model) {
- const key = getModelKey(workbookId, worksheetId);
model = new ObjectMatrix();
- this._numfmtModel.set(key, model);
+ const map = new Map();
+ map.set(worksheetId, model);
+ this._numfmtModel.set(workbookId, map);
}
if (value) {
model.setValue(row, col, value);
@@ -73,27 +66,81 @@ 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) {
+ return '0';
+ }
+ const keyList = refModel.getKeyMap('numfmtId') as string[];
+ const maxId = Math.max(...keyList.map(Number), 0);
+ return `${maxId + 1}`;
+ }
+
+ getValue(workbookId: string, worksheetId: string, row: number, col: number, model?: ObjectMatrix<NumfmtItem>) {
+ const _model: Nullable<ObjectMatrix<NumfmtItem>> = model || this.getModel(workbookId, worksheetId);
+ if (!_model) {
+ return null;
+ }
+ const refMode = this._refAliasModel.get(workbookId);
+ const value = _model.getValue(row, col);
+ if (value && refMode) {
+ const refValue = refMode.getValue(value?.pattern);
+ if (!refValue) {
+ this._logService.error('[Numfmt Service]:', 'RefAliasModel is not match model');
+ return null;
+ }
+ return {
+ pattern: refValue.pattern,
+ type: refValue.type,
+ };
+ }
+ return null;
+ }
+
setValues(
workbookId: string,
worksheetId: string,
- values: Array<{ row: number; col: number; pattern?: string; type: NumfmtItem['type'] }>
+ values: Array<{ row: number; col: number; 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<RefItem, 'numfmtId' | 'pattern'>([], ['pattern', 'numfmtId']);
+ this._refAliasModel.set(workbookId, refModel);
+ }
Object.keys(group).forEach((pattern: string) => {
const values = group[pattern];
const length = values.length;
if (!length) {
return;
}
- let refPattern = this._refAliasModel.getValue(pattern);
+ 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 = this._refAliasModel.getValue(oldValue.pattern);
+ const oldRefPattern = refModel.getValue(oldValue.pattern);
if (oldRefPattern) {
oldRefPattern.count--;
// if (oldRefPattern.count <= 0) {
@@ -101,12 +148,12 @@ export class NumfmtService extends Disposable implements INumfmtService {
// }
}
}
- this.setValue(workbookId, worksheetId, row, col, null);
+ this._setValue(workbookId, worksheetId, row, col, null);
});
if (refPattern) {
const count = refPattern.count - length;
if (count > 0) {
- this._refAliasModel.setValue(pattern, 'count', count);
+ refModel.setValue(pattern, 'count', count);
}
//else {
// this._refAliasModel.deleteValue(pattern);
@@ -114,15 +161,20 @@ export class NumfmtService extends Disposable implements INumfmtService {
}
} else {
if (!refPattern) {
- refPattern = { count: 0, numfmtId: this._getUniqueRefId(), pattern };
- this._refAliasModel.addValue(refPattern);
+ refPattern = {
+ count: 0,
+ numfmtId: this._getUniqueRefId(workbookId),
+ pattern,
+ type: values[0].type,
+ };
+ refModel.addValue(refPattern);
}
values.forEach((item) => {
- const { row, col, type } = item;
+ const { row, col } = item;
if (model) {
const oldValue = this.getValue(workbookId, worksheetId, row, col, model);
if (oldValue && oldValue.pattern) {
- const oldRefPattern = this._refAliasModel.getValue(oldValue.pattern);
+ const oldRefPattern = refModel.getValue(oldValue.pattern);
if (oldRefPattern) {
oldRefPattern.count--;
// if (oldRefPattern.count <= 0) {
@@ -131,9 +183,8 @@ export class NumfmtService extends Disposable implements INumfmtService {
}
}
}
- this.setValue(workbookId, worksheetId, row, col, {
+ this._setValue(workbookId, worksheetId, row, col, {
pattern: refPattern?.numfmtId || pattern!,
- type,
});
refPattern!.count++;
});
@@ -141,34 +192,14 @@ export class NumfmtService extends Disposable implements INumfmtService {
});
}
- _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[]>
- );
- }
-
- _getUniqueRefId() {
- const keyList = this._refAliasModel.getKeyMap('numfmtId') as string[];
- const maxId = Math.max(...keyList.map(Number), 0);
- return `${maxId + 1}`;
+ getModel(workbookId: string, worksheetId: string) {
+ const workbookModel = this._numfmtModel.get(workbookId);
+ const sheetModel = workbookModel?.get(worksheetId);
+ return sheetModel;
}
- getModel(workbookId: string, worksheetId: string) {
- const key = getModelKey(workbookId, worksheetId);
- return this._numfmtModel.get(key);
+ getRefModel(workbookId: string) {
+ const refModel = this._refAliasModel.get(workbookId);
+ return refModel;
}
}
-
-const getModelKey = (workbookId: string, worksheetId: string) => `${workbookId}_${worksheetId}`;
diff --git a/packages/sheets-plugin-numfmt/src/service/type.ts b/packages/sheets-plugin-numfmt/src/service/type.ts
index 7cd8d5d0b0..65a1a82240 100644
--- a/packages/sheets-plugin-numfmt/src/service/type.ts
+++ b/packages/sheets-plugin-numfmt/src/service/type.ts
@@ -1,8 +1,8 @@
import type { ICellData, Nullable, ObjectMatrix } from '@univerjs/core';
-import { LifecycleStages, runOnLifecycle } from '@univerjs/core';
+import { LifecycleStages, RefAlias, runOnLifecycle } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
-import { NumfmtItem } from '../base/types/index';
+import { FormatType, NumfmtItem } from '../base/types/index';
export type NumfmtItemWithCache = NumfmtItem & {
// when change parameters or pattern, the cache is cleared follow mutation execute
@@ -10,17 +10,19 @@ export type NumfmtItemWithCache = NumfmtItem & {
result: ICellData;
parameters: number; // The parameter that was last calculated
};
+ type: FormatType;
};
+export type RefItem = NumfmtItem & { count: number; numfmtId: string; type: FormatType };
+
export interface INumfmtService {
getValue(workbookId: string, worksheetId: string, row: number, col: number): Nullable<NumfmtItemWithCache>;
- getModel(workbookId: string, worksheetId: string): Nullable<ObjectMatrix<NumfmtItemWithCache>>;
-
- setValue(workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<NumfmtItem>): void;
+ getModel(workbookId: string, worksheetId: string): Nullable<ObjectMatrix<NumfmtItem>>;
setValues(
workbookId: string,
worksheetId: string,
- values: Array<{ row: number; col: number; pattern?: string; type: NumfmtItem['type'] }>
+ values: Array<{ row: number; col: number; pattern?: string; type: FormatType }>
): void;
+ getRefModel(workbookId: string): Nullable<RefAlias<RefItem, 'numfmtId' | 'pattern'>>;
}
export const INumfmtService = createIdentifier<INumfmtService>('INumfmtService');