Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(sheets-numfmt): preserve colors for non-negative values (#7942)

白熱6ef7deddfedb
diff --git a/packages/core/src/shared/numfmt/__tests__/format-api.spec.ts b/packages/core/src/shared/numfmt/__tests__/api.spec.ts
similarity index 100%
rename from packages/core/src/shared/numfmt/__tests__/format-api.spec.ts
rename to packages/core/src/shared/numfmt/__tests__/api.spec.ts
diff --git a/packages/core/src/shared/numfmt/__tests__/parse-value.spec.ts b/packages/core/src/shared/numfmt/__tests__/parse-value.spec.ts
index 82c21206bc..0526e6fab7 100644
--- a/packages/core/src/shared/numfmt/__tests__/parse-value.spec.ts
+++ b/packages/core/src/shared/numfmt/__tests__/parse-value.spec.ts
@@ -19,8 +19,11 @@
// @vitest-environment node
-import { addLocale, dateToSerial, format, parseBool, parseDate, parseNumber, parseTime, parseValue } from '../api';
-import { getLocale, listLocales } from '../locale';
+import { describe, expect, it } from 'vitest';
+import { format } from '../api';
+import { addLocale, getLocale, listLocales } from '../locale';
+import { parseBool, parseDate, parseNumber, parseTime, parseValue } from '../parse-value';
+import { dateToSerial } from '../serial-date';
import { getTimeZoneName, isLeapYear, numfmtTest } from './test-utils';
/* globals process */
@@ -795,3 +798,16 @@ numfmtTest('parseBool locale support', (t) => {
t.deepEqual(parseBool('IGAZ', { locale: 'hu' }), { v: true }, 'hu: IGAZ');
t.deepEqual(parseBool('HAMIS', { locale: 'hu' }), { v: false }, 'hu: HAMIS');
});
+
+describe('parseDate', () => {
+ it('date parse date', () => {
+ expect(parseDate('asdasdasd')).toBe(null);
+ expect(parseDate('1988/12/12 21:21:21')?.z).toBe('yyyy/mm/dd hh:mm:ss');
+ expect(parseDate('12/12 21:21:21')?.z).toBe('mm/dd hh:mm:ss');
+ expect(parseDate('2012/12 21:21:21')?.z).toBe('yyyy/m hh:mm:ss');
+ expect(parseDate('2012/12 21:21')?.z).toBe('yyyy/m hh:mm');
+ expect(parseDate('2012/12')?.z).toBe('yyyy/m');
+ expect(parseDate('2012/12/12')?.z).toBe('yyyy/mm/dd');
+ expect(parseDate('21:21')).toBe(null);
+ });
+});
diff --git a/packages/core/src/shared/numfmt/__tests__/utils.spec.ts b/packages/core/src/shared/numfmt/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..f08dffc242
--- /dev/null
+++ b/packages/core/src/shared/numfmt/__tests__/utils.spec.ts
@@ -0,0 +1,27 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { isPatternEqualWithoutDecimal } from '../utils';
+
+describe('isPatternEqualWithoutDecimal', () => {
+ it('isPatternEqualWithoutDecimal', () => {
+ expect(isPatternEqualWithoutDecimal('_(###0.000);-###0.00', '[red]_(###0.0000);-###0.00')).toBe(true);
+ expect(isPatternEqualWithoutDecimal('_(###0;-###0.00', '_(###0;[red]-###0.00')).toBe(false);
+ expect(isPatternEqualWithoutDecimal('_(###00.0;-###0.00', '_(###0;[red]-###0.00')).toBe(false);
+ expect(isPatternEqualWithoutDecimal('_(###0;-###0.00', '_(###0.00;-###0.00')).toBe(true);
+ });
+});
diff --git a/packages/sheets-numfmt/src/__tests__/date.test.ts b/packages/sheets-numfmt/src/__tests__/date.test.ts
deleted file mode 100644
index 7a4117f7bf..0000000000
--- a/packages/sheets-numfmt/src/__tests__/date.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { numfmt } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
-
-describe('test numfmt date', () => {
- it('date parse date', () => {
- expect(numfmt.parseDate('asdasdasd')).toBe(null);
- expect(numfmt.parseDate('1988/12/12 21:21:21')?.z).toBe('yyyy/mm/dd hh:mm:ss');
- expect(numfmt.parseDate('12/12 21:21:21')?.z).toBe('mm/dd hh:mm:ss');
- expect(numfmt.parseDate('2012/12 21:21:21')?.z).toBe('yyyy/m hh:mm:ss'); // TODO: is yyy/mm hh:mm:ss ?
- expect(numfmt.parseDate('2012/12 21:21')?.z).toBe('yyyy/m hh:mm'); // TODO: is yyy/mm hh:mm ?
- expect(numfmt.parseDate('2012/12')?.z).toBe('yyyy/m'); // TODO: is yyy/mm ?
- expect(numfmt.parseDate('2012/12/12')?.z).toBe('yyyy/mm/dd');
- expect(numfmt.parseDate('21:21')).toBe(null);
- });
-});
diff --git a/packages/sheets-numfmt/src/__tests__/utils.test.ts b/packages/sheets-numfmt/src/__tests__/utils.test.ts
deleted file mode 100644
index b1ace8ff1e..0000000000
--- a/packages/sheets-numfmt/src/__tests__/utils.test.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { cellToRange, CellValueType, currencySymbols, DEFAULT_NUMBER_FORMAT, DEFAULT_TEXT_FORMAT_EXCEL, isPatternEqualWithoutDecimal, LocaleType } from '@univerjs/core';
-import { RemoveNumfmtMutation, SetNumfmtMutation } from '@univerjs/sheets';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { getCurrencyFormat, getCurrencySymbolByLocale, getCurrencySymbolIconByLocale } from '../base/const/currency-symbols';
-import { getCurrencyType } from '../utils/currency';
-import { getDecimalFromPattern, getDecimalString, isPatternHasDecimal, setPatternDecimal } from '../utils/decimal';
-import { mergeNumfmtMutations } from '../utils/mutation';
-import { getCurrencyFormatOptions, getCurrencyOptions, getDateFormatOptions, getNumberFormatOptions } from '../utils/options';
-import { getPatternPreview, getPatternPreviewIgnoreGeneral, getPatternType } from '../utils/pattern';
-import { getScientificNotationFormatFromCell, isAllowedPatternForScientificNotationNumber, isScientificNotationNumericCell } from '../utils/scientific-notation';
-
-describe('test numfmt utils function', () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it('getCurrencyType', () => {
- expect(getCurrencyType(`_(${currencySymbols[7]} 123123`)).toBe(currencySymbols[7]);
- expect(getCurrencyType('_(# 123123')).toBeUndefined();
- expect(getCurrencyType(`_(${currencySymbols[7]} 123123 ${currencySymbols[8]}`)).toBe(currencySymbols[7]);
- });
- it('getDecimalFromPattern', () => {
- expect(getDecimalFromPattern('_(###0.000);--###0.00')).toBe(3);
- expect(getDecimalFromPattern('_(###0);-###0.00')).toBe(0); // the function decimal just use positive,negative configuration ignored
- expect(getDecimalFromPattern('_(###0.0);--###0.00')).toBe(1);
- expect(getDecimalFromPattern('_(###0.);--###0.00')).toBe(0);
- });
- it('isPatternEqualWithoutDecimal', () => {
- expect(isPatternEqualWithoutDecimal('_(###0.000);-###0.00', '[red]_(###0.0000);-###0.00')).toBe(true); // the positive color ignored
- expect(isPatternEqualWithoutDecimal('_(###0;-###0.00', '_(###0;[red]-###0.00')).toBe(false);
- expect(isPatternEqualWithoutDecimal('_(###00.0;-###0.00', '_(###0;[red]-###0.00')).toBe(false);
- expect(isPatternEqualWithoutDecimal('_(###0;-###0.00', '_(###0.00;-###0.00')).toBe(true);
- });
- it('getDecimalString', () => {
- expect(getDecimalString(3)).toBe('000'); // the positive color ignored
- expect(getDecimalString(-1)).toBe(''); // the positive color ignored
- expect(getDecimalString(0)).toBe(''); // the positive color ignored
- });
- it('setPatternDecimal', () => {
- expect(setPatternDecimal('0.', 4)).toBe('0.0000'); // the positive color ignored
- expect(setPatternDecimal('.', 4)).toBe('.0000'); // the positive color ignored
- expect(setPatternDecimal('0.0', 4)).toBe('0.0000'); // the positive color ignored
- expect(setPatternDecimal('0.0', 0)).toBe('0'); // the positive color ignored
- });
-
- it('isPatternHasDecimal', () => {
- expect(isPatternHasDecimal('0.00')).toBe(true);
- expect(isPatternHasDecimal('#,##0')).toBe(true);
- expect(isPatternHasDecimal('General')).toBe(false);
- });
-
- it('currency symbol helpers', () => {
- expect(getCurrencySymbolByLocale(LocaleType.ZH_CN)).toBe('¥');
- expect(getCurrencySymbolByLocale(LocaleType.KO_KR)).toBe('₩');
- expect(getCurrencySymbolIconByLocale(LocaleType.FR_FR)).toEqual({
- icon: 'EuroIcon',
- symbol: '€',
- locale: LocaleType.FR_FR,
- });
- expect(getCurrencySymbolIconByLocale(LocaleType.KO_KR)).toEqual({
- icon: 'WonIcon',
- symbol: '₩',
- locale: LocaleType.KO_KR,
- });
- expect([
- LocaleType.VI_VN,
- LocaleType.FA_IR,
- LocaleType.AR_SA,
- LocaleType.ID_ID,
- LocaleType.PL_PL,
- ].map((locale) => getCurrencySymbolIconByLocale(locale).icon)).toEqual([
- 'DongIcon',
- 'RialIcon',
- 'RialIcon',
- 'RupiahIcon',
- 'ZlotyIcon',
- ]);
- expect(getCurrencyFormat(LocaleType.ZH_CN, 3)).toContain('"¥"#,##0.000');
- expect(getCurrencyFormat(LocaleType.EN_US, 200)).toContain(`.${'0'.repeat(127)}`);
- });
-
- it('option helpers expose formatted labels and values', () => {
- expect(getCurrencyOptions()[0]).toEqual({ label: 'Rp', value: 'Rp' });
- expect(getCurrencyFormatOptions('€')[0]).toMatchObject({
- label: expect.stringContaining('€'),
- value: expect.stringContaining('€'),
- });
- expect(getDateFormatOptions()[0]).toMatchObject({
- label: expect.any(String),
- value: expect.any(String),
- });
- expect(getNumberFormatOptions()[0]).toMatchObject({
- label: expect.any(String),
- value: expect.any(String),
- });
- });
-
- it('pattern preview helpers return types and gracefully handle general or invalid formats', () => {
- vi.spyOn(console, 'warn').mockImplementation(() => undefined);
-
- expect(getPatternType('0%')).toBe('percent');
- expect(getPatternPreview('0.00', 12.3)).toEqual({ result: '12.30' });
- expect(getPatternPreviewIgnoreGeneral(DEFAULT_NUMBER_FORMAT, 0.1 + 0.2)).toEqual({ result: '0.3' });
- expect(getPatternPreview('[invalid', 42)).toEqual({ result: '42' });
- });
-
- it('scientific notation helpers detect numeric cells and derive display patterns from mantissa decimals', () => {
- expect(isScientificNotationNumericCell({ v: 1e21, t: CellValueType.NUMBER })).toBe(true);
- expect(isScientificNotationNumericCell({ v: 1.2345e31, t: CellValueType.NUMBER })).toBe(true);
- expect(isScientificNotationNumericCell({ v: '1e21', t: CellValueType.STRING })).toBe(false);
- expect(isScientificNotationNumericCell({ v: 123, t: CellValueType.NUMBER })).toBe(false);
- expect(isScientificNotationNumericCell(null)).toBe(false);
-
- expect(getScientificNotationFormatFromCell({ v: 1e21, t: CellValueType.NUMBER })).toBe('0.00E+00');
- expect(getScientificNotationFormatFromCell({ v: 1.2e21, t: CellValueType.NUMBER })).toBe('0.00E+00');
- expect(getScientificNotationFormatFromCell({ v: 1.2345e31, t: CellValueType.NUMBER })).toBe('0.0000E+00');
- expect(getScientificNotationFormatFromCell({ v: -1.2345e-31, t: CellValueType.NUMBER })).toBe('0.0000E+00');
- });
-
- it('scientific notation format guard only allows general, text, and scientific patterns', () => {
- expect(isAllowedPatternForScientificNotationNumber(undefined)).toBe(true);
- expect(isAllowedPatternForScientificNotationNumber(DEFAULT_NUMBER_FORMAT)).toBe(true);
- expect(isAllowedPatternForScientificNotationNumber(DEFAULT_TEXT_FORMAT_EXCEL)).toBe(true);
- expect(isAllowedPatternForScientificNotationNumber('0.00E+00')).toBe(true);
- expect(isAllowedPatternForScientificNotationNumber('0.00')).toBe(false);
- expect(isAllowedPatternForScientificNotationNumber('0%')).toBe(false);
- });
-
- it('mergeNumfmtMutations', () => {
- const result = mergeNumfmtMutations([
- {
- id: SetNumfmtMutation.id,
- params: {
- values: {
- a: { ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)] },
- },
- refMap: { a: { pattern: '', type: '' } },
- },
- },
- {
- id: RemoveNumfmtMutation.id,
- params: {
- ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)],
- },
- },
- {
- id: SetNumfmtMutation.id,
- params: {
- values: {
- a: { ranges: [cellToRange(4, 6), cellToRange(4, 5)] },
- },
- refMap: { a: { pattern: '', type: '' } },
- },
- },
- ]);
-
- const removeMutation = result[0] as { params: { ranges: unknown } };
- const setMutation = result[1] as { params: { values: Record<string, { ranges: unknown }> } };
-
- expect(result[0].id === RemoveNumfmtMutation.id).toBeTruthy();
- expect(result[1].id === SetNumfmtMutation.id).toBeTruthy();
- expect(removeMutation.params.ranges).toEqual([
- {
- startRow: 2,
- endRow: 2,
- startColumn: 3,
- endColumn: 4,
- },
- {
- startRow: 4,
- endRow: 4,
- startColumn: 5,
- endColumn: 5,
- },
- ]);
- expect(setMutation.params.values['1'].ranges).toEqual([
- {
- startRow: 2,
- endRow: 2,
- startColumn: 3,
- endColumn: 4,
- },
- {
- startRow: 4,
- endRow: 4,
- startColumn: 5,
- endColumn: 6,
- },
- ]);
- });
-
- it('mergeNumfmtMutations multiple data formats of different types', () => {
- const result = mergeNumfmtMutations([
- {
- id: SetNumfmtMutation.id,
- params: {
- values: {
- a: { ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)] },
- },
- refMap: { a: { pattern: 'a', type: '' } },
- },
- },
- {
- id: RemoveNumfmtMutation.id,
- params: {
- ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)],
- },
- },
- {
- id: SetNumfmtMutation.id,
- params: {
- values: {
- a: { ranges: [cellToRange(4, 6), cellToRange(4, 5)] },
- },
- refMap: { a: { pattern: 'b', type: '' } },
- },
- },
- ]);
- expect(result).toEqual([
- {
- id: 'sheet.mutation.remove.numfmt',
- params: {
- ranges: [
- {
- startRow: 2,
- endRow: 2,
- startColumn: 3,
- endColumn: 4,
- },
- {
- startRow: 4,
- endRow: 4,
- startColumn: 5,
- endColumn: 5,
- },
- ],
- unitId: undefined,
- subUnitId: undefined,
- },
- },
- {
- id: 'sheet.mutation.set.numfmt',
- params: {
- values: {
- 1: {
- ranges: [
- {
- startRow: 2,
- endRow: 2,
- startColumn: 3,
- endColumn: 4,
- },
- {
- startRow: 4,
- endRow: 4,
- startColumn: 5,
- endColumn: 5,
- },
- ],
- },
- 2: {
- ranges: [
- {
- startRow: 4,
- endRow: 4,
- startColumn: 5,
- endColumn: 6,
- },
- ],
- },
- },
- refMap: {
- 1: {
- pattern: 'a',
- type: '',
- },
- 2: {
- pattern: 'b',
- type: '',
- },
- },
- unitId: undefined,
- subUnitId: undefined,
- },
- },
- ]);
- });
-});
diff --git a/packages/sheets-numfmt/src/base/const/__tests__/currency-symbols.spec.ts b/packages/sheets-numfmt/src/base/const/__tests__/currency-symbols.spec.ts
new file mode 100644
index 0000000000..a62786bd7f
--- /dev/null
+++ b/packages/sheets-numfmt/src/base/const/__tests__/currency-symbols.spec.ts
@@ -0,0 +1,51 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { LocaleType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { getCurrencyFormat, getCurrencySymbolByLocale, getCurrencySymbolIconByLocale } from '../currency-symbols';
+
+describe('currency symbols', () => {
+ it('currency symbol helpers', () => {
+ expect(getCurrencySymbolByLocale(LocaleType.ZH_CN)).toBe('¥');
+ expect(getCurrencySymbolByLocale(LocaleType.KO_KR)).toBe('₩');
+ expect(getCurrencySymbolIconByLocale(LocaleType.FR_FR)).toEqual({
+ icon: 'EuroIcon',
+ symbol: '€',
+ locale: LocaleType.FR_FR,
+ });
+ expect(getCurrencySymbolIconByLocale(LocaleType.KO_KR)).toEqual({
+ icon: 'WonIcon',
+ symbol: '₩',
+ locale: LocaleType.KO_KR,
+ });
+ expect([
+ LocaleType.VI_VN,
+ LocaleType.FA_IR,
+ LocaleType.AR_SA,
+ LocaleType.ID_ID,
+ LocaleType.PL_PL,
+ ].map((locale) => getCurrencySymbolIconByLocale(locale).icon)).toEqual([
+ 'DongIcon',
+ 'RialIcon',
+ 'RialIcon',
+ 'RupiahIcon',
+ 'ZlotyIcon',
+ ]);
+ expect(getCurrencyFormat(LocaleType.ZH_CN, 3)).toContain('"¥"#,##0.000');
+ expect(getCurrencyFormat(LocaleType.EN_US, 200)).toContain(`.${'0'.repeat(127)}`);
+ });
+});
diff --git a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
index e9f1825391..b2147ee4e8 100644
--- a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
+++ b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts
@@ -29,6 +29,7 @@ import {
LocaleType,
LogLevel,
Plugin,
+ ThemeService,
Univer,
UniverInstanceType,
} from '@univerjs/core';
@@ -40,9 +41,8 @@ import {
SetRangeValuesMutation,
SheetInterceptorService,
} from '@univerjs/sheets';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SHEETS_NUMFMT_PLUGIN_CONFIG_KEY } from '../../config/config';
-import * as patternUtils from '../../utils/pattern';
import { SheetsNumfmtCellContentController } from '../numfmt-cell-content.controller';
function createWorkbookData(
@@ -164,7 +164,6 @@ describe('SheetsNumfmtCellContentController', () => {
let workbook: Workbook;
let commandService: ICommandService;
let numfmtService: INumfmtService;
- let controller: SheetsNumfmtCellContentController;
beforeEach(() => {
const testBed = createControllerTestBed();
@@ -174,18 +173,17 @@ describe('SheetsNumfmtCellContentController', () => {
commandService = get(ICommandService);
numfmtService = get(INumfmtService);
- controller = get(SheetsNumfmtCellContentController);
commandService.registerCommand(SetNumfmtMutation);
commandService.registerCommand(SetRangeValuesMutation);
});
afterEach(() => {
- vi.restoreAllMocks();
univer.dispose();
});
it('skips unsupported cells and handles text format markers', () => {
+ get(SheetsNumfmtCellContentController);
const worksheet = workbook.getSheetBySheetId('sheet1')!;
expect(getInterceptedCell(worksheet, workbook, 0, 0, get)).toEqual({ v: true, t: CellValueType.BOOLEAN });
@@ -231,8 +229,8 @@ describe('SheetsNumfmtCellContentController', () => {
});
it('formats numeric values and clears render cache on numfmt or value mutations', async () => {
+ get(SheetsNumfmtCellContentController);
const worksheet = workbook.getSheetBySheetId('sheet1')!;
- const previewSpy = vi.spyOn(patternUtils, 'getPatternPreviewIgnoreGeneral');
numfmtService.setValues('test', 'sheet1', [
{ pattern: '0.00', ranges: [cellToRange(1, 1)] },
@@ -254,17 +252,12 @@ describe('SheetsNumfmtCellContentController', () => {
},
});
- const previewCallsAfterFirstRender = previewSpy.mock.calls.length;
-
- getInterceptedCell(worksheet, workbook, 1, 1, get);
- expect(previewSpy).toHaveBeenCalledTimes(previewCallsAfterFirstRender);
-
await commandService.executeCommand(SetNumfmtMutation.id, {
unitId: 'test',
subUnitId: 'sheet1',
refMap: {
1: {
- pattern: '0.00',
+ pattern: '0.0',
},
},
values: {
@@ -274,8 +267,7 @@ describe('SheetsNumfmtCellContentController', () => {
},
});
- getInterceptedCell(worksheet, workbook, 1, 1, get);
- expect(previewSpy).toHaveBeenCalledTimes(previewCallsAfterFirstRender + 1);
+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)).toMatchObject({ v: '1234.5' });
await commandService.executeCommand(SetRangeValuesMutation.id, {
unitId: 'test',
@@ -283,82 +275,110 @@ describe('SheetsNumfmtCellContentController', () => {
cellValue: {
1: {
1: {
- v: '1234.5',
+ v: '42',
t: CellValueType.STRING,
},
},
},
});
- getInterceptedCell(worksheet, workbook, 1, 1, get);
- expect(previewSpy).toHaveBeenCalledTimes(previewCallsAfterFirstRender + 2);
+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)).toMatchObject({ v: '42.0' });
+ });
+
+ it('updates section colors after value and format edits while preserving the raw font color', async () => {
+ get(SheetsNumfmtCellContentController);
+ const worksheet = workbook.getSheetBySheetId('sheet1')!;
+ const themeService = get(ThemeService);
+ const originalStyle = { cl: { rgb: '#663399' } };
+
+ numfmtService.setValues('test', 'sheet1', [{
+ pattern: '[Red]0.00;[Green]\\-0.00;[Blue]0.00',
+ ranges: [cellToRange(1, 1)],
+ }]);
+
+ for (const { value, color } of [
+ { value: 12.34, color: 'red' },
+ { value: -12.34, color: 'green' },
+ { value: 0, color: 'blue' },
+ ]) {
+ await commandService.executeCommand(SetRangeValuesMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: { 1: { 1: { v: value, t: CellValueType.NUMBER, s: originalStyle } } },
+ });
+
+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)).toMatchObject({
+ v: value.toFixed(2),
+ interceptorStyle: { cl: { rgb: themeService.getColorFromTheme(`${color}.500`) } },
+ });
+ expect(worksheet.getCellRaw(1, 1)).toMatchObject({ v: value });
+ expect(workbook.getStyles().get(worksheet.getCellRaw(1, 1)?.s)).toMatchObject(originalStyle);
+ }
+
+ await commandService.executeCommand(SetNumfmtMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ refMap: { 1: { pattern: '0.00' } },
+ values: { 1: { ranges: [cellToRange(1, 1)] } },
+ });
+
+ const cell = getInterceptedCell(worksheet, workbook, 1, 1, get);
+ expect(cell).toMatchObject({ v: '0.00' });
+ expect(cell?.interceptorStyle).toBeUndefined();
+ expect(workbook.getStyles().get(cell?.s)).toMatchObject(originalStyle);
});
it('formats each workbook with its own locale and date system', () => {
+ get(SheetsNumfmtCellContentController);
const date1900Sheet = workbook.getSheetBySheetId('sheet1')!;
const date1904Workbook = univer.createUnit<IWorkbookData, Workbook>(
UniverInstanceType.UNIVER_SHEET,
createWorkbookData('date1904', LocaleType.FR_FR, DateSystem.Date1904)
);
const date1904Sheet = date1904Workbook.getSheetBySheetId('sheet1')!;
- const previewSpy = vi.spyOn(patternUtils, 'getPatternPreviewIgnoreGeneral');
numfmtService.setValues('test', 'sheet1', [{ pattern: 'yyyy-mm-dd', ranges: [cellToRange(1, 4)] }]);
numfmtService.setValues('date1904', 'sheet1', [{ pattern: 'yyyy-mm-dd', ranges: [cellToRange(1, 4)] }]);
expect(getInterceptedCell(date1900Sheet, workbook, 1, 4, get)).toMatchObject({ v: '1900-01-00' });
expect(getInterceptedCell(date1904Sheet, date1904Workbook, 1, 4, get)).toMatchObject({ v: '1904-01-01' });
- expect(previewSpy).toHaveBeenLastCalledWith('yyyy-mm-dd', 0, 'fr', DateSystem.Date1904);
});
- it('applies and caches a legitimate empty number-format result', () => {
+ it('preserves a legitimate empty number-format result across renders', () => {
+ get(SheetsNumfmtCellContentController);
const worksheet = workbook.getSheetBySheetId('sheet1')!;
- const previewSpy = vi.spyOn(patternUtils, 'getPatternPreviewIgnoreGeneral');
numfmtService.setValues('test', 'sheet1', [{ pattern: ';;;', ranges: [cellToRange(1, 1)] }]);
- expect(getInterceptedCell(worksheet, workbook, 1, 1, get)).toMatchObject({
+ const formattedCell = getInterceptedCell(worksheet, workbook, 1, 1, get);
+ expect(formattedCell).toMatchObject({
v: '',
t: CellValueType.NUMBER,
coverable: false,
});
expect(worksheet.getCellRaw(1, 1)).toMatchObject({ v: '1234.5', t: CellValueType.STRING });
- const previewCallsAfterFirstRender = previewSpy.mock.calls.length;
- getInterceptedCell(worksheet, workbook, 1, 1, get);
- expect(previewSpy).toHaveBeenCalledTimes(previewCallsAfterFirstRender);
+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)).toEqual(formattedCell);
});
- it('resets cached rendering when active sheet changes and supports locale override', () => {
+ it('formats sheets independently and applies locale overrides after switching sheets', () => {
+ const controller = get(SheetsNumfmtCellContentController);
const sheet1 = workbook.getSheetBySheetId('sheet1')!;
const sheet2 = workbook.getSheetBySheetId('sheet2')!;
- const previewSpy = vi.spyOn(patternUtils, 'getPatternPreviewIgnoreGeneral');
numfmtService.setValues('test', 'sheet1', [{ pattern: '0.00', ranges: [cellToRange(1, 1)] }]);
+ numfmtService.setValues('test', 'sheet2', [{ pattern: '0.0', ranges: [cellToRange(1, 1)] }]);
expect(getInterceptedCell(sheet1, workbook, 1, 1, get)).toMatchObject({ v: '1234.50', t: CellValueType.NUMBER });
- let previewCallCount = previewSpy.mock.calls.length;
-
- getInterceptedCell(sheet1, workbook, 1, 1, get);
- expect(previewSpy).toHaveBeenCalledTimes(previewCallCount);
-
workbook.setActiveSheet(sheet2);
-
- getInterceptedCell(sheet1, workbook, 1, 1, get);
- previewCallCount += 1;
- expect(previewSpy).toHaveBeenCalledTimes(previewCallCount);
+ expect(getInterceptedCell(sheet2, workbook, 1, 1, get)).toMatchObject({ v: '9.9' });
workbook.setActiveSheet(sheet1);
- getInterceptedCell(sheet1, workbook, 1, 1, get);
- previewCallCount += 1;
- expect(previewSpy).toHaveBeenCalledTimes(previewCallCount);
+ expect(getInterceptedCell(sheet1, workbook, 1, 1, get)).toMatchObject({ v: '1234.50' });
controller.setNumfmtLocal('fr');
- expect(controller.locale).toBe('fr');
-
- getInterceptedCell(sheet1, workbook, 1, 1, get);
- previewCallCount += 1;
- expect(previewSpy).toHaveBeenCalledTimes(previewCallCount);
+ expect(getInterceptedCell(sheet1, workbook, 1, 1, get)).toMatchObject({ v: '1234,50' });
+ expect(getInterceptedCell(sheet2, workbook, 1, 1, get)).toMatchObject({ v: '9,9' });
});
});
diff --git a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
index 3c2e0a751c..cf81253be0 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
@@ -14,9 +14,8 @@
* limitations under the License.
*/
-import type { ICellData, ICellDataForSheetInterceptor, INumfmtLocaleTag, Workbook } from '@univerjs/core';
-import type { ISetNumfmtMutationParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import type { IUniverSheetsNumfmtConfig } from '../config/config';
+import type { DateSystem, ICellData, ICellDataForSheetInterceptor, INumfmtLocaleTag, Nullable, Workbook } from '@univerjs/core';
+import type { ISetNumfmtMutationParams, ISetRangeValuesMutationParams, ISheetLocation } from '@univerjs/sheets';
import {
CellValueType,
Disposable,
@@ -45,6 +44,7 @@ import {
SheetInterceptorService,
} from '@univerjs/sheets';
import { BehaviorSubject, merge, of, skip, switchMap } from 'rxjs';
+import type { IUniverSheetsNumfmtConfig } from '../config/config';
import { SHEETS_NUMFMT_PLUGIN_CONFIG_KEY } from '../config/config';
import { getPatternPreviewIgnoreGeneral } from '../utils/pattern';
@@ -55,6 +55,7 @@ const TEXT_FORMAT_MARK = {
},
};
export class SheetsNumfmtCellContentController extends Disposable {
+ private readonly _renderCache = new ObjectMatrix<{ result: ICellDataForSheetInterceptor; parameters: string }>();
private _locale$ = new BehaviorSubject<INumfmtLocaleTag | null>(null);
public locale$ = this._locale$.asObservable();
constructor(
@@ -78,109 +79,14 @@ export class SheetsNumfmtCellContentController extends Disposable {
return this._locale$.getValue() ?? getNumfmtLocaleTag(workbook?.getSnapshot().locale ?? this._localeService.getCurrentLocale());
}
- // eslint-disable-next-line max-lines-per-function
private _initInterceptorCellContent() {
- const renderCache = new ObjectMatrix<{ result: ICellData; parameters: string | number }>();
-
this.disposeWithMe(merge(this._locale$, this._localeService.currentLocale$).subscribe(() => {
- renderCache.reset();
+ this._renderCache.reset();
}));
this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
effect: InterceptorEffectEnum.Value | InterceptorEffectEnum.Style,
-
- // eslint-disable-next-line max-lines-per-function, complexity
- handler: (cell, location, next) => {
- // If the cell is empty, or the cell type is boolean or force_string, do not process it.
- // Cell type is number or number string, it will be applied number format.
- if (!cell || cell.v === undefined || cell.v === null || cell.t === CellValueType.BOOLEAN || cell.t === CellValueType.FORCE_STRING) {
- return next(cell);
- }
-
- const unitId = location.unitId;
- const sheetId = location.subUnitId;
- const locale = this.getLocale(location.workbook);
- const dateSystem = location.workbook.getDateSystem();
- let numfmtValue;
-
- if (cell?.s) {
- const style = location.workbook.getStyles().get(cell.s);
- if (style?.n) {
- numfmtValue = style.n;
- }
- }
-
- if (!numfmtValue) {
- numfmtValue = this._numfmtService.getValue(unitId, sheetId, location.row, location.col);
- }
-
- // If the cell is not formatted, or the format is 'General', do not process it
- // e.g. { v: '001', t: 1, s: { n: { pattern: 'General' } } } should display as '001'
- if (isDefaultFormat(numfmtValue?.pattern)) {
- return next(cell);
- }
-
- // If the cell not specified number type, then check the cell value type
- if (cell.t !== CellValueType.NUMBER) {
- const type = checkCellValueType(cell.v, cell.t);
- // just handle number/number string/number string with text format, other type will not be processed
- if (
- type !== CellValueType.NUMBER &&
- !(
- isTextFormat(numfmtValue?.pattern) &&
- typeof cell.v === 'string' &&
- typeof getNumfmtParseValueFilter(cell.v, { locale, dateSystem })?.v === 'number'
- )
- ) {
- return next(cell);
- }
- }
-
- const originCellValue = cell;
- if (!cell || cell === location.rawData) {
- cell = { ...location.rawData };
- }
-
- // Add error marker to text format number
- if (isTextFormat(numfmtValue?.pattern)) {
- // If the user has disabled the text format mark, do not show it
- if (this._configService.getConfig<IUniverSheetsNumfmtConfig>(SHEETS_NUMFMT_PLUGIN_CONFIG_KEY)?.disableTextFormatMark) {
- cell.t = CellValueType.STRING;
- return next(cell);
- }
-
- cell.t = CellValueType.STRING;
- cell.markers = { ...cell?.markers, ...TEXT_FORMAT_MARK };
- return next(cell);
- }
-
- const cacheParameters = `${unitId}_${sheetId}_${originCellValue.v}_${numfmtValue?.pattern}_${locale}_${dateSystem}`;
- const cache = renderCache.getValue(location.row, location.col);
- if (cache && cache.parameters === cacheParameters) {
- return next({ ...cell, ...cache.result });
- }
-
- const info = getPatternPreviewIgnoreGeneral(numfmtValue?.pattern as string, Number(originCellValue.v), locale, dateSystem);
- const numfmtRes = info.result;
- const res: ICellDataForSheetInterceptor = { v: numfmtRes, t: CellValueType.NUMBER };
- if (numfmtRes === '') {
- res.coverable = false;
- }
- if (info.color) {
- const color = this._themeService.getColorFromTheme(`${info.color}.500`) ?? info.color;
-
- if (color) {
- res.interceptorStyle = { cl: { rgb: color } };
- }
- }
-
- renderCache.setValue(location.row, location.col, {
- result: res,
- parameters: cacheParameters,
- });
- Object.assign(cell, res);
- return next(cell);
- },
+ handler: (cell, location, next) => next(this._formatCell(cell, location)),
priority: InterceptCellContentPriority.NUMFMT,
}));
@@ -191,14 +97,14 @@ export class SheetsNumfmtCellContentController extends Disposable {
const v = params.values[key];
v.ranges.forEach((range) => {
Range.foreach(range, (row, col) => {
- renderCache.realDeleteValue(row, col);
+ this._renderCache.realDeleteValue(row, col);
});
});
});
} else if (commandInfo.id === SetRangeValuesMutation.id) {
const params = commandInfo.params as ISetRangeValuesMutationParams;
new ObjectMatrix(params.cellValue).forValue((row, col) => {
- renderCache.realDeleteValue(row, col);
+ this._renderCache.realDeleteValue(row, col);
});
}
}));
@@ -209,7 +115,70 @@ export class SheetsNumfmtCellContentController extends Disposable {
switchMap((workbook) => workbook?.activeSheet$ ?? of(null)),
skip(1)
)
- .subscribe(() => renderCache.reset())
+ .subscribe(() => this._renderCache.reset())
+ );
+ }
+
+ private _formatCell(
+ cell: Nullable<ICellDataForSheetInterceptor>,
+ location: ISheetLocation & { rawData: Nullable<ICellData> }
+ ): Nullable<ICellDataForSheetInterceptor> {
+ if (!cell || cell.v == null || cell.t === CellValueType.BOOLEAN || cell.t === CellValueType.FORCE_STRING) {
+ return cell;
+ }
+
+ const { unitId, subUnitId: sheetId, row, col, workbook } = location;
+ const locale = this.getLocale(workbook);
+ const dateSystem = workbook.getDateSystem();
+ const numfmtValue = workbook.getStyles().get(cell.s)?.n ?? this._numfmtService.getValue(unitId, sheetId, row, col);
+ const pattern = numfmtValue?.pattern;
+ // General must preserve numeric strings such as '001'.
+ if (isDefaultFormat(pattern)) {
+ return cell;
+ }
+
+ if (!this._isNumericCell(cell, pattern, locale, dateSystem)) {
+ return cell;
+ }
+
+ const formattedCell = cell === location.rawData ? { ...cell } : cell;
+
+ if (isTextFormat(pattern)) {
+ formattedCell.t = CellValueType.STRING;
+ if (!this._configService.getConfig<IUniverSheetsNumfmtConfig>(SHEETS_NUMFMT_PLUGIN_CONFIG_KEY)?.disableTextFormatMark) {
+ formattedCell.markers = { ...formattedCell.markers, ...TEXT_FORMAT_MARK };
+ }
+ return formattedCell;
+ }
+
+ const cacheParameters = `${unitId}_${sheetId}_${cell.v}_${pattern}_${locale}_${dateSystem}`;
+ const cache = this._renderCache.getValue(row, col);
+ if (cache && cache.parameters === cacheParameters) {
+ return { ...formattedCell, ...cache.result };
+ }
+
+ const info = getPatternPreviewIgnoreGeneral(pattern as string, Number(cell.v), locale, dateSystem);
+ const res: ICellDataForSheetInterceptor = { v: info.result, t: CellValueType.NUMBER };
+ if (info.result === '') {
+ res.coverable = false;
+ }
+ if (info.color) {
+ const color = this._themeService.getColorFromTheme(`${info.color}.500`) ?? info.color;
+ if (color) {
+ res.interceptorStyle = { cl: { rgb: color } };
+ }
+ }
+
+ this._renderCache.setValue(row, col, { result: res, parameters: cacheParameters });
+ Object.assign(formattedCell, res);
+ return formattedCell;
+ }
+
+ private _isNumericCell(cell: ICellData, pattern: string | undefined, locale: INumfmtLocaleTag, dateSystem: DateSystem): boolean {
+ return cell.t === CellValueType.NUMBER || checkCellValueType(cell.v, cell.t) === CellValueType.NUMBER || (
+ isTextFormat(pattern) &&
+ typeof cell.v === 'string' &&
+ typeof getNumfmtParseValueFilter(cell.v, { locale, dateSystem })?.v === 'number'
);
}
diff --git a/packages/sheets-numfmt/src/utils/__tests__/currency.spec.ts b/packages/sheets-numfmt/src/utils/__tests__/currency.spec.ts
new file mode 100644
index 0000000000..fa3a9f70a1
--- /dev/null
+++ b/packages/sheets-numfmt/src/utils/__tests__/currency.spec.ts
@@ -0,0 +1,27 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { currencySymbols } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { getCurrencyType } from '../currency';
+
+describe('getCurrencyType', () => {
+ it('getCurrencyType', () => {
+ expect(getCurrencyType(`_(${currencySymbols[7]} 123123`)).toBe(currencySymbols[7]);
+ expect(getCurrencyType('_(# 123123')).toBeUndefined();
+ expect(getCurrencyType(`_(${currencySymbols[7]} 123123 ${currencySymbols[8]}`)).toBe(currencySymbols[7]);
+ });
+});
diff --git a/packages/sheets-numfmt/src/utils/__tests__/decimal.spec.ts b/packages/sheets-numfmt/src/utils/__tests__/decimal.spec.ts
new file mode 100644
index 0000000000..05e0bfd511
--- /dev/null
+++ b/packages/sheets-numfmt/src/utils/__tests__/decimal.spec.ts
@@ -0,0 +1,46 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { getDecimalFromPattern, getDecimalString, isPatternHasDecimal, setPatternDecimal } from '../decimal';
+
+describe('decimal formats', () => {
+ it('getDecimalFromPattern', () => {
+ expect(getDecimalFromPattern('_(###0.000);--###0.00')).toBe(3);
+ expect(getDecimalFromPattern('_(###0);-###0.00')).toBe(0); // the function decimal just use positive,negative configuration ignored
+ expect(getDecimalFromPattern('_(###0.0);--###0.00')).toBe(1);
+ expect(getDecimalFromPattern('_(###0.);--###0.00')).toBe(0);
+ });
+
+ it('getDecimalString', () => {
+ expect(getDecimalString(3)).toBe('000');
+ expect(getDecimalString(-1)).toBe('');
+ expect(getDecimalString(0)).toBe('');
+ });
+
+ it('setPatternDecimal', () => {
+ expect(setPatternDecimal('0.', 4)).toBe('0.0000');
+ expect(setPatternDecimal('.', 4)).toBe('.0000');
+ expect(setPatternDecimal('0.0', 4)).toBe('0.0000');
+ expect(setPatternDecimal('0.0', 0)).toBe('0');
+ });
+
+ it('isPatternHasDecimal', () => {
+ expect(isPatternHasDecimal('0.00')).toBe(true);
+ expect(isPatternHasDecimal('#,##0')).toBe(true);
+ expect(isPatternHasDecimal('General')).toBe(false);
+ });
+});
diff --git a/packages/sheets-numfmt/src/utils/__tests__/mutation.spec.ts b/packages/sheets-numfmt/src/utils/__tests__/mutation.spec.ts
new file mode 100644
index 0000000000..5add5d45e8
--- /dev/null
+++ b/packages/sheets-numfmt/src/utils/__tests__/mutation.spec.ts
@@ -0,0 +1,182 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { cellToRange } from '@univerjs/core';
+import { RemoveNumfmtMutation, SetNumfmtMutation } from '@univerjs/sheets';
+import { describe, expect, it } from 'vitest';
+import { mergeNumfmtMutations } from '../mutation';
+
+describe('mergeNumfmtMutations', () => {
+ it('mergeNumfmtMutations', () => {
+ const result = mergeNumfmtMutations([
+ {
+ id: SetNumfmtMutation.id,
+ params: {
+ values: {
+ a: { ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)] },
+ },
+ refMap: { a: { pattern: '', type: '' } },
+ },
+ },
+ {
+ id: RemoveNumfmtMutation.id,
+ params: {
+ ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)],
+ },
+ },
+ {
+ id: SetNumfmtMutation.id,
+ params: {
+ values: {
+ a: { ranges: [cellToRange(4, 6), cellToRange(4, 5)] },
+ },
+ refMap: { a: { pattern: '', type: '' } },
+ },
+ },
+ ]);
+
+ const removeMutation = result[0] as { params: { ranges: unknown } };
+ const setMutation = result[1] as { params: { values: Record<string, { ranges: unknown }> } };
+
+ expect(result[0].id).toBe(RemoveNumfmtMutation.id);
+ expect(result[1].id).toBe(SetNumfmtMutation.id);
+ expect(removeMutation.params.ranges).toEqual([
+ {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 4,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 5,
+ },
+ ]);
+ expect(setMutation.params.values['1'].ranges).toEqual([
+ {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 4,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 6,
+ },
+ ]);
+ });
+
+ it('mergeNumfmtMutations multiple data formats of different types', () => {
+ const result = mergeNumfmtMutations([
+ {
+ id: SetNumfmtMutation.id,
+ params: {
+ values: {
+ a: { ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)] },
+ },
+ refMap: { a: { pattern: 'a', type: '' } },
+ },
+ },
+ {
+ id: RemoveNumfmtMutation.id,
+ params: {
+ ranges: [cellToRange(2, 3), cellToRange(2, 4), cellToRange(4, 5)],
+ },
+ },
+ {
+ id: SetNumfmtMutation.id,
+ params: {
+ values: {
+ a: { ranges: [cellToRange(4, 6), cellToRange(4, 5)] },
+ },
+ refMap: { a: { pattern: 'b', type: '' } },
+ },
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ id: 'sheet.mutation.remove.numfmt',
+ params: {
+ ranges: [
+ {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 4,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 5,
+ },
+ ],
+ unitId: undefined,
+ subUnitId: undefined,
+ },
+ },
+ {
+ id: 'sheet.mutation.set.numfmt',
+ params: {
+ values: {
+ 1: {
+ ranges: [
+ {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 4,
+ },
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 5,
+ },
+ ],
+ },
+ 2: {
+ ranges: [
+ {
+ startRow: 4,
+ endRow: 4,
+ startColumn: 5,
+ endColumn: 6,
+ },
+ ],
+ },
+ },
+ refMap: {
+ 1: {
+ pattern: 'a',
+ type: '',
+ },
+ 2: {
+ pattern: 'b',
+ type: '',
+ },
+ },
+ unitId: undefined,
+ subUnitId: undefined,
+ },
+ },
+ ]);
+ });
+});
diff --git a/packages/sheets-numfmt/src/utils/__tests__/options.spec.ts b/packages/sheets-numfmt/src/utils/__tests__/options.spec.ts
index 5db7c02851..aa722d0c99 100644
--- a/packages/sheets-numfmt/src/utils/__tests__/options.spec.ts
+++ b/packages/sheets-numfmt/src/utils/__tests__/options.spec.ts
@@ -17,7 +17,7 @@
import { LocaleType, numfmt } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { DATEFMTLISG } from '../../base/const/formatdetail';
-import { getDateFormatOptions } from '../options';
+import { getCurrencyFormatOptions, getCurrencyOptions, getDateFormatOptions, getNumberFormatOptions } from '../options';
describe('getDateFormatOptions', () => {
it('keeps the legacy public options when no locale is supplied', () => {
@@ -66,3 +66,21 @@ describe('getDateFormatOptions', () => {
expect(options.some((option) => /[年月日]|上午|下午/.test(option.label))).toBe(false);
});
});
+
+describe('format options', () => {
+ it('option helpers expose formatted labels and values', () => {
+ expect(getCurrencyOptions()[0]).toEqual({ label: 'Rp', value: 'Rp' });
+ expect(getCurrencyFormatOptions('€')[0]).toMatchObject({
+ label: expect.stringContaining('€'),
+ value: expect.stringContaining('€'),
+ });
+ expect(getDateFormatOptions()[0]).toMatchObject({
+ label: expect.any(String),
+ value: expect.any(String),
+ });
+ expect(getNumberFormatOptions()[0]).toMatchObject({
+ label: expect.any(String),
+ value: expect.any(String),
+ });
+ });
+});
diff --git a/packages/sheets-numfmt/src/utils/__tests__/pattern.spec.ts b/packages/sheets-numfmt/src/utils/__tests__/pattern.spec.ts
index e8434d3cd5..7ec88a873b 100644
--- a/packages/sheets-numfmt/src/utils/__tests__/pattern.spec.ts
+++ b/packages/sheets-numfmt/src/utils/__tests__/pattern.spec.ts
@@ -15,8 +15,8 @@
*/
import { DEFAULT_NUMBER_FORMAT } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
-import { getPatternPreview, getPatternType } from '../pattern';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { getPatternPreview, getPatternPreviewIgnoreGeneral, getPatternType } from '../pattern';
describe('getPatternType', () => {
it('classifies conditional general formats as number formats', () => {
@@ -40,3 +40,34 @@ describe('getPatternType', () => {
expect(getPatternPreview(pattern, -1)).toEqual({ result: '完成' });
});
});
+
+describe('getPatternPreview', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ { pattern: '[Red]0.00;[Green]\\-0.00;0.00', colors: ['red', 'green', undefined, 'red'] },
+ { pattern: '[Red]0.00;[Green]\\-0.00;[Blue]0.00', colors: ['red', 'green', 'blue', 'red'] },
+ { pattern: '[Red]0.00', colors: ['red', 'red', 'red', 'red'] },
+ { pattern: '[Red]0.00;[Green]\\-0.00', colors: ['red', 'green', 'red', 'red'] },
+ { pattern: '[Red][>=10]0.00;[Blue][<0]\\-0.00;[Green]0.00', colors: ['red', 'blue', 'green', 'green'] },
+ { pattern: '0.00', colors: [undefined, undefined, undefined, undefined] },
+ ])('returns the active section color for $pattern', ({ pattern, colors }) => {
+ [12.34, -12.34, 0, 5].forEach((value, index) => {
+ expect(getPatternPreview(pattern, value)).toEqual({
+ result: value.toFixed(2),
+ color: colors[index],
+ });
+ });
+ });
+
+ it('pattern preview helpers return types and gracefully handle general or invalid formats', () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+
+ expect(getPatternType('0%')).toBe('percent');
+ expect(getPatternPreview('0.00', 12.3)).toEqual({ result: '12.30' });
+ expect(getPatternPreviewIgnoreGeneral(DEFAULT_NUMBER_FORMAT, 0.1 + 0.2)).toEqual({ result: '0.3' });
+ expect(getPatternPreview('[invalid', 42)).toEqual({ result: '42' });
+ });
+});
diff --git a/packages/sheets-numfmt/src/utils/__tests__/scientific-notation.spec.ts b/packages/sheets-numfmt/src/utils/__tests__/scientific-notation.spec.ts
new file mode 100644
index 0000000000..bdf59885b5
--- /dev/null
+++ b/packages/sheets-numfmt/src/utils/__tests__/scientific-notation.spec.ts
@@ -0,0 +1,43 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CellValueType, DEFAULT_NUMBER_FORMAT, DEFAULT_TEXT_FORMAT_EXCEL } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { getScientificNotationFormatFromCell, isAllowedPatternForScientificNotationNumber, isScientificNotationNumericCell } from '../scientific-notation';
+
+describe('scientific notation', () => {
+ it('scientific notation helpers detect numeric cells and derive display patterns from mantissa decimals', () => {
+ expect(isScientificNotationNumericCell({ v: 1e21, t: CellValueType.NUMBER })).toBe(true);
+ expect(isScientificNotationNumericCell({ v: 1.2345e31, t: CellValueType.NUMBER })).toBe(true);
+ expect(isScientificNotationNumericCell({ v: '1e21', t: CellValueType.STRING })).toBe(false);
+ expect(isScientificNotationNumericCell({ v: 123, t: CellValueType.NUMBER })).toBe(false);
+ expect(isScientificNotationNumericCell(null)).toBe(false);
+
+ expect(getScientificNotationFormatFromCell({ v: 1e21, t: CellValueType.NUMBER })).toBe('0.00E+00');
+ expect(getScientificNotationFormatFromCell({ v: 1.2e21, t: CellValueType.NUMBER })).toBe('0.00E+00');
+ expect(getScientificNotationFormatFromCell({ v: 1.2345e31, t: CellValueType.NUMBER })).toBe('0.0000E+00');
+ expect(getScientificNotationFormatFromCell({ v: -1.2345e-31, t: CellValueType.NUMBER })).toBe('0.0000E+00');
+ });
+
+ it('scientific notation format guard only allows general, text, and scientific patterns', () => {
+ expect(isAllowedPatternForScientificNotationNumber(undefined)).toBe(true);
+ expect(isAllowedPatternForScientificNotationNumber(DEFAULT_NUMBER_FORMAT)).toBe(true);
+ expect(isAllowedPatternForScientificNotationNumber(DEFAULT_TEXT_FORMAT_EXCEL)).toBe(true);
+ expect(isAllowedPatternForScientificNotationNumber('0.00E+00')).toBe(true);
+ expect(isAllowedPatternForScientificNotationNumber('0.00')).toBe(false);
+ expect(isAllowedPatternForScientificNotationNumber('0%')).toBe(false);
+ });
+});
diff --git a/packages/sheets-numfmt/src/utils/pattern.ts b/packages/sheets-numfmt/src/utils/pattern.ts
index f8d3a7c4b0..ccacbcc3f0 100644
--- a/packages/sheets-numfmt/src/utils/pattern.ts
+++ b/packages/sheets-numfmt/src/utils/pattern.ts
@@ -38,21 +38,13 @@ export const getPatternPreview = (
locale: INumfmtLocaleTag = 'en',
dateSystem?: DateSystem
): IPatternPreview => {
- // in the source code of numfmt, the formatColor function will read the the partitions[3]
try {
const formatColor = numfmt.formatColor(pattern, value);
const color = formatColor ? String(formatColor) : undefined;
const result = numfmt.format(pattern, value, { locale, dateSystem, throws: false });
- if (value < 0) {
- // pay attention, controllers/ui.controller.ts
- // in the pattern, the negative value color may be upper case one , so if we read a color with UpperCase, we should return the color with lower case for our theme system
- return {
- result,
- color,
- };
- }
return {
result,
+ color,
};
} catch (e) {
console.warn('getPatternPreview error:', pattern, e);