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(sheet): select currency add habit (#585)
Gpound.liu0e62c9f10edf
diff --git a/packages/base-sheets/src/base-sheets-plugin.ts b/packages/base-sheets/src/base-sheets-plugin.tsindex 76de22253a..036c14b379 100644--- a/packages/base-sheets/src/base-sheets-plugin.ts+++ b/packages/base-sheets/src/base-sheets-plugin.ts@@ -1,10 +1,13 @@import { ICommandService, LocaleService, Plugin, PLUGIN_NAMES, PluginType } from '@univerjs/core';-import { Dependency, Inject, Injector } from '@wendellhu/redi';+import type { Dependency } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';import { BasicWorksheetController } from './controllers/basic-worksheet.controller';import { MergeCellController } from './controllers/merge-cell.controller';import { enUS } from './locale';import { BorderStyleManagerService } from './services/border-style-manager.service';+import { NumfmtService } from './services/numfmt/numfmt.service';+import { INumfmtService } from './services/numfmt/type';import { SheetPermissionService } from './services/permission';import { RefRangeService } from './services/ref-range/ref-range.service';import { SelectionManagerService } from './services/selection-manager.service';@@ -39,6 +42,8 @@ export class SheetPlugin extends Plugin {[SelectionManagerService],[RefRangeService],[SheetPermissionService],+ [INumfmtService, { useClass: NumfmtService }],+// controllers[BasicWorksheetController],[MergeCellController],diff --git a/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.ts b/packages/base-sheets/src/commands/mutations/set-numfmt-mutation.tssimilarity index 72%rename from packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.tsrename to packages/base-sheets/src/commands/mutations/set-numfmt-mutation.tsindex 66a28c698e..5cc258daad 100644--- a/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/set-numfmt-mutation.ts@@ -1,15 +1,16 @@-import { CommandType, ICommand } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';+import type { ICommand } from '@univerjs/core';+import { CommandType } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';-import { FormatType } from '../../base/types';-import { INumfmtService } from '../../service/type';+import type { FormatType } from '../../services/numfmt/type';+import { INumfmtService } from '../../services/numfmt/type';export const factorySetNumfmtUndoMutation = (accessor: IAccessor,- option: SetNumfmtMutationParams-): SetNumfmtMutationParams => {+ option: ISetNumfmtMutationParams+): ISetNumfmtMutationParams => {const numfmtService = accessor.get(INumfmtService);- const undos: SetNumfmtMutationParams = {+ const undos: ISetNumfmtMutationParams = {...option,values: option.values.map((item) => {@@ -25,13 +26,13 @@ export const factorySetNumfmtUndoMutation = (return undos;};-export type SetNumfmtMutationParams = {+export interface ISetNumfmtMutationParams {values: Array<{ pattern?: string; row: number; col: number; type?: FormatType }>;workbookId: string;worksheetId: string;-};+}-export const SetNumfmtMutation: ICommand<SetNumfmtMutationParams> = {+export const SetNumfmtMutation: ICommand<ISetNumfmtMutationParams> = {id: 'sheet.mutation.set.numfmt',type: CommandType.MUTATION,handler: (accessor: IAccessor, params) => {diff --git a/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts b/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.tsindex ab5f84beb8..2a1096ad55 100644--- a/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts@@ -1,6 +1,7 @@-import { IRowAutoHeightInfo } from '@univerjs/base-render';-import { CommandType, IMutation, IRange, IUniverInstanceService, Nullable, ObjectArray } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';+import type { IRowAutoHeightInfo } from '@univerjs/base-render';+import type { IMutation, IRange, Nullable } from '@univerjs/core';+import { CommandType, IUniverInstanceService, ObjectArray } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';const MAXIMUM_ROW_HEIGHT = 2000;diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.tsindex f96ae4640c..10c6759d2e 100644--- a/packages/base-sheets/src/index.ts+++ b/packages/base-sheets/src/index.ts@@ -179,6 +179,8 @@ 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';@@ -212,6 +214,8 @@ export {} from './commands/mutations/set-worksheet-row-height.mutation';export { type ISetSelectionsOperationParams, SetSelectionsOperation } from './commands/operations/selection.operation';export { type ISheetCommandSharedParams } from './commands/utils/interface';+export type { FormatType, INumfmtItem, INumfmtItemWithCache } from './services/numfmt/type';+export { INumfmtService } from './services/numfmt/type';export { RefRangeService } from './services/ref-range/ref-range.service';export type { EffectRefRangeParams } from './services/ref-range/type';export { EffectRefRangId, OperatorType } from './services/ref-range/type';diff --git a/packages/sheets-plugin-numfmt/src/__tests__/numfmt.service.test.ts b/packages/base-sheets/src/services/__tests__/numfmt.service.test.tssimilarity index 64%rename from packages/sheets-plugin-numfmt/src/__tests__/numfmt.service.test.tsrename to packages/base-sheets/src/services/__tests__/numfmt.service.test.tsindex 8ded8492b4..cd16c01b99 100644--- a/packages/sheets-plugin-numfmt/src/__tests__/numfmt.service.test.ts+++ b/packages/base-sheets/src/services/__tests__/numfmt.service.test.ts@@ -1,21 +1,28 @@+import type { ISetNumfmtMutationParams } from '@univerjs/base-sheets';+import type { Univer } from '@univerjs/core';import { ICommandService, IUniverInstanceService } from '@univerjs/core';-import { Injector } from '@wendellhu/redi';-import { beforeEach, describe, expect, it } from 'vitest';+import type { Injector } from '@wendellhu/redi';+import { afterEach, 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';+import { SetNumfmtMutation } from '../../commands/mutations/set-numfmt-mutation';+import { NumfmtService } from '../numfmt/numfmt.service';+import { INumfmtService } from '../numfmt/type';+import { createTestBase } from './util';describe('test numfmt service', () => {+ let univer: Univer;let get: Injector['get'];let commandService: ICommandService;beforeEach(() => {const testBed = createTestBase(undefined, [[INumfmtService, { useClass: NumfmtService }]]);+ univer = testBed.univer;get = testBed.get;commandService = get(ICommandService);});+ afterEach(() => {+ univer.dispose();+ });it('model set', () => {const univerInstanceService = get(IUniverInstanceService);@@ -24,7 +31,7 @@ describe('test numfmt service', () => {const sheet = workbook.getActiveSheet();const workbookId = workbook.getUnitId();const worksheetId = sheet.getSheetId();- const params: SetNumfmtMutationParams = {+ const params: ISetNumfmtMutationParams = {workbookId,worksheetId,values: [{ row: 1, col: 1, pattern: 'asdws' }],@@ -43,7 +50,7 @@ describe('test numfmt service', () => {const sheet = workbook.getActiveSheet();const workbookId = workbook.getUnitId();const worksheetId = sheet.getSheetId();- const params: SetNumfmtMutationParams = {+ const params: ISetNumfmtMutationParams = {workbookId,worksheetId,values: [{ row: 1, col: 1, pattern: 'asdws' }],@@ -63,7 +70,7 @@ describe('test numfmt service', () => {const sheet = workbook.getActiveSheet();const workbookId = workbook.getUnitId();const worksheetId = sheet.getSheetId();- const params: SetNumfmtMutationParams = {+ const params: ISetNumfmtMutationParams = {workbookId,worksheetId,values: [{ row: 1, col: 1, pattern: 'asdws' }],@@ -83,7 +90,7 @@ describe('test numfmt service', () => {const sheet = workbook.getActiveSheet();const workbookId = workbook.getUnitId();const worksheetId = sheet.getSheetId();- const params: SetNumfmtMutationParams = {+ const params: ISetNumfmtMutationParams = {workbookId,worksheetId,values: [{ row: 1, col: 1, pattern: 'asdws' }],@@ -94,4 +101,32 @@ describe('test numfmt service', () => {expect(refModel?.getValue('asdws')?.count).toEqual(0);expect(refModel?.getValue('1')?.count).toEqual(0);});++ it('model delete', () => {+ const univerInstanceService = get(IUniverInstanceService);+ const numfmtService = get(INumfmtService);+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();+ const workbookId = workbook.getUnitId();+ const sheets = workbook.getSheets();+ const pattern = 'asdws';+ const params1: ISetNumfmtMutationParams = {+ workbookId,+ worksheetId: sheets[0].getSheetId(),+ values: [{ row: 1, col: 1, pattern }],+ };+ commandService.executeCommand(SetNumfmtMutation.id, params1);+ const params2: ISetNumfmtMutationParams = {+ workbookId,+ worksheetId: sheets[1].getSheetId(),+ values: [{ row: 1, col: 1, pattern }],+ };+ commandService.executeCommand(SetNumfmtMutation.id, params2);+ const refModel = numfmtService.getRefModel(workbookId);+ const model1 = numfmtService.getModel(workbookId, sheets[0].getSheetId());+ const model2 = numfmtService.getModel(workbookId, sheets[1].getSheetId());+ expect(refModel?.getValue(pattern)?.count).toBe(2);+ expect(model1?.getValue(1, 1)?.pattern).toBe('1');+ expect(model2?.getValue(1, 1)?.pattern).toBe('1');+ expect(refModel?.getValue(model2?.getValue(1, 1)?.pattern!)?.pattern).toBe(pattern);+ });});diff --git a/packages/base-sheets/src/services/__tests__/util.ts b/packages/base-sheets/src/services/__tests__/util.tsindex ae541adedd..09989079ba 100644--- a/packages/base-sheets/src/services/__tests__/util.ts+++ b/packages/base-sheets/src/services/__tests__/util.ts@@ -1,13 +1,7 @@-import {- ILogService,- IUniverInstanceService,- IWorkbookData,- LocaleType,- Plugin,- PluginType,- Univer,-} from '@univerjs/core';-import { Dependency, Inject, Injector } from '@wendellhu/redi';+import type { IWorkbookData } from '@univerjs/core';+import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';+import type { Dependency } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';export const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {id: 'test',@@ -26,10 +20,23 @@ export const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {},},},+ sheet2: {+ id: 'sheet2',+ cellData: {+ '0': {+ '0': {+ v: 'A1',+ },+ '1': {+ v: 'A2',+ },+ },+ },+ },},locale: LocaleType.EN_US,name: '',- sheetOrder: [],+ sheetOrder: ['sheet1'],styles: {},};diff --git a/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts b/packages/base-sheets/src/services/numfmt/numfmt.service.tssimilarity index 86%rename from packages/sheets-plugin-numfmt/src/service/numfmt.service.tsrename to packages/base-sheets/src/services/numfmt/numfmt.service.tsindex 4cf9b3a1b4..f4a9264ee7 100644--- a/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts+++ b/packages/base-sheets/src/services/numfmt/numfmt.service.ts@@ -13,24 +13,20 @@ import {} from '@univerjs/core';import { Inject } from '@wendellhu/redi';-import { SHEET_NUMFMT_PLUGIN } from '../base/const/PLUGIN_NAME';-import type { FormatType, NumfmtItem } from '../base/types';-import { SetNumfmtMutation } from '../commands/mutations/set.numfmt.mutation';-import type { INumfmtService, ISnapshot, RefItem } from './type';+import { SetNumfmtMutation } from '../../commands/mutations/set-numfmt-mutation';+import type { FormatType, INumfmtItem, INumfmtService, IRefItem, ISnapshot } from './type';+const SHEET_NUMFMT_PLUGIN = 'SHEET_NUMFMT_PLUGIN';@OnLifecycle(LifecycleStages.Ready, NumfmtService)export class NumfmtService extends Disposable implements INumfmtService {/**- * @type {Map<WorkbookId, Map<worksheetId, ObjectMatrix<NumfmtItemWithCache>>>}- */- private _numfmtModel: Map<string, Map<string, ObjectMatrix<NumfmtItem>>> = new Map();-- /**- * @private- * @type {(Map<workbookId, RefAlias<RefItem, 'numfmtId' | 'pattern'>>)}+ * Map<unitID ,<sheetId ,ObjectMatrix>>+ * @type {Map<string, Map<string, ObjectMatrix<INumfmtItemWithCache>>>}* @memberof NumfmtService*/- private _refAliasModel: Map<string, RefAlias<RefItem, 'numfmtId' | 'pattern'>> = new Map();+ private _numfmtModel: Map<string, Map<string, ObjectMatrix<INumfmtItem>>> = new Map();++ private _refAliasModel: Map<string, RefAlias<IRefItem, 'numfmtId' | 'pattern'>> = new Map();constructor(@Inject(ICommandService) private _commandService: ICommandService,@@ -60,15 +56,15 @@ export class NumfmtService extends Disposable implements INumfmtService {if (model) {const parseModel = Object.keys(model).reduce((result, sheetId) => {- result.set(sheetId, new ObjectMatrix<NumfmtItem>(model[sheetId]));+ result.set(sheetId, new ObjectMatrix<INumfmtItem>(model[sheetId]));return result;- }, new Map<string, ObjectMatrix<NumfmtItem>>());+ }, new Map<string, ObjectMatrix<INumfmtItem>>());this._numfmtModel.set(unitID, parseModel);}if (refModel) {this._refAliasModel.set(unitID,- new RefAlias<RefItem, 'numfmtId' | 'pattern'>(refModel, ['numfmtId', 'pattern'])+ new RefAlias<IRefItem, 'numfmtId' | 'pattern'>(refModel, ['numfmtId', 'pattern']));}},@@ -106,7 +102,7 @@ export class NumfmtService extends Disposable implements INumfmtService {result[key] = object.toJSON();return result;},- {} as Record<string, ObjectMatrixPrimitiveType<NumfmtItem>>+ {} as Record<string, ObjectMatrixPrimitiveType<INumfmtItem>>);// Filter the count equal 0 when snapshot save.// It is typically cleaned up once every 100 versions.@@ -129,13 +125,14 @@ export class NumfmtService extends Disposable implements INumfmtService {[SetNumfmtMutation].forEach((config) => this.disposeWithMe(this._commandService.registerCommand(config)));}- private _setValue(workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<NumfmtItem>) {+ private _setValue(workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<INumfmtItem>) {let model = this.getModel(workbookId, worksheetId);if (!model) {- model = new ObjectMatrix();- const map = new Map();- map.set(worksheetId, model);- this._numfmtModel.set(workbookId, map);+ const worksheetMap = this._numfmtModel.get(workbookId) || new Map<string, ObjectMatrix<INumfmtItem>>();+ const worksheetModel = worksheetMap.get(worksheetId) || new ObjectMatrix<INumfmtItem>();+ worksheetMap.set(worksheetId, worksheetModel);+ this._numfmtModel.set(workbookId, worksheetMap);+ model = worksheetModel;}if (value) {model.setValue(row, col, value);@@ -172,8 +169,8 @@ export class NumfmtService extends Disposable implements INumfmtService {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);+ getValue(workbookId: string, worksheetId: string, row: number, col: number, model?: ObjectMatrix<INumfmtItem>) {+ const _model: Nullable<ObjectMatrix<INumfmtItem>> = model || this.getModel(workbookId, worksheetId);if (!_model) {return null;}@@ -203,7 +200,7 @@ export class NumfmtService extends Disposable implements INumfmtService {const model = this.getModel(workbookId, worksheetId);let refModel = this._refAliasModel.get(workbookId)!;if (!refModel) {- refModel = new RefAlias<RefItem, 'numfmtId' | 'pattern'>([], ['pattern', 'numfmtId']);+ refModel = new RefAlias<IRefItem, 'numfmtId' | 'pattern'>([], ['pattern', 'numfmtId']);this._refAliasModel.set(workbookId, refModel);}Object.keys(group).forEach((pattern: string) => {diff --git a/packages/sheets-plugin-numfmt/src/service/type.ts b/packages/base-sheets/src/services/numfmt/type.tssimilarity index 50%rename from packages/sheets-plugin-numfmt/src/service/type.tsrename to packages/base-sheets/src/services/numfmt/type.tsindex f090731955..7434573b75 100644--- a/packages/sheets-plugin-numfmt/src/service/type.ts+++ b/packages/base-sheets/src/services/numfmt/type.ts@@ -2,9 +2,27 @@ import type { ICellData, Nullable, ObjectMatrix, ObjectMatrixPrimitiveType, RefAimport { LifecycleStages, runOnLifecycle } from '@univerjs/core';import { createIdentifier } from '@wendellhu/redi';-import type { FormatType, NumfmtItem } from '../base/types/index';+// eslint-disable-next-line @typescript-eslint/consistent-type-definitions+export type INumfmtItem = {+ pattern: string;+};++export type FormatType =+ | 'currency'+ | 'date'+ | 'datetime'+ | 'error'+ | 'fraction'+ | 'general'+ | 'grouped'+ | 'number'+ | 'percent'+ | 'scientific'+ | 'text'+ | 'time'+ | 'unknown';-export type NumfmtItemWithCache = NumfmtItem & {+export type INumfmtItemWithCache = INumfmtItem & {// when change parameters or pattern, the cache is cleared follow mutation execute_cache?: {result: ICellData;@@ -12,22 +30,28 @@ export type NumfmtItemWithCache = NumfmtItem & {};type: FormatType;};-export type RefItem = NumfmtItem & { count: number; numfmtId: string; type: FormatType };+export type IRefItem = INumfmtItem & { 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<NumfmtItem>>;+ getValue(+ workbookId: string,+ worksheetId: string,+ row: number,+ col: number,+ model?: ObjectMatrix<INumfmtItem>+ ): Nullable<INumfmtItemWithCache>;+ getModel(workbookId: string, worksheetId: string): Nullable<ObjectMatrix<INumfmtItem>>;setValues(workbookId: string,worksheetId: string,values: Array<{ row: number; col: number; pattern?: string; type: FormatType }>): void;- getRefModel(workbookId: string): Nullable<RefAlias<RefItem, 'numfmtId' | 'pattern'>>;+ getRefModel(workbookId: string): Nullable<RefAlias<IRefItem, 'numfmtId' | 'pattern'>>;}export interface ISnapshot {- model: Record<string, ObjectMatrixPrimitiveType<NumfmtItem>>;- refModel: RefItem[];+ model: Record<string, ObjectMatrixPrimitiveType<INumfmtItem>>;+ refModel: IRefItem[];}export const INumfmtService = createIdentifier<INumfmtService>('INumfmtService');diff --git a/packages/base-sheets/src/services/ref-range/ref-range.service.ts b/packages/base-sheets/src/services/ref-range/ref-range.service.tsindex 402e51e6f4..0fdfcc141e 100644--- a/packages/base-sheets/src/services/ref-range/ref-range.service.ts+++ b/packages/base-sheets/src/services/ref-range/ref-range.service.ts@@ -1,7 +1,6 @@+import type { IMutationInfo, IRange } from '@univerjs/core';import {Disposable,- IMutationInfo,- IRange,IUniverInstanceService,LifecycleStages,OnLifecycle,@@ -9,12 +8,17 @@ import {SheetInterceptorService,toDisposable,} from '@univerjs/core';-import { IDisposable, Inject } from '@wendellhu/redi';+import type { IDisposable } from '@wendellhu/redi';+import { Inject } from '@wendellhu/redi';import { SelectionManagerService } from '../selection-manager.service';-import { EffectRefRangeParams, EffectRefRangId } from './type';+import type { EffectRefRangeParams } from './type';+import { EffectRefRangId } from './type';-type RefRangCallback = (params: EffectRefRangeParams) => {+type RefRangCallback = (+ params: EffectRefRangeParams,+ preValues: Array<{ redos: IMutationInfo[]; undos: IMutationInfo[] }>+) => {redos: IMutationInfo[];undos: IMutationInfo[];};@@ -35,7 +39,7 @@ export class RefRangeService extends Disposable {private _refRangeManagerMap = new Map<string, Map<string, Set<RefRangCallback>>>();- private serializer = createRangeSerializer();+ private _serializer = createRangeSerializer();private _onRefRangeChange = () => {this._sheetInterceptorService.interceptCommand({@@ -127,7 +131,14 @@ export class RefRangeService extends Disposable {};const cbList = getEffectsCbList() || [];const result = cbList- .map((cb) => cb(command))+ .reduce(+ (result, currentFn) => {+ const v = currentFn(command, result);+ result.push(v);+ return result;+ },+ [] as Array<{ redos: IMutationInfo[]; undos: IMutationInfo[] }>+ ).reduce((result, currentValue) => {result.redos.push(...currentValue.redos);@@ -136,6 +147,8 @@ export class RefRangeService extends Disposable {},{ redos: [], undos: [] });+ // TODO@gggpound: The mutations need to be merge by mutation.id+return result;},});@@ -151,7 +164,7 @@ export class RefRangeService extends Disposable {keyList.forEach((key) => {const cbList = manager.get(key);- const range = this.serializer.deserialize(key);+ const range = this._serializer.deserialize(key);// Todo@Gggpound : How to reduce this calculationif (effectRanges.some((item) => Rectangle.intersects(item, range))) {cbList &&@@ -174,7 +187,7 @@ export class RefRangeService extends Disposable {const workbookId = _workbookId || getWorkbookId(this._univerInstanceService);const worksheetId = _worksheetId || getWorksheetId(this._univerInstanceService);const refRangeManagerId = getRefRangId(workbookId, worksheetId);- const rangeString = this.serializer.serialize(range);+ const rangeString = this._serializer.serialize(range);let manager = this._refRangeManagerMap.get(refRangeManagerId) as Map<string, Set<RefRangCallback>>;if (!manager) {diff --git a/packages/sheets-plugin-numfmt/src/__tests__/createTestBase.ts b/packages/sheets-plugin-numfmt/src/__tests__/createTestBase.tsdeleted file mode 100644index e00ef9c3e8..0000000000--- a/packages/sheets-plugin-numfmt/src/__tests__/createTestBase.ts+++ /dev/null@@ -1,72 +0,0 @@-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/base/const/CURRENCY-SYMBOLS.ts b/packages/sheets-plugin-numfmt/src/base/const/CURRENCY-SYMBOLS.tsindex a50d49b3e7..f2403cc215 100644--- a/packages/sheets-plugin-numfmt/src/base/const/CURRENCY-SYMBOLS.ts+++ b/packages/sheets-plugin-numfmt/src/base/const/CURRENCY-SYMBOLS.ts@@ -1,13 +1,13 @@export const currencySymbols = [- '¤','$','£','¥',+ '¤','֏','؋','৳','฿',- '៛',+ // '៛','₡','₦','₩',diff --git a/packages/sheets-plugin-numfmt/src/base/types/index.ts b/packages/sheets-plugin-numfmt/src/base/types/index.tsindex 64ecb04a9d..6c41d0b422 100644--- a/packages/sheets-plugin-numfmt/src/base/types/index.ts+++ b/packages/sheets-plugin-numfmt/src/base/types/index.ts@@ -1,23 +1,8 @@-export type BusinessComponentProps = {+import type { MutableRefObject } from 'react';++export interface IBusinessComponentProps {onChange: (result: string) => void;defaultValue: number;defaultPattern: string;-};-export type NumfmtItem = {- pattern: string;-};--export type FormatType =- | 'currency'- | 'date'- | 'datetime'- | 'error'- | 'fraction'- | 'general'- | 'grouped'- | 'number'- | 'percent'- | 'scientific'- | 'text'- | 'time'- | 'unknown';+ action: MutableRefObject<() => string | null>;+}diff --git a/packages/sheets-plugin-numfmt/src/commands/commands/add.decimal.command.ts b/packages/sheets-plugin-numfmt/src/commands/commands/add.decimal.command.tsindex cf883e11ce..c866ec529c 100644--- a/packages/sheets-plugin-numfmt/src/commands/commands/add.decimal.command.ts+++ b/packages/sheets-plugin-numfmt/src/commands/commands/add.decimal.command.ts@@ -1,10 +1,11 @@-import { SelectionManagerService } from '@univerjs/base-sheets';-import { CommandType, ICommand, ICommandService, IUniverInstanceService, Range } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';+import { INumfmtService, SelectionManagerService } from '@univerjs/base-sheets';+import type { ICommand } from '@univerjs/core';+import { CommandType, ICommandService, IUniverInstanceService, Range } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';-import { INumfmtService } from '../../service/type';import { getDecimalFromPattern, isPatternEqualWithoutDecimal, setPatternDecimal } from '../../utils/decimal';-import { SetNumfmtCommand, SetNumfmtCommandParams } from './set.numfmt.command';+import type { ISetNumfmtCommandParams } from './set.numfmt.command';+import { SetNumfmtCommand } from './set.numfmt.command';export const AddDecimalCommand: ICommand = {id: 'sheet.command.numfmt.add.decimal.command',@@ -37,7 +38,7 @@ export const AddDecimalCommand: ICommand = {});const decimals = maxDecimals + 1;const pattern = setPatternDecimal(`0${decimals > 0 ? '.0' : ''}`, decimals);- const values: SetNumfmtCommandParams['values'] = [];+ const values: ISetNumfmtCommandParams['values'] = [];selections.forEach((selection) => {Range.foreach(selection.range, (row, col) => {diff --git a/packages/sheets-plugin-numfmt/src/commands/commands/set.currency.command.ts b/packages/sheets-plugin-numfmt/src/commands/commands/set.currency.command.tsindex 0e5d9e97e5..7cfb2ce88b 100644--- a/packages/sheets-plugin-numfmt/src/commands/commands/set.currency.command.ts+++ b/packages/sheets-plugin-numfmt/src/commands/commands/set.currency.command.ts@@ -1,9 +1,11 @@import { SelectionManagerService } from '@univerjs/base-sheets';-import { CommandType, ICommand, ICommandService, Range } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';+import type { ICommand } from '@univerjs/core';+import { CommandType, ICommandService, Range } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';import { CURRENCYFORMAT } from '../../base/const/FORMATDETAIL';-import { SetNumfmtCommand, SetNumfmtCommandParams } from './set.numfmt.command';+import type { ISetNumfmtCommandParams } from './set.numfmt.command';+import { SetNumfmtCommand } from './set.numfmt.command';export const SetCurrencyCommand: ICommand = {id: 'sheet.command.numfmt.set.currency',@@ -16,7 +18,7 @@ export const SetCurrencyCommand: ICommand = {if (!selections || !selections.length) {return false;}- const values: SetNumfmtCommandParams['values'] = [];+ const values: ISetNumfmtCommandParams['values'] = [];const suffix = CURRENCYFORMAT[0].suffix('¥');diff --git a/packages/sheets-plugin-numfmt/src/commands/commands/set.numfmt.command.ts b/packages/sheets-plugin-numfmt/src/commands/commands/set.numfmt.command.tsindex 57b7fb47b0..9bf4424c78 100644--- a/packages/sheets-plugin-numfmt/src/commands/commands/set.numfmt.command.ts+++ b/packages/sheets-plugin-numfmt/src/commands/commands/set.numfmt.command.ts@@ -1,14 +1,14 @@-import { CommandType, ICommand, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';+import type { FormatType } from '@univerjs/base-sheets';+import { factorySetNumfmtUndoMutation, SetNumfmtMutation } from '@univerjs/base-sheets';+import type { ICommand } from '@univerjs/core';+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';-import { FormatType } from '../../base/types';-import { factorySetNumfmtUndoMutation, SetNumfmtMutation } from '../mutations/set.numfmt.mutation';--export type SetNumfmtCommandParams = {+export interface ISetNumfmtCommandParams {values: Array<{ pattern?: string; row: number; col: number; type?: FormatType }>;-};+}-export const SetNumfmtCommand: ICommand<SetNumfmtCommandParams> = {+export const SetNumfmtCommand: ICommand<ISetNumfmtCommandParams> = {id: 'sheet.command.numfmt.set.numfmt',type: CommandType.COMMAND,handler: (accessor: IAccessor, params) => {diff --git a/packages/sheets-plugin-numfmt/src/commands/commands/subtract.decimal.command.ts b/packages/sheets-plugin-numfmt/src/commands/commands/subtract.decimal.command.tsindex a18e19f761..2c5dfddad9 100644--- a/packages/sheets-plugin-numfmt/src/commands/commands/subtract.decimal.command.ts+++ b/packages/sheets-plugin-numfmt/src/commands/commands/subtract.decimal.command.ts@@ -1,10 +1,11 @@-import { SelectionManagerService } from '@univerjs/base-sheets';-import { CommandType, ICommand, ICommandService, IUniverInstanceService, Range } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';+import { INumfmtService, SelectionManagerService } from '@univerjs/base-sheets';+import type { ICommand } from '@univerjs/core';+import { CommandType, ICommandService, IUniverInstanceService, Range } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';-import { INumfmtService } from '../../service/type';import { getDecimalFromPattern, isPatternEqualWithoutDecimal, setPatternDecimal } from '../../utils/decimal';-import { SetNumfmtCommand, SetNumfmtCommandParams } from './set.numfmt.command';+import type { ISetNumfmtCommandParams } from './set.numfmt.command';+import { SetNumfmtCommand } from './set.numfmt.command';export const SubtractDecimalCommand: ICommand = {id: 'sheet.command.numfmt.subtract.decimal.command',@@ -38,7 +39,7 @@ export const SubtractDecimalCommand: ICommand = {const decimals = maxDecimals - 1;const pattern = setPatternDecimal(`0${decimals > 0 ? '.0' : '.'}`, decimals);- const values: SetNumfmtCommandParams['values'] = [];+ const values: ISetNumfmtCommandParams['values'] = [];selections.forEach((selection) => {Range.foreach(selection.range, (row, col) => {diff --git a/packages/sheets-plugin-numfmt/src/commands/operators/close.numfmt.panel.operator.ts b/packages/sheets-plugin-numfmt/src/commands/operators/close.numfmt.panel.operator.tsindex 759d85ac9b..bff38594f6 100644--- a/packages/sheets-plugin-numfmt/src/commands/operators/close.numfmt.panel.operator.ts+++ b/packages/sheets-plugin-numfmt/src/commands/operators/close.numfmt.panel.operator.ts@@ -1,4 +1,5 @@-import { CommandType, ICommand } from '@univerjs/core';+import type { ICommand } from '@univerjs/core';+import { CommandType } from '@univerjs/core';export const CloseNumfmtPanelOperator: ICommand = {id: 'sheet.operation.close.numfmt.panel',diff --git a/packages/sheets-plugin-numfmt/src/commands/operators/open.numfmt.panel.operator.ts b/packages/sheets-plugin-numfmt/src/commands/operators/open.numfmt.panel.operator.tsindex e726fa2b92..590fa98c3a 100644--- a/packages/sheets-plugin-numfmt/src/commands/operators/open.numfmt.panel.operator.ts+++ b/packages/sheets-plugin-numfmt/src/commands/operators/open.numfmt.panel.operator.ts@@ -1,5 +1,6 @@-import { CommandType, ICommand } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';+import type { ICommand } from '@univerjs/core';+import { CommandType } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';import { INumfmtController } from '../../controllers/type';diff --git a/packages/sheets-plugin-numfmt/src/components/accounting/index.tsx b/packages/sheets-plugin-numfmt/src/components/accounting/index.tsxindex f721335026..b0133bc220 100644--- a/packages/sheets-plugin-numfmt/src/components/accounting/index.tsx+++ b/packages/sheets-plugin-numfmt/src/components/accounting/index.tsx@@ -2,35 +2,39 @@ import { LocaleService } from '@univerjs/core';import { InputNumber, Select } from '@univerjs/design';import { useDependency } from '@wendellhu/redi/react-bindings';import type { FC } from 'react';-import React, { useEffect, useMemo, useState } from 'react';+import React, { useContext, useMemo, useState } from 'react';-import type { BusinessComponentProps } from '../../base/types';+import type { IBusinessComponentProps } from '../../base/types';+import { UserHabitCurrencyContext } from '../../context/user-habit';import { getCurrencyType } from '../../utils/currency';import { getDecimalFromPattern, setPatternDecimal } from '../../utils/decimal';-import { getCurrencyOptions } from '../../utils/options';export const isAccountingPanel = (pattern: string) => {const type = getCurrencyType(pattern);return !!type && pattern.startsWith('_(');};-export const AccountingPanel: FC<BusinessComponentProps> = (props) => {+export const AccountingPanel: FC<IBusinessComponentProps> = (props) => {const [decimal, decimalSet] = useState(() => getDecimalFromPattern(props.defaultPattern || '', 2));- const [suffix, suffixSet] = useState(- () => getCurrencyType(props.defaultPattern || '') || getCurrencyOptions()[0].value- );+ const userHabitCurrency = useContext(UserHabitCurrencyContext);+ const [suffix, suffixSet] = useState(() => getCurrencyType(props.defaultPattern) || userHabitCurrency[0]);+ const options = useMemo(() => userHabitCurrency.map((key) => ({ label: key, value: key })), []);+const localeService = useDependency(LocaleService);const t = localeService.t;- const pattern = useMemo(- () => setPatternDecimal(`_("${suffix}"* #,##0${decimal > 0 ? '.0' : ''}_)`, decimal),- [suffix, decimal]- );- const currencyOptions = useMemo(getCurrencyOptions, []);+ props.action.current = () => setPatternDecimal(`_("${suffix}"* #,##0${decimal > 0 ? '.0' : ''}_)`, decimal);++ const onSelect = (v: string) => {+ suffixSet(v);+ props.onChange(setPatternDecimal(`_("${v}"* #,##0${decimal > 0 ? '.0' : ''}_)`, decimal));+ };- useEffect(() => {- props.onChange(pattern);- }, [pattern]);+ const onDecimalChange = (v: number | null) => {+ const decimal = v || 0;+ decimalSet(decimal);+ props.onChange(setPatternDecimal(`_("${suffix}"* #,##0${decimal > 0 ? '.0' : ''}_)`, decimal));+ };return (<div>@@ -39,14 +43,14 @@ export const AccountingPanel: FC<BusinessComponentProps> = (props) => {<div className="label">{t('sheet.numfmt.decimalLength')}</div><div className="m-t-8 w-120">- <InputNumber value={decimal} max={20} min={0} onChange={(value) => decimalSet(value || 0)} />+ <InputNumber value={decimal} max={20} min={0} onChange={onDecimalChange} /></div></div><div className="option"><div className="label">{t('sheet.numfmt.currencyType')}</div><div className="m-t-8 w-140">- <Select onChange={suffixSet} options={currencyOptions} value={suffix} />+ <Select onChange={onSelect} options={options} value={suffix} /></div></div></div>diff --git a/packages/sheets-plugin-numfmt/src/components/currency/index.tsx b/packages/sheets-plugin-numfmt/src/components/currency/index.tsxindex 050f71a241..21737a3ed7 100644--- a/packages/sheets-plugin-numfmt/src/components/currency/index.tsx+++ b/packages/sheets-plugin-numfmt/src/components/currency/index.tsx@@ -4,61 +4,54 @@ import { LocaleService } from '@univerjs/core';import { InputNumber, Select, SelectList } from '@univerjs/design';import { useDependency } from '@wendellhu/redi/react-bindings';import type { FC } from 'react';-import React, { useEffect, useMemo, useRef, useState } from 'react';+import React, { useContext, useMemo, useState } from 'react';-import type { BusinessComponentProps } from '../../base/types';+import type { IBusinessComponentProps } from '../../base/types';+import { UserHabitCurrencyContext } from '../../context/user-habit';import { getCurrencyType } from '../../utils/currency';import { getDecimalFromPattern, isPatternEqualWithoutDecimal, setPatternDecimal } from '../../utils/decimal';-import { getCurrencyFormatOptions, getCurrencyOptions } from '../../utils/options';+import { getCurrencyFormatOptions } from '../../utils/options';export const isCurrencyPanel = (pattern: string) => {const type = getCurrencyType(pattern);return !!type && !pattern.startsWith('_(');};-const useEffectWithoutFirst = (cb: () => () => void, dep: unknown[]) => {- const ref = useRef(false);- useEffect(() => {- if (!ref.current) {- ref.current = true;- return;- }- return cb();- }, dep);-};-export const CurrencyPanel: FC<BusinessComponentProps> = (props) => {++export const CurrencyPanel: FC<IBusinessComponentProps> = (props) => {const localeService = useDependency(LocaleService);const t = localeService.t;+ const userHabitCurrency = useContext(UserHabitCurrencyContext);+ const [suffix, suffixSet] = useState(() => getCurrencyType(props.defaultPattern) || userHabitCurrency[0]);const [decimal, decimalSet] = useState(() => getDecimalFromPattern(props.defaultPattern || '', 2));- const [suffix, suffixSet] = useState(- () => getCurrencyType(props.defaultPattern || '') || getCurrencyOptions()[0].value- );-- const negativeOptions = useMemo(() => getCurrencyFormatOptions(suffix), [suffix]);-const [pattern, patternSet] = useState(() => {- const _defaultPattern = getCurrencyFormatOptions(suffix)[0].value;- if (!props.defaultPattern) {- return _defaultPattern;- }- const defaultPattern = props.defaultPattern;- return (- negativeOptions.find((item) => isPatternEqualWithoutDecimal(item.value, defaultPattern))?.value ||- _defaultPattern- );+ const negativeOptions = getCurrencyFormatOptions(suffix);+ const pattern =+ negativeOptions.find((item) => isPatternEqualWithoutDecimal(item.value, props.defaultPattern))?.value ||+ negativeOptions[0].value;+ return pattern;});- const resultPattern = useMemo(() => setPatternDecimal(pattern, decimal), [pattern, decimal]);+ const negativeOptions = useMemo(() => getCurrencyFormatOptions(suffix), [suffix]);+ const options = useMemo(() => userHabitCurrency.map((key) => ({ label: key, value: key })), [userHabitCurrency]);++ props.action.current = () => setPatternDecimal(pattern, decimal);- const currencyOptions = useMemo(getCurrencyOptions, []);+ const onSelect = (value: string) => {+ suffixSet(value);+ const pattern = getCurrencyFormatOptions(value)[0].value;+ patternSet(pattern);+ props.onChange(setPatternDecimal(pattern, decimal));+ };- useEffect(() => {- props.onChange(resultPattern);- }, [resultPattern]);+ const onChange = (value: string) => {+ patternSet(value);+ props.onChange(setPatternDecimal(value, decimal));+ };- useEffectWithoutFirst(() => {- patternSet(negativeOptions[0].value);- return () => {};- }, [negativeOptions]);+ const onDecimalChange = (v: number | null) => {+ decimalSet(v || 0);+ props.onChange(setPatternDecimal(pattern, v || 0));+ };return (<div>@@ -66,27 +59,20 @@ export const CurrencyPanel: FC<BusinessComponentProps> = (props) => {<div className="option"><div className="label">{t('sheet.numfmt.decimalLength')}</div><div className="m-t-8 w-120">- <InputNumber value={decimal} max={20} min={0} onChange={(value) => decimalSet(value || 0)} />+ <InputNumber value={decimal} max={20} min={0} onChange={onDecimalChange} /></div></div><div className="option"><div className="label"> {t('sheet.numfmt.currencyType')}</div><div className="m-t-8 w-140">- <Select- onChange={(value) => {- suffixSet(value);- patternSet(negativeOptions[0].value);- }}- options={currencyOptions}- value={suffix}- />+ <Select onChange={onSelect} options={options} value={suffix} /></div></div></div><div className="m-t-16 label"> {t('sheet.numfmt.negType')}</div><div className="m-t-8">- <SelectList onChange={patternSet} options={negativeOptions} value={pattern} />+ <SelectList onChange={onChange} options={negativeOptions} value={pattern} /></div><div className="describe m-t-14">{t('sheet.numfmt.currencyDes')}</div>diff --git a/packages/sheets-plugin-numfmt/src/components/date/index.tsx b/packages/sheets-plugin-numfmt/src/components/date/index.tsxindex 998a9ca6bd..008236d16f 100644--- a/packages/sheets-plugin-numfmt/src/components/date/index.tsx+++ b/packages/sheets-plugin-numfmt/src/components/date/index.tsx@@ -3,9 +3,9 @@ import { LocaleService } from '@univerjs/core';import { SelectList } from '@univerjs/design';import { useDependency } from '@wendellhu/redi/react-bindings';import type { FC } from 'react';-import React, { useEffect, useMemo, useState } from 'react';+import React, { useMemo, useState } from 'react';-import type { BusinessComponentProps } from '../../base/types';+import type { IBusinessComponentProps } from '../../base/types';import { getDateFormatOptions } from '../../utils/options';export const isDatePanel = (pattern: string) => {@@ -17,7 +17,7 @@ export const isDatePanel = (pattern: string) => {);};-export const DatePanel: FC<BusinessComponentProps> = (props) => {+export const DatePanel: FC<IBusinessComponentProps> = (props) => {const options = useMemo(getDateFormatOptions, []);const localeService = useDependency(LocaleService);const t = localeService.t;@@ -31,14 +31,18 @@ export const DatePanel: FC<BusinessComponentProps> = (props) => {return options[0].value;});- useEffect(() => {- props.onChange(suffix);- }, [suffix]);+ props.action.current = () => suffix;++ const onChange = (v: string) => {+ suffixSet(v);+ props.onChange(v);+ };+return (<div><div className="m-t-16 label">{t('sheet.numfmt.dateType')}</div><div className="m-t-8">- <SelectList value={suffix} options={options} onChange={suffixSet} />+ <SelectList value={suffix} options={options} onChange={onChange} /></div><div className="describe m-t-14">{t('sheet.numfmt.dateDes')}</div></div>diff --git a/packages/sheets-plugin-numfmt/src/components/general/index.tsx b/packages/sheets-plugin-numfmt/src/components/general/index.tsxindex 04d8aeffa9..63d339c967 100644--- a/packages/sheets-plugin-numfmt/src/components/general/index.tsx+++ b/packages/sheets-plugin-numfmt/src/components/general/index.tsx@@ -1,18 +1,18 @@import { LocaleService } from '@univerjs/core';import { useDependency } from '@wendellhu/redi/react-bindings';import type { FC } from 'react';-import React, { useEffect } from 'react';+import React from 'react';-import type { BusinessComponentProps } from '../../base/types';+import type { IBusinessComponentProps } from '../../base/types';export const isGeneralPanel = (pattern: string) => !pattern;-export const GeneralPanel: FC<BusinessComponentProps> = (props) => {+export const GeneralPanel: FC<IBusinessComponentProps> = (props) => {const localeService = useDependency(LocaleService);const t = localeService.t;- useEffect(() => {- props.onChange('');- }, []);++ props.action.current = () => '';+return (<div><div className="describe m-t-14">{t('sheet.numfmt.generalDes')}</div>diff --git a/packages/sheets-plugin-numfmt/src/components/index.tsx b/packages/sheets-plugin-numfmt/src/components/index.tsxindex 2261f10a62..8632952f1f 100644--- a/packages/sheets-plugin-numfmt/src/components/index.tsx+++ b/packages/sheets-plugin-numfmt/src/components/index.tsx@@ -7,22 +7,29 @@ import { useDependency } from '@wendellhu/redi/react-bindings';import type { FC } from 'react';import React, { useEffect, useMemo, useRef, useState } from 'react';-import type { BusinessComponentProps } from '../base/types';+import type { IBusinessComponentProps } from '../base/types';+import { UserHabitCurrencyContext } from '../context/user-habit';+import { useCurrencyOptions } from '../hooks/useCurrencyOptions';+import { useNextTick } from '../hooks/useNextTick';+import { getCurrencyType } from '../utils/currency';import { AccountingPanel, isAccountingPanel } from './accounting';import { CurrencyPanel, isCurrencyPanel } from './currency';import { DatePanel, isDatePanel } from './date';import { GeneralPanel, isGeneralPanel } from './general';import { isThousandthPercentilePanel, ThousandthPercentilePanel } from './thousandth-percentile';-export interface SheetNumfmtPanelProps {- value: { defaultValue: number; defaultPattern: string };+export interface ISheetNumfmtPanelProps {+ value: { defaultValue: number; defaultPattern: string; row: number; col: number };onChange: (config: { type: 'change' | 'cancel' | 'confirm'; value: string }) => void;}-export const SheetNumfmtPanel: FC<SheetNumfmtPanelProps> = (props) => {- const { defaultValue, defaultPattern } = props.value;+export const SheetNumfmtPanel: FC<ISheetNumfmtPanelProps> = (props) => {+ const { defaultValue, defaultPattern, row, col } = props.value;const localeService = useDependency(LocaleService);+ const getCurrentPattern = useRef<() => string | null>(() => '');const t = localeService.t;- const options = useMemo(+ const nextTick = useNextTick();+ const pattern = useRef('');+ const typeOptions = useMemo(() =>[{ label: 'sheet.numfmt.general', component: GeneralPanel },@@ -33,44 +40,58 @@ export const SheetNumfmtPanel: FC<SheetNumfmtPanelProps> = (props) => {].map((item) => ({ ...item, label: t(item.label) })),[]);- const findDefaultType = () => {+ const [type, typeSet] = useState(findDefaultType);+ const [key, keySet] = useState(() => `${row}_${col}`);+ const { mark, userHabitCurrency } = useCurrencyOptions(() => keySet(`${row}_${col}_userCurrency'`));++ const BusinessComponent = useMemo(() => typeOptions.find((item) => item.label === type)?.component, [type]);++ function findDefaultType() {const list = [isGeneralPanel, isAccountingPanel, isCurrencyPanel, isDatePanel, isThousandthPercentilePanel];return (- list.reduce((pre, curFn, index) => pre || (curFn(defaultPattern) ? options[index].label : ''), '') ||- options[0].label+ list.reduce((pre, curFn, index) => pre || (curFn(defaultPattern) ? typeOptions[index].label : ''), '') ||+ typeOptions[0].label);- };- const [type, typeSet] = useState(findDefaultType);- const pattern = useRef('');- const BusinessComponent = useMemo(() => options.find((item) => item.label === type)?.component, [type]);+ }- const selectOptions: ISelectProps['options'] = options.map((option) => ({+ const selectOptions: ISelectProps['options'] = typeOptions.map((option) => ({label: option.label,value: option.label,}));+const handleSelect: ISelectProps['onChange'] = (value) => {typeSet(value);+ // after the BusinessComponent render.+ nextTick(() => props.onChange({ type: 'change', value: getCurrentPattern.current() || '' }));};+const handleChange = (v: string) => {pattern.current = v;props.onChange({ type: 'change', value: v });};+const handleConfirm = () => {+ const currency = getCurrencyType(pattern.current);+ if (currency) {+ mark(currency);+ }props.onChange({ type: 'confirm', value: pattern.current });};const handleCancel = () => {props.onChange({ type: 'cancel', value: pattern.current });};- const subProps: BusinessComponentProps = {+ const subProps: IBusinessComponentProps = {onChange: handleChange,defaultValue,defaultPattern,+ action: getCurrentPattern,};useEffect(() => {typeSet(findDefaultType());- }, [defaultPattern, defaultValue]);+ keySet(`${row}_${col}`);+ }, [row, col]);return (<div className="numfmt-panel p-b-20">@@ -79,7 +100,13 @@ export const SheetNumfmtPanel: FC<SheetNumfmtPanelProps> = (props) => {<div className="m-t-8"><Select onChange={handleSelect} options={selectOptions} value={type} /></div>- <div>{BusinessComponent && <BusinessComponent {...subProps} />}</div>+ <div>+ {BusinessComponent && (+ <UserHabitCurrencyContext.Provider value={userHabitCurrency}>+ <BusinessComponent {...subProps} key={key} />+ </UserHabitCurrencyContext.Provider>+ )}+ </div></div><div className="btn-list m-t-14 m-b-20">diff --git a/packages/sheets-plugin-numfmt/src/components/stories/panel.stories.tsx b/packages/sheets-plugin-numfmt/src/components/stories/panel.stories.tsxindex 6b8409d6ad..b38ca93278 100644--- a/packages/sheets-plugin-numfmt/src/components/stories/panel.stories.tsx+++ b/packages/sheets-plugin-numfmt/src/components/stories/panel.stories.tsx@@ -5,7 +5,7 @@ import { connectInjector } from '@wendellhu/redi/react-bindings';import React, { useMemo } from 'react';import { zhCn } from '../../locale/zh-CN';-import type { SheetNumfmtPanelProps } from '../index';+import type { ISheetNumfmtPanelProps } from '../index';import { SheetNumfmtPanel } from '../index';const Index = (props: any) => {@@ -29,9 +29,9 @@ const meta: Meta = {export default meta;-export const Test: StoryObj<SheetNumfmtPanelProps> = {+export const Test: StoryObj<ISheetNumfmtPanelProps> = {args: {- value: { defaultPattern: '', defaultValue: 123123 },+ value: { defaultPattern: '', defaultValue: 123123, row: 2, col: 3 },onChange(pattern) {console.log(pattern);},diff --git a/packages/sheets-plugin-numfmt/src/components/thousandth-percentile/index.tsx b/packages/sheets-plugin-numfmt/src/components/thousandth-percentile/index.tsxindex acb71bbc96..0a5810012c 100644--- a/packages/sheets-plugin-numfmt/src/components/thousandth-percentile/index.tsx+++ b/packages/sheets-plugin-numfmt/src/components/thousandth-percentile/index.tsx@@ -1,8 +1,8 @@import { InputNumber, SelectList } from '@univerjs/design';import type { FC } from 'react';-import React, { useEffect, useMemo, useState } from 'react';+import React, { useMemo, useState } from 'react';-import type { BusinessComponentProps } from '../../base/types';+import type { IBusinessComponentProps } from '../../base/types';import {getDecimalFromPattern,isPatternEqualWithoutDecimal,@@ -14,7 +14,7 @@ import { getNumberFormatOptions } from '../../utils/options';export const isThousandthPercentilePanel = (pattern: string) =>getNumberFormatOptions().some((item) => isPatternEqualWithoutDecimal(item.value, pattern));-export const ThousandthPercentilePanel: FC<BusinessComponentProps> = (props) => {+export const ThousandthPercentilePanel: FC<IBusinessComponentProps> = (props) => {const options = useMemo(getNumberFormatOptions, []);const [decimal, decimalSet] = useState(() => getDecimalFromPattern(props.defaultPattern || '', 0));@@ -32,9 +32,7 @@ export const ThousandthPercentilePanel: FC<BusinessComponentProps> = (props) =>suffixSet(v);};- useEffect(() => {- props.onChange(pattern);- }, [pattern]);+ props.action.current = () => pattern;return (<div>@@ -52,7 +50,9 @@ export const ThousandthPercentilePanel: FC<BusinessComponentProps> = (props) =><div className="m-t-8"><SelectList onChange={handleClick} options={options} value={suffix} /></div>- <div className="describe m-t-14">货币格式用于表示一般货币数值。会计格式可以对一列数值进行小数点对齐。</div>+ <div className="describe m-t-14">+ 数值格式用于一般数字的表示。货币和会计格式则提供货币值计算的专用格式。+ </div></div>);};diff --git a/packages/sheets-plugin-numfmt/src/context/user-habit.ts b/packages/sheets-plugin-numfmt/src/context/user-habit.tsnew file mode 100644index 0000000000..6b60520a3a--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/context/user-habit.ts@@ -0,0 +1,3 @@+import { createContext } from 'react';++export const UserHabitCurrencyContext = createContext<string[]>([]);diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.tsindex d965e224dc..59e2961e0e 100644--- a/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts+++ b/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts@@ -1,26 +1,15 @@-import numfmt from '@univerjs/base-numfmt-engine';import { IRenderManagerService } from '@univerjs/base-render';-import type { EffectRefRangeParams } from '@univerjs/base-sheets';+import type { ISetNumfmtMutationParams } from '@univerjs/base-sheets';import {ClearSelectionAllCommand,ClearSelectionFormatCommand,- EffectRefRangId,- handleDeleteRangeMoveLeft,- handleDeleteRangeMoveUp,- handleInsertCol,- handleInsertRangeMoveDown,- handleInsertRangeMoveRight,- handleInsertRow,- handleIRemoveCol,- handleIRemoveRow,- handleMoveRange,- RefRangeService,- runRefRangeMutations,+ factorySetNumfmtUndoMutation,+ INumfmtService,SelectionManagerService,- SetRangeValuesCommand,+ SetNumfmtMutation,} from '@univerjs/base-sheets';import { ComponentManager, IMenuService, ISidebarService } from '@univerjs/base-ui';-import type { ICellData, IMutationInfo, IRange, Nullable } from '@univerjs/core';+import type { ICellData, IMutationInfo, IRange } from '@univerjs/core';import {CellValueType,Disposable,@@ -28,9 +17,11 @@ import {ICommandService,INTERCEPTOR_POINT,IUniverInstanceService,+ LifecycleStages,LocaleService,LocaleType,ObjectMatrix,+ OnLifecycle,Range,Rectangle,SheetInterceptorService,@@ -39,66 +30,39 @@ import {} from '@univerjs/core';import type { IAutoFillHook } from '@univerjs/ui-plugin-sheets';import { APPLY_TYPE, getRepeatRange, IAutoFillService, SheetSkeletonManagerService } from '@univerjs/ui-plugin-sheets';-import type { IDisposable } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { combineLatest, Observable } from 'rxjs';-import { bufferTime, distinctUntilChanged, filter, map, switchMap, tap } from 'rxjs/operators';+import { distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';import { SHEET_NUMFMT_PLUGIN } from '../base/const/PLUGIN_NAME';import { AddDecimalCommand } from '../commands/commands/add.decimal.command';import { SetCurrencyCommand } from '../commands/commands/set.currency.command';-import type { SetNumfmtCommandParams } from '../commands/commands/set.numfmt.command';+import type { ISetNumfmtCommandParams } from '../commands/commands/set.numfmt.command';import { SetNumfmtCommand } from '../commands/commands/set.numfmt.command';import { SubtractDecimalCommand } from '../commands/commands/subtract.decimal.command';-import type { SetNumfmtMutationParams } from '../commands/mutations/set.numfmt.mutation';-import { factorySetNumfmtUndoMutation, SetNumfmtMutation } from '../commands/mutations/set.numfmt.mutation';import { CloseNumfmtPanelOperator } from '../commands/operators/close.numfmt.panel.operator';import { OpenNumfmtPanelOperator } from '../commands/operators/open.numfmt.panel.operator';-import type { SheetNumfmtPanelProps } from '../components/index';+import type { ISheetNumfmtPanelProps } from '../components/index';import { SheetNumfmtPanel } from '../components/index';import { zhCn } from '../locale/zh-CN';import { AddDecimalMenuItem, CurrencyMenuItem, FactoryOtherMenuItem, SubtractDecimalMenuItem } from '../menu/menu';-import type { NumfmtItemWithCache } from '../service/type';-import { INumfmtService } from '../service/type';import { getPatternPreview, getPatternType } from '../utils/pattern';import type { INumfmtController } from './type';-const createCollectEffectMutation = () => {- interface IConfig {- workbookId: string;- worksheetId: string;- row: number;- col: number;- value: Nullable<NumfmtItemWithCache>;- }- let list: IConfig[] = [];- 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 = [];- };- return {- add,- getEffects,- clean,- };-};+@OnLifecycle(LifecycleStages.Rendered, NumfmtController)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 = '';+ /**+ * If _previewPattern is null ,the realTimeRenderingInterceptor will skip and if it is '',realTimeRenderingInterceptor will clear numfmt.+ * @private+ * @type {(string | null)}+ * @memberof NumfmtController+ */+ private _previewPattern: string | null = '';constructor(@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@Inject(ThemeService) private _themeService: ThemeService,@Inject(Injector) private _injector: Injector,@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,- @Inject(RefRangeService) private _refRangeService: RefRangeService,@Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,@Inject(ICommandService) private _commandService: ICommandService,@Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,@@ -111,18 +75,15 @@ export class NumfmtController extends Disposable implements INumfmtController {@Inject(IAutoFillService) private _autoFillService: IAutoFillService) {super();- this._initInterceptorCellContent();- this._initInterceptorEditorStart();- this._initInterceptorEditorEnd();this._initInterceptorCommands();this._initRealTimeRenderingInterceptor();- this._registerRefRange();- this._initMenu();- this._initLocal();this._initPanel();this._initCommands();- this._initAutoFill();this._commandExecutedListener();+ this._initMenu();+ this._initInterceptorCellContent();+ this._initLocal();+ this._initAutoFill();}openPanel = () => {@@ -156,7 +117,7 @@ export class NumfmtController extends Disposable implements INumfmtController {// eslint-disable-next-line no-magic-numbersconst defaultValue = (cellValue?.t === CellValueType.NUMBER ? cellValue.v : 12345678) as number;- const props: SheetNumfmtPanelProps = {+ const props: ISheetNumfmtPanelProps = {onChange: (config) => {if (config.type === 'change') {this._previewPattern = config.value;@@ -164,7 +125,7 @@ export class NumfmtController extends Disposable implements INumfmtController {this._renderManagerService.getRenderById(workbook.getUnitId())?.mainComponent?.makeDirty();} else if (config.type === 'confirm') {const selections = selectionManagerService.getSelectionRanges() || [];- const params: SetNumfmtCommandParams = { values: [] };+ const params: ISetNumfmtCommandParams = { values: [] };const patternType = getPatternType(config.value);selections.forEach((rangeInfo) => {Range.foreach(rangeInfo, (row, col) => {@@ -182,7 +143,7 @@ export class NumfmtController extends Disposable implements INumfmtController {sidebarService.close();}},- value: { defaultPattern: pattern, defaultValue },+ value: { defaultPattern: pattern, defaultValue, row: range.startRow, col: range.startColumn },};sidebarService.open({@@ -223,7 +184,7 @@ export class NumfmtController extends Disposable implements INumfmtController {endRow: targetStartCell.row,};- const values: SetNumfmtMutationParams['values'] = [];+ const values: ISetNumfmtMutationParams['values'] = [];Range.foreach(relativeRange, (row, col) => {const sourcePositionRange = Rectangle.getPositionRange(@@ -260,7 +221,7 @@ export class NumfmtController extends Disposable implements INumfmtController {}});if (values.length) {- const redo: IMutationInfo<SetNumfmtMutationParams> = {+ const redo: IMutationInfo<ISetNumfmtMutationParams> = {id: SetNumfmtMutation.id,params: {values,@@ -347,35 +308,6 @@ export class NumfmtController extends Disposable implements INumfmtController {this._sheetInterceptorService.interceptCommand({getMutations(command) {switch (command.id) {- case SetRangeValuesCommand.id: {- const workbookId = self._univerInstanceService.getCurrentUniverSheetInstance().getUnitId();- const worksheetId = self._univerInstanceService- .getCurrentUniverSheetInstance()- .getActiveSheet()- .getSheetId();- const list = self._collectEffectMutation.getEffects();- if (!list.length) {- return {- redos: [],- undos: [],- };- }- const redos: SetNumfmtMutationParams = {- workbookId,- worksheetId,- values: list.map((item) => ({- pattern: item.value ? item.value.pattern : '',- row: item.row,- col: item.col,- type: item.value?.type,- })),- };- const undos = factorySetNumfmtUndoMutation(self._injector, redos);- return {- redos: [{ id: SetNumfmtMutation.id, params: redos }],- undos: [{ id: SetNumfmtMutation.id, params: undos }],- };- }case ClearSelectionAllCommand.id:case ClearSelectionFormatCommand.id: {const workbookId = self._univerInstanceService.getCurrentUniverSheetInstance().getUnitId();@@ -387,7 +319,7 @@ export class NumfmtController extends Disposable implements INumfmtController {if (!selections?.length) {break;}- const redos: SetNumfmtMutationParams = {+ const redos: ISetNumfmtMutationParams = {workbookId,worksheetId,values: [],@@ -472,7 +404,7 @@ export class NumfmtController extends Disposable implements INumfmtController {this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === SetNumfmtMutation.id) {- const params = commandInfo.params as SetNumfmtMutationParams;+ const params = commandInfo.params as ISetNumfmtMutationParams;params.values.map((value) => ({ row: value.row, col: value.col })).forEach(({ row, col }) => {@@ -536,24 +468,8 @@ export class NumfmtController extends Disposable implements INumfmtController {};})),- // _previewPattern will be correct by react effect,this is late and causes the render to flash.- // this to fix this problem by preset the correct rendering pattern in advance.- tap(({ selectionRanges }) => {- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();- const range = selectionRanges[0];- const row = range.startRow;- const col = range.startColumn;- const numfmtValue = this._numfmtService.getValue(- workbook.getUnitId(),- workbook.getActiveSheet().getSheetId(),- row,- col- );- if (numfmtValue) {- this._previewPattern = numfmtValue.pattern;- } else {- this._previewPattern = '';- }+ tap(() => {+ this._previewPattern = null;})).subscribe(({ disposableCollection, selectionRanges }) => {@@ -576,8 +492,13 @@ export class NumfmtController extends Disposable implements INumfmtController {const rawValue = location.worksheet.getCellRaw(row, col);const value = rawValue?.v;const type = rawValue?.t;- if (value === undefined || value === null || type !== CellValueType.NUMBER) {- return next();+ if (+ value === undefined ||+ value === null ||+ type !== CellValueType.NUMBER ||+ this._previewPattern === null+ ) {+ return next(cell);}const info = getPatternPreview(this._previewPattern, value as number);if (info.color) {@@ -606,107 +527,6 @@ export class NumfmtController extends Disposable implements INumfmtController {);}- /**- * Process the initial values before entering the edit- * @private- * @memberof NumfmtService- */- private _initInterceptorEditorStart() {- this.disposeWithMe(- this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.BEFORE_CELL_EDIT, {- handler: (value, context, next) => {- const row = context.row;- const col = context.col;- const numfmtCell = this._numfmtService.getValue(context.workbookId, context.worksheetId, row, col);- if (numfmtCell) {- const type = getPatternType(numfmtCell.pattern);- switch (type) {- case 'scientific':- case 'percent':- case 'currency':- case 'grouped':- case 'number': {- // remove the style atr- const cell = context.worksheet.getCellRaw(row, col);- return cell ? filterAtr(cell, ['s']) : cell;- }- case 'date':- case 'time':- case 'datetime':- default: {- return next && next(value);- }- }- }- return next(value);- },- })- );- }-- /**- * Process the values after edit- * @private- * @memberof NumfmtService- */- private _initInterceptorEditorEnd() {- this.disposeWithMe(- this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.AFTER_CELL_EDIT, {- handler: (value, context, next) => {- // clear the effect- this._collectEffectMutation.clean();- const currentNumfmtValue = this._numfmtService.getValue(- context.workbookId,- context.worksheetId,- context.row,- context.col- );- const clean = () => {- currentNumfmtValue &&- this._collectEffectMutation.add(- context.workbookId,- context.worksheetId,- context.row,- context.col,- null- );- };- if (!value?.v) {- clean();- return next(value);- }-- const content = String(value.v);-- const dateInfo = numfmt.parseDate(content) || numfmt.parseTime(content);- const isTranslateDate = !!dateInfo;- if (isTranslateDate) {- if (dateInfo && dateInfo.z) {- const v = Number(dateInfo.v);- this._collectEffectMutation.add(- context.workbookId,- context.worksheetId,- context.row,- context.col,- {- type: 'date',- pattern: dateInfo.z,- }- );- return { ...value, v, t: CellValueType.NUMBER };- }- } else if (- ['date', 'time', 'datetime'].includes(currentNumfmtValue?.type || '') ||- !isNumeric(content)- ) {- clean();- }- return next(value);- },- })- );- }-private _commandExecutedListener() {this.disposeWithMe(this._commandService.onCommandExecuted((command) => {@@ -718,220 +538,4 @@ export class NumfmtController extends Disposable implements INumfmtController {}));}-- private _registerRefRange() {- this.disposeWithMe(- toDisposable(- this._sheetSkeletonManagerService.currentSkeleton$- .pipe(- map((skeleton) => skeleton?.sheetId),- distinctUntilChanged(),- switchMap(- () =>- new Observable<DisposableCollection>((subscribe) => {- const disposableCollection = new DisposableCollection();- subscribe.next(disposableCollection);- return () => {- disposableCollection.dispose();- };- })- )- )- .subscribe((disposableCollection) => {- const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();- const workbookId = workbook.getUnitId();- const worksheetId = this._univerInstanceService- .getCurrentUniverSheetInstance()- .getActiveSheet()- .getSheetId();- const model = this._numfmtService.getModel(workbookId, worksheetId);- const disposableMap: Map<string, IDisposable> = new Map();- const register = (commandInfo: EffectRefRangeParams, row: number, col: number) => {- const targetRange = {- startRow: row,- startColumn: col,- endRow: row,- endColumn: col,- };- let operators = [];- switch (commandInfo.id) {- case EffectRefRangId.DeleteRangeMoveLeftCommandId: {- operators = handleDeleteRangeMoveLeft(commandInfo, targetRange);- break;- }- case EffectRefRangId.DeleteRangeMoveUpCommandId: {- operators = handleDeleteRangeMoveUp(commandInfo, targetRange);- break;- }- case EffectRefRangId.InsertColCommandId: {- operators = handleInsertCol(commandInfo, targetRange);- break;- }- case EffectRefRangId.InsertRangeMoveDownCommandId: {- operators = handleInsertRangeMoveDown(commandInfo, targetRange);- break;- }- case EffectRefRangId.InsertRangeMoveRightCommandId: {- operators = handleInsertRangeMoveRight(commandInfo, targetRange);- break;- }- case EffectRefRangId.InsertRowCommandId: {- operators = handleInsertRow(commandInfo, targetRange);- break;- }- case EffectRefRangId.MoveRangeCommandId: {- operators = handleMoveRange(commandInfo, targetRange);- break;- }- case EffectRefRangId.RemoveColCommandId: {- operators = handleIRemoveCol(commandInfo, targetRange);- break;- }- case EffectRefRangId.RemoveRowCommandId: {- operators = handleIRemoveRow(commandInfo, targetRange);- break;- }- }- const result = runRefRangeMutations(operators, targetRange);- if (!result) {- // 删除- const redoParams: SetNumfmtMutationParams = {- workbookId,- worksheetId,- values: [{ row, col }],- };- const undoParams = factorySetNumfmtUndoMutation(this._injector, redoParams);- return {- redos: [- {- id: SetNumfmtMutation.id,- params: redoParams,- },- ],- undos: [- {- id: SetNumfmtMutation.id,- params: undoParams,- },- ],- };- }- const numfmtValue = this._numfmtService.getValue(workbookId, worksheetId, row, col);-- if (numfmtValue) {- const redoParams: SetNumfmtMutationParams = {- workbookId,- worksheetId,- values: [- { row, col },- { ...numfmtValue, row: result.startRow, col: result.startColumn },- ],- };- const undoParams = factorySetNumfmtUndoMutation(this._injector, redoParams);- return {- redos: [- {- id: SetNumfmtMutation.id,- params: redoParams,- },- ],- undos: [- {- id: SetNumfmtMutation.id,- params: undoParams,- },- ],- };- }- return { redos: [], undos: [] };- };- if (model) {- model.forValue((row, col) => {- const targetRange = {- startRow: row,- startColumn: col,- endRow: row,- endColumn: col,- };- const disposable = this._refRangeService.registerRefRange(targetRange, (commandInfo) =>- register(commandInfo, row, col)- );- disposableMap.set(`${row}_${col}`, disposable);- disposableCollection.add(disposable);- });- }-- // on change- disposableCollection.add(- toDisposable(- new Observable<SetNumfmtMutationParams>((subscribe) => {- disposableCollection.add(- this._commandService.onCommandExecuted((commandInfo) => {- if (commandInfo.id === SetNumfmtMutation.id) {- subscribe.next(commandInfo.params as SetNumfmtMutationParams);- }- })- );- })- .pipe(- filter(- (commandInfo) =>- commandInfo.workbookId === workbookId &&- commandInfo.worksheetId === worksheetId- ),- map((commandInfo) => commandInfo.values),- bufferTime(300), // updating the listener moves to the next queue- map((values) =>- values.reduce((pre, cur) => {- pre.push(...cur);- return pre;- }, [])- ),- 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);- if (!value.pattern) {- disposable && disposable.dispose();- } else {- const targetRange = {- startRow: row,- startColumn: col,- endRow: row,- endColumn: col,- };- const disposable = this._refRangeService.registerRefRange(- targetRange,- (commandInfo) => register(commandInfo, row, col)- );- disposableMap.set(key, disposable);- disposableCollection.add(disposable);- }- });- })- )- );- })- )- );- }-}--const filterAtr = (obj: Record<string, any>, filterKey: string[]) => {- const keys = Object.keys(obj).filter((key) => !filterKey.includes(key));- return keys.reduce(- (pre, cur) => {- pre[cur] = obj[cur];- return pre;- },- {} as Record<string, any>- );-};--function isNumeric(str: string) {- return /^-?\d+(\.\d+)?$/.test(str);}diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt.editor.controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt.editor.controller.tsnew file mode 100644index 0000000000..9f58c7b544--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/controllers/numfmt.editor.controller.ts@@ -0,0 +1,221 @@+import numfmt from '@univerjs/base-numfmt-engine';+import type { INumfmtItemWithCache, ISetNumfmtMutationParams } from '@univerjs/base-sheets';+import {+ factorySetNumfmtUndoMutation,+ INumfmtService,+ SetNumfmtMutation,+ SetRangeValuesCommand,+} from '@univerjs/base-sheets';+import type { Nullable } from '@univerjs/core';+import {+ CellValueType,+ Disposable,+ INTERCEPTOR_POINT,+ IUniverInstanceService,+ LifecycleStages,+ OnLifecycle,+ SheetInterceptorService,+} from '@univerjs/core';+import { Inject, Injector } from '@wendellhu/redi';++import { getPatternType } from '../utils/pattern';++const createCollectEffectMutation = () => {+ interface IConfig {+ workbookId: string;+ worksheetId: string;+ row: number;+ col: number;+ value: Nullable<INumfmtItemWithCache>;+ }+ let list: IConfig[] = [];+ const add = (+ workbookId: string,+ worksheetId: string,+ row: number,+ col: number,+ value: Nullable<INumfmtItemWithCache>+ ) => list.push({ workbookId, worksheetId, row, col, value });+ const getEffects = () => list;+ const clean = () => {+ list = [];+ };+ return {+ add,+ getEffects,+ clean,+ };+};+@OnLifecycle(LifecycleStages.Rendered, NumfmtEditorController)+export class NumfmtEditorController extends Disposable {+ // collect effect mutations when edit end and push this to commands stack in next commands progress+ private _collectEffectMutation = createCollectEffectMutation();++ constructor(+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,+ @Inject(INumfmtService) private _numfmtService: INumfmtService,+ @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,+ @Inject(Injector) private _injector: Injector+ ) {+ super();+ this._initInterceptorEditorStart();+ this._initInterceptorEditorEnd();+ this._initInterceptorCommands();+ }++ private _initInterceptorEditorStart() {+ this.disposeWithMe(+ this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.BEFORE_CELL_EDIT, {+ handler: (value, context, next) => {+ const row = context.row;+ const col = context.col;+ const numfmtCell = this._numfmtService.getValue(context.workbookId, context.worksheetId, row, col);+ if (numfmtCell) {+ const type = getPatternType(numfmtCell.pattern);+ switch (type) {+ case 'scientific':+ case 'percent':+ case 'currency':+ case 'grouped':+ case 'number': {+ // remove the style atr+ const cell = context.worksheet.getCellRaw(row, col);+ return cell ? filterAtr(cell, ['s']) : cell;+ }+ case 'date':+ case 'time':+ case 'datetime':+ default: {+ return next && next(value);+ }+ }+ }+ return next(value);+ },+ })+ );+ }++ /**+ * Process the values after edit+ * @private+ * @memberof NumfmtService+ */+ private _initInterceptorEditorEnd() {+ this.disposeWithMe(+ this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.AFTER_CELL_EDIT, {+ handler: (value, context, next) => {+ // clear the effect+ this._collectEffectMutation.clean();+ const currentNumfmtValue = this._numfmtService.getValue(+ context.workbookId,+ context.worksheetId,+ context.row,+ context.col+ );+ const clean = () => {+ currentNumfmtValue &&+ this._collectEffectMutation.add(+ context.workbookId,+ context.worksheetId,+ context.row,+ context.col,+ null+ );+ };+ if (!value?.v) {+ clean();+ return next(value);+ }++ const content = String(value.v);++ const dateInfo = numfmt.parseDate(content) || numfmt.parseTime(content);+ const isTranslateDate = !!dateInfo;+ if (isTranslateDate) {+ if (dateInfo && dateInfo.z) {+ const v = Number(dateInfo.v);+ this._collectEffectMutation.add(+ context.workbookId,+ context.worksheetId,+ context.row,+ context.col,+ {+ type: 'date',+ pattern: dateInfo.z,+ }+ );+ return { ...value, v, t: CellValueType.NUMBER };+ }+ } else if (+ ['date', 'time', 'datetime'].includes(currentNumfmtValue?.type || '') ||+ !isNumeric(content)+ ) {+ clean();+ }+ return next(value);+ },+ })+ );+ }++ private _initInterceptorCommands() {+ const self = this;+ this.disposeWithMe(+ this._sheetInterceptorService.interceptCommand({+ getMutations(command) {+ switch (command.id) {+ case SetRangeValuesCommand.id: {+ const workbookId = self._univerInstanceService.getCurrentUniverSheetInstance().getUnitId();+ const worksheetId = self._univerInstanceService+ .getCurrentUniverSheetInstance()+ .getActiveSheet()+ .getSheetId();+ const list = self._collectEffectMutation.getEffects();+ if (!list.length) {+ return {+ redos: [],+ undos: [],+ };+ }+ const redos: ISetNumfmtMutationParams = {+ workbookId,+ worksheetId,+ values: list.map((item) => ({+ pattern: item.value ? item.value.pattern : '',+ row: item.row,+ col: item.col,+ type: item.value?.type,+ })),+ };+ const undos = factorySetNumfmtUndoMutation(self._injector, redos);+ return {+ redos: [{ id: SetNumfmtMutation.id, params: redos }],+ undos: [{ id: SetNumfmtMutation.id, params: undos }],+ };+ }+ }+ return {+ redos: [],+ undos: [],+ };+ },+ })+ );+ }+}++const filterAtr = (obj: Record<string, any>, filterKey: string[]) => {+ const keys = Object.keys(obj).filter((key) => !filterKey.includes(key));+ return keys.reduce(+ (pre, cur) => {+ pre[cur] = obj[cur];+ return pre;+ },+ {} as Record<string, any>+ );+};++function isNumeric(str: string) {+ return /^-?\d+(\.\d+)?$/.test(str);+}diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt.ref-range.controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt.ref-range.controller.tsnew file mode 100644index 0000000000..c3e946f286--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/controllers/numfmt.ref-range.controller.ts@@ -0,0 +1,271 @@+import type { EffectRefRangeParams, ISetNumfmtMutationParams } from '@univerjs/base-sheets';+import {+ EffectRefRangId,+ factorySetNumfmtUndoMutation,+ handleDeleteRangeMoveLeft,+ handleDeleteRangeMoveUp,+ handleInsertCol,+ handleInsertRangeMoveDown,+ handleInsertRangeMoveRight,+ handleInsertRow,+ handleIRemoveCol,+ handleIRemoveRow,+ handleMoveRange,+ INumfmtService,+ RefRangeService,+ runRefRangeMutations,+ SetNumfmtMutation,+} from '@univerjs/base-sheets';+import type { IMutationInfo } from '@univerjs/core';+import {+ Disposable,+ DisposableCollection,+ ICommandService,+ IUniverInstanceService,+ LifecycleStages,+ OnLifecycle,+ toDisposable,+} from '@univerjs/core';+import { SheetSkeletonManagerService } from '@univerjs/ui-plugin-sheets';+import type { IDisposable } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';+import { Observable } from 'rxjs';+import { bufferTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';++@OnLifecycle(LifecycleStages.Rendered, NumfmtRefRangeController)+export class NumfmtRefRangeController extends Disposable {+ constructor(+ @Inject(INumfmtService) private _numfmtService: INumfmtService,+ @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,+ @Inject(Injector) private _injector: Injector,+ @Inject(RefRangeService) private _refRangeService: RefRangeService,+ @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @Inject(ICommandService) private _commandService: ICommandService+ ) {+ super();+ this._registerRefRange();+ }++ private _registerRefRange() {+ this.disposeWithMe(+ toDisposable(+ this._sheetSkeletonManagerService.currentSkeleton$+ .pipe(+ map((skeleton) => skeleton?.sheetId),+ distinctUntilChanged(),+ switchMap(+ () =>+ new Observable<DisposableCollection>((subscribe) => {+ const disposableCollection = new DisposableCollection();+ subscribe.next(disposableCollection);+ return () => {+ disposableCollection.dispose();+ };+ })+ )+ )+ .subscribe((disposableCollection) => {+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();+ const workbookId = workbook.getUnitId();+ const worksheetId = this._univerInstanceService+ .getCurrentUniverSheetInstance()+ .getActiveSheet()+ .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 targetRange = {+ startRow: row,+ startColumn: col,+ endRow: row,+ endColumn: col,+ };+ let operators = [];+ switch (commandInfo.id) {+ case EffectRefRangId.DeleteRangeMoveLeftCommandId: {+ operators = handleDeleteRangeMoveLeft(commandInfo, targetRange);+ break;+ }+ case EffectRefRangId.DeleteRangeMoveUpCommandId: {+ operators = handleDeleteRangeMoveUp(commandInfo, targetRange);+ break;+ }+ case EffectRefRangId.InsertColCommandId: {+ operators = handleInsertCol(commandInfo, targetRange);+ break;+ }+ case EffectRefRangId.InsertRangeMoveDownCommandId: {+ operators = handleInsertRangeMoveDown(commandInfo, targetRange);+ break;+ }+ case EffectRefRangId.InsertRangeMoveRightCommandId: {+ operators = handleInsertRangeMoveRight(commandInfo, targetRange);+ break;+ }+ case EffectRefRangId.InsertRowCommandId: {+ operators = handleInsertRow(commandInfo, targetRange);+ break;+ }+ case EffectRefRangId.MoveRangeCommandId: {+ operators = handleMoveRange(commandInfo, targetRange);+ break;+ }+ case EffectRefRangId.RemoveColCommandId: {+ operators = handleIRemoveCol(commandInfo, targetRange);+ break;+ }+ case EffectRefRangId.RemoveRowCommandId: {+ operators = handleIRemoveRow(commandInfo, targetRange);+ break;+ }+ }+ 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 undoParams = factorySetNumfmtUndoMutation(this._injector, redoParams);+ return {+ redos: [+ {+ id: SetNumfmtMutation.id,+ params: redoParams,+ },+ ],+ undos: [+ {+ id: SetNumfmtMutation.id,+ params: undoParams,+ },+ ],+ };+ }+ 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 },+ ],+ };+ if (!isPreSetNumfmt) {+ redoParams.values.unshift({ row, col });+ }+ const undoParams = factorySetNumfmtUndoMutation(this._injector, redoParams);+ return {+ redos: [+ {+ id: SetNumfmtMutation.id,+ params: redoParams,+ },+ ],+ undos: [+ {+ id: SetNumfmtMutation.id,+ params: undoParams,+ },+ ],+ };+ }+ return { redos: [], undos: [] };+ };+ if (model) {+ model.forValue((row, col) => {+ 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(`${row}_${col}`, disposable);+ disposableCollection.add(disposable);+ });+ }++ // on change+ disposableCollection.add(+ toDisposable(+ new Observable<ISetNumfmtMutationParams>((subscribe) => {+ disposableCollection.add(+ this._commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetNumfmtMutation.id) {+ subscribe.next(commandInfo.params as ISetNumfmtMutationParams);+ }+ })+ );+ })+ .pipe(+ filter(+ (commandInfo) =>+ commandInfo.workbookId === workbookId &&+ commandInfo.worksheetId === worksheetId+ ),+ map((commandInfo) => commandInfo.values),+ bufferTime(300), // updating the listener moves to the next queue+ map((values) =>+ values.reduce((pre, cur) => {+ pre.push(...cur);+ return pre;+ }, [])+ ),+ 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)+ );+ disposableMap.set(key, disposable);+ disposableCollection.add(disposable);+ }+ });+ })+ )+ );+ })+ )+ );+ }+}diff --git a/packages/sheets-plugin-numfmt/src/controllers/user-habit.controller.ts b/packages/sheets-plugin-numfmt/src/controllers/user-habit.controller.tsnew file mode 100644index 0000000000..3252ba8130--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/controllers/user-habit.controller.ts@@ -0,0 +1,62 @@+import { ILocalStorageService } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';++type HabitValue = string | number;+interface IUserHabitController {+ addHabit(habit: string, initValue: HabitValue[]): Promise<void>;+ markHabit(habit: string, value: HabitValue): void;+ deleteHabit(habit: string): void;+ getHabit(habit: string, sortList?: HabitValue[]): Promise<HabitValue[]>;+}++export class UserHabitController implements IUserHabitController {+ constructor(@Inject(ILocalStorageService) private _localStorageService: ILocalStorageService) {}+ private _getKey(habit: string) {+ return `userHabitController_${habit}`;+ }++ async addHabit<T = unknown[]>(habit: string, initValue: T) {+ const key = this._getKey(habit);+ return this._localStorageService.getItem<T>(key).then((item) => {+ if (!item) {+ this._localStorageService.setItem(key, initValue);+ }+ });+ }++ markHabit(habit: string, value: HabitValue) {+ const key = this._getKey(habit);+ this._localStorageService.getItem<HabitValue[]>(key).then((list) => {+ if (list) {+ const index = list.findIndex((item) => item === value);+ index > -1 && list.splice(index, 1);+ list.unshift(value);+ this._localStorageService.setItem(key, list);+ }+ });+ }++ async getHabit(habit: string, sortList: HabitValue[]) {+ const key = this._getKey(habit);+ const result = await this._localStorageService.getItem<HabitValue[]>(key);+ if (sortList && result) {+ const priority = result.map((item, index, arr) => {+ const length = arr.length;+ return {+ value: item,+ priority: length - index,+ };+ });+ return sortList.sort((a, b) => {+ const ap = priority.find((item) => item.value === a)?.priority || -1;+ const bp = priority.find((item) => item.value === b)?.priority || -1;+ return bp - ap;+ });+ }+ return result || [];+ }++ deleteHabit(habit: string) {+ this._localStorageService.removeItem(habit);+ }+}diff --git a/packages/sheets-plugin-numfmt/src/hooks/useCurrencyOptions.ts b/packages/sheets-plugin-numfmt/src/hooks/useCurrencyOptions.tsnew file mode 100644index 0000000000..e1e1ba631c--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/hooks/useCurrencyOptions.ts@@ -0,0 +1,25 @@+import { useDependency } from '@wendellhu/redi/react-bindings';+import { useEffect, useState } from 'react';++import { currencySymbols } from '../base/const/CURRENCY-SYMBOLS';+import { UserHabitController } from '../controllers/user-habit.controller';++const key = 'numfmtCurrency';+export const useCurrencyOptions = (onOptionChange?: (options: string[]) => void) => {+ const userHabitController = useDependency(UserHabitController);+ const [options, optionsSet] = useState(currencySymbols);++ useEffect(() => {+ userHabitController.addHabit('numfmtCurrency', []).then(() => {+ userHabitController.getHabit(key, [...currencySymbols]).then((list) => {+ optionsSet(list as string[]);+ onOptionChange && onOptionChange(list as string[]);+ });+ });+ }, []);++ const mark = (v: string) => {+ userHabitController.markHabit(key, v);+ };+ return { userHabitCurrency: options, mark };+};diff --git a/packages/sheets-plugin-numfmt/src/hooks/useNextTick.ts b/packages/sheets-plugin-numfmt/src/hooks/useNextTick.tsnew file mode 100644index 0000000000..7170d6ca09--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/hooks/useNextTick.ts@@ -0,0 +1,19 @@+import { useEffect, useRef, useState } from 'react';++export const useNextTick = () => {+ const effectList = useRef<Array<() => void>>([]);+ const [value, dispatch] = useState<Record<string, string>>({});++ useEffect(() => {+ effectList.current.forEach((fn) => {+ fn();+ });+ effectList.current = [];+ }, [value]);++ const nextTick = (fn: () => void) => {+ effectList.current.push(fn);+ dispatch({});+ };+ return nextTick;+};diff --git a/packages/sheets-plugin-numfmt/src/hooks/usePatternPreview.ts b/packages/sheets-plugin-numfmt/src/hooks/usePatternPreview.tsdeleted file mode 100644index 6cabf818ef..0000000000--- a/packages/sheets-plugin-numfmt/src/hooks/usePatternPreview.ts+++ /dev/null@@ -1,21 +0,0 @@-import { ThemeService } from '@univerjs/core';-import { useDependency } from '@wendellhu/redi/react-bindings';-import { useMemo } from 'react';--import { getPatternPreview } from '../utils/pattern';--export const usePatternPreview = (pattern: string, value: number) => {- const themeService = useDependency(ThemeService);- return useMemo(() => {- const info = getPatternPreview(pattern, value);- if (info.color) {- const colorMap = themeService.getCurrentTheme();- const color = colorMap[`${info.color}500`];- return {- ...info,- color,- };- }- return info;- }, [pattern, value]);-};diff --git a/packages/sheets-plugin-numfmt/src/index.node.ts b/packages/sheets-plugin-numfmt/src/index.node.tsdeleted file mode 100644index 4d579cb51e..0000000000--- a/packages/sheets-plugin-numfmt/src/index.node.ts+++ /dev/null@@ -1 +0,0 @@-export * from './numfmt-plugin.node';diff --git a/packages/sheets-plugin-numfmt/src/menu/menu.ts b/packages/sheets-plugin-numfmt/src/menu/menu.tsindex d63d6c801e..f30a270485 100644--- a/packages/sheets-plugin-numfmt/src/menu/menu.ts+++ b/packages/sheets-plugin-numfmt/src/menu/menu.ts@@ -1,8 +1,9 @@-import { SelectionManagerService } from '@univerjs/base-sheets';-import { ComponentManager, IMenuButtonItem, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/base-ui';+import { INumfmtService, SelectionManagerService } from '@univerjs/base-sheets';+import type { ComponentManager, IMenuButtonItem } from '@univerjs/base-ui';+import { MenuGroup, MenuItemType, MenuPosition } from '@univerjs/base-ui';import { IUniverInstanceService } from '@univerjs/core';import { AddDigitsSingle, MoreDownSingle, ReduceDigitsSingle, RmbSingle } from '@univerjs/icons';-import { IAccessor } from '@wendellhu/redi';+import type { IAccessor } from '@wendellhu/redi';import { Observable } from 'rxjs';import { AddDecimalCommand } from '../commands/commands/add.decimal.command';@@ -14,7 +15,6 @@ import { isCurrencyPanel } from '../components/currency';import { isDatePanel } from '../components/date';import { MoreNumfmtType } from '../components/more-numfmt-type/MoreNumfmtType';import { isThousandthPercentilePanel } from '../components/thousandth-percentile';-import { INumfmtService } from '../service/type';export const CurrencyMenuItem = (componentManager: ComponentManager) => {const iconKey = 'icon-rmbSingle';diff --git a/packages/sheets-plugin-numfmt/src/numfmt-plugin.node.ts b/packages/sheets-plugin-numfmt/src/numfmt-plugin.node.tsdeleted file mode 100644index a851028d82..0000000000--- a/packages/sheets-plugin-numfmt/src/numfmt-plugin.node.ts+++ /dev/null@@ -1,17 +0,0 @@-import { Plugin, PluginType } from '@univerjs/core';-import { Inject, Injector } from '@wendellhu/redi';--import { SHEET_NUMFMT_PLUGIN } from './base/const/PLUGIN_NAME';-import { NumfmtService } from './service/numfmt.service';-import { INumfmtService } from './service/type';--export class NumfmtPlugin extends Plugin {- static override type = PluginType.Sheet;- constructor(@Inject(Injector) override readonly _injector: Injector) {- super(SHEET_NUMFMT_PLUGIN);- }-- override onStarting(): void {- this._injector.add([INumfmtService, { useClass: NumfmtService }]);- }-}diff --git a/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts b/packages/sheets-plugin-numfmt/src/numfmt-plugin.tsindex ad883dbacc..a1d6a6b46d 100644--- a/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts+++ b/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts@@ -3,9 +3,10 @@ import { Inject, Injector } from '@wendellhu/redi';import { SHEET_NUMFMT_PLUGIN } from './base/const/PLUGIN_NAME';import { NumfmtController } from './controllers/numfmt.controller';+import { NumfmtEditorController } from './controllers/numfmt.editor.controller';+import { NumfmtRefRangeController } from './controllers/numfmt.ref-range.controller';import { INumfmtController } from './controllers/type';-import { NumfmtService } from './service/numfmt.service';-import { INumfmtService } from './service/type';+import { UserHabitController } from './controllers/user-habit.controller';export class NumfmtPlugin extends Plugin {static override type = PluginType.Sheet;@@ -15,6 +16,8 @@ export class NumfmtPlugin extends Plugin {override onStarting(): void {this._injector.add([INumfmtController, { useClass: NumfmtController, lazy: false }]);- this._injector.add([INumfmtService, { useClass: NumfmtService, lazy: false }]);+ this._injector.add([NumfmtEditorController]);+ this._injector.add([UserHabitController]);+ this._injector.add([NumfmtRefRangeController]);}}diff --git a/packages/sheets-plugin-numfmt/src/utils/pattern.ts b/packages/sheets-plugin-numfmt/src/utils/pattern.tsindex 45f536aafe..9e2fa52bd4 100644--- a/packages/sheets-plugin-numfmt/src/utils/pattern.ts+++ b/packages/sheets-plugin-numfmt/src/utils/pattern.ts@@ -1,6 +1,5 @@import numfmt from '@univerjs/base-numfmt-engine';--import { FormatType } from '../base/types';+import type { FormatType } from '@univerjs/base-sheets';export const getPatternType = (pattern: string): FormatType => numfmt.getInfo(pattern).type || 'unknown';export const getPatternPreview = (pattern: string, value: number) => {