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.

chore(*): update numfmt (#5248)

白熱c825657a0aa3
diff --git a/examples/src/sheets-webcomponent/univer.tsx b/examples/src/sheets-webcomponent/univer.tsx
deleted file mode 100644
index 0929e4b656..0000000000
--- a/examples/src/sheets-webcomponent/univer.tsx
+++ /dev/null
@@ -1,70 +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 { LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';
-import { UniverDocsPlugin } from '@univerjs/docs';
-import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
-import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
-import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
-import { DEFAULT_WORKBOOK_DATA_DEMO } from '@univerjs/mockdata';
-import zhCN from '@univerjs/mockdata/locales/zh-CN';
-import { UniverSheetsPlugin } from '@univerjs/sheets';
-import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
-import { UniverSheetsFormulaUIPlugin } from '@univerjs/sheets-formula-ui';
-import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';
-import { UniverSheetsNumfmtUIPlugin } from '@univerjs/sheets-numfmt-ui';
-import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
-import { UniverUIPlugin } from '@univerjs/ui';
-import { useEffect, useRef } from 'react';
-
-import '../global.css';
-
-export function UniverComponent() {
- const containerRef = useRef<HTMLDivElement>(null!);
-
- useEffect(() => {
- const univer = new Univer({
- locale: LocaleType.ZH_CN,
- locales: {
- [LocaleType.ZH_CN]: zhCN,
- },
- logLevel: LogLevel.VERBOSE,
- });
-
- univer.registerPlugin(UniverFormulaEnginePlugin);
- univer.registerPlugin(UniverRenderEnginePlugin);
- univer.registerPlugin(UniverUIPlugin, {
- container: containerRef.current,
- });
- univer.registerPlugin(UniverDocsPlugin);
- univer.registerPlugin(UniverDocsUIPlugin);
-
- // sheets plugin
- univer.registerPlugin(UniverSheetsPlugin);
- univer.registerPlugin(UniverSheetsUIPlugin);
- univer.registerPlugin(UniverSheetsFormulaUIPlugin);
- // sheet feature plugins
- univer.registerPlugin(UniverSheetsNumfmtPlugin);
- univer.registerPlugin(UniverSheetsNumfmtUIPlugin);
- univer.registerPlugin(UniverSheetsFormulaPlugin);
-
- univer.createUnit(UniverInstanceType.UNIVER_SHEET, DEFAULT_WORKBOOK_DATA_DEMO);
- }, []);
-
- return (
- <div ref={containerRef} className="univer-h-full" />
- );
-};
diff --git a/packages/core/package.json b/packages/core/package.json
index 058135be21..e0b98f7bd0 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -82,7 +82,7 @@
"kdbush": "^4.0.2",
"lodash-es": "^4.17.21",
"nanoid": "5.1.5",
- "numfmt": "^2.5.2",
+ "numfmt": "^3.2.2",
"ot-json1": "^1.0.2",
"rbush": "^4.0.1"
},
diff --git a/packages/core/src/facade/f-util.ts b/packages/core/src/facade/f-util.ts
index 7dcf8d7022..e2c2729c66 100644
--- a/packages/core/src/facade/f-util.ts
+++ b/packages/core/src/facade/f-util.ts
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { INumfmt } from '@univerjs/core';
import { numfmt, Rectangle, Tools } from '@univerjs/core';
/**
@@ -81,7 +80,7 @@ export class FUtil {
* console.log(text);
* ```
*/
- get numfmt(): INumfmt {
+ get numfmt(): typeof numfmt {
return numfmt;
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index a7a4eb7b56..d58f3dac1d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -18,7 +18,6 @@ import { installShims } from './common/shims';
installShims();
export { getPlainText } from './docs/data-model/text-x/build-utils/parse';
-export type { INumfmt } from './shared/types/numfmt.type';
export { debounce, get, merge, mergeWith, set } from 'lodash-es';
export { textDiff } from './shared/text-diff';
export { dedupe, dedupeBy, groupBy, makeArray, remove, rotate } from './common/array';
diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.ts
index 652bf55a89..11268abafd 100644
--- a/packages/core/src/shared/index.ts
+++ b/packages/core/src/shared/index.ts
@@ -31,7 +31,7 @@ export * from './hash-algorithm';
export * from './lifecycle';
export * from './locale';
export { LRUHelper, LRUMap } from './lru/lru-map';
-export { type INumfmtLocalTag, numfmt } from './numfmt';
+export { type INumfmtLocalTag, isPatternEqualWithoutDecimal, numfmt } from './numfmt';
export * from './object-matrix';
export { queryObjectMatrix } from './object-matrix-query';
export { moveRangeByOffset, splitIntoGrid } from './range';
diff --git a/packages/core/src/shared/numfmt.ts b/packages/core/src/shared/numfmt.ts
index 395bcb3413..6bab180611 100644
--- a/packages/core/src/shared/numfmt.ts
+++ b/packages/core/src/shared/numfmt.ts
@@ -14,9 +14,96 @@
* limitations under the License.
*/
-import type { INumfmt, LocaleTag } from './types/numfmt.type';
-// @ts-ignore
-import _numfmt from 'numfmt';
+import * as numfmt from 'numfmt';
-const numfmt = _numfmt as INumfmt;
-export { LocaleTag as INumfmtLocalTag, numfmt };
+export * as numfmt from 'numfmt';
+
+export type INumfmtLocalTag =
+ | 'zh-CN'
+ | 'zh-TW'
+ | 'cs'
+ | 'da'
+ | 'nl'
+ | 'en'
+ | 'fi'
+ | 'fr'
+ | 'de'
+ | 'el'
+ | 'hu'
+ | 'is'
+ | 'id'
+ | 'it'
+ | 'ja'
+ | 'ko'
+ | 'nb'
+ | 'pl'
+ | 'pt'
+ | 'ru'
+ | 'sk'
+ | 'es'
+ | 'sv'
+ | 'th'
+ | 'tr'
+ | 'vi';
+
+ /**
+ * Determines whether two patterns are equal, excluding differences in decimal places.
+ * This function ignores the decimal part of the patterns and the positive color will be ignored but negative color will be considered.
+ * more info can check the test case.
+ */
+export const isPatternEqualWithoutDecimal = (patternA: string, patternB: string): boolean => {
+ if ((patternA && !patternB) || (!patternA && patternB)) {
+ return false;
+ }
+
+ const getStringWithoutDecimal = (pattern: string): string => {
+ const tokens = numfmt.tokenize(pattern);
+ let result = '';
+ let isDecimalPart = false;
+ let isColorBefore = false;
+
+ for (const token of tokens) {
+ if (token.type === numfmt.tokenTypes.POINT) {
+ isDecimalPart = true; // Start ignoring tokens after the decimal point
+ continue;
+ }
+ // for the excel number
+
+ // this if should be before the color token check
+ if (isColorBefore && token.type === numfmt.tokenTypes.MINUS) {
+ // ignore the minus token in the decimal part after the color token
+ continue;
+ }
+
+ if (token.type === numfmt.tokenTypes.SKIP) {
+ // Skip tokens that are not relevant to the string representation
+ continue;
+ }
+
+ if (token.type === numfmt.tokenTypes.COLOR) {
+ isColorBefore = true; // If we are in the decimal part, we ignore the color tokens
+ continue;
+ } else {
+ isColorBefore = false; // Reset after processing the color part
+ }
+
+ if (isDecimalPart && token.type === numfmt.tokenTypes.ZERO) {
+ // If we are in the decimal part, we ignore the number tokens
+ continue;
+ } else {
+ isDecimalPart = false; // Reset after processing the decimal part
+ }
+
+ if (!isDecimalPart) {
+ result += token.value || '';
+ }
+ }
+
+ return result;
+ };
+
+ const normalizedA = getStringWithoutDecimal(patternA);
+ const normalizedB = getStringWithoutDecimal(patternB);
+
+ return normalizedA === normalizedB;
+};
diff --git a/packages/core/src/shared/types/numfmt.type.ts b/packages/core/src/shared/types/numfmt.type.ts
deleted file mode 100644
index fd51066633..0000000000
--- a/packages/core/src/shared/types/numfmt.type.ts
+++ /dev/null
@@ -1,303 +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.
- */
-
-type FormatType =
- | 'currency'
- | 'date'
- | 'datetime'
- | 'error'
- | 'fraction'
- | 'general'
- | 'grouped'
- | 'number'
- | 'percent'
- | 'scientific'
- | 'text'
- | 'time';
-
-/**
- * An arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
- *
- * text: 15
- * datetime: 10.8
- * date: 10.8
- * time: 10.8
- * percent: 10.6
- * currency: 10.4
- * grouped: 10.2
- * scientific: 6
- * number: 4
- * fraction: 2
- * general: 0
- * error: 0
- */
-type Level = 15 | 10.8 | 10.6 | 10.4 | 10.2 | 6 | 4 | 2 | 0;
-
-interface Info {
- type: FormatType;
-
- /**
- * Correspond to the output from same named functions found on the formatters.
- */
- isDate: boolean;
- isText: boolean;
- isPercent: boolean;
-
- /** The maximum number of decimals this format will emit. */
- maxDecimals: number;
-
- /**
- * 1 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
- */
- color: 0 | 1;
-
- /**
- * 1 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
- */
- parentheses: 0 | 1;
-
- /**
- * 1 if the positive portion of the format uses a thousands separator, else a 0.
- */
- grouped: 1;
- /**
- * Corresponds to Excel's CELL("format") functionality. It is should match Excel's quirky behaviour fairly well.
- */
- code: string;
- /**
- * The multiplier used when formatting the number (100 for percentages).
- */
- scale: 1;
-
- /**
- * An arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
- */
- level: Level;
- _partitions: Array<{
- color: string;
- tokens: Array<{ type: 'num'; num: string } | { type: 'point'; value: string } | { type: 'frac'; num: string }>;
- }>;
-}
-
-interface DateInfo {
- /** If any `y` or `b` operator was found in the pattern. */
- year: boolean;
-
- /** If any `m` operator was found in the pattern. */
- month: boolean;
-
- /** If any `d` operator was found in the pattern (including ones that emit weekday). */
- day: boolean;
-
- /** If any `h` operator was found in the pattern. */
- hours: boolean;
-
- /** If any `:m` operator was found in the pattern. */
- minutes: boolean;
- /** If any `s` operator was found in the pattern. */
- seconds: boolean;
-
- /** Will be set to `12` if AM/PM operators are being used in the formatting string, else it will be set to `24`. */
- clockType: 24 | 12;
-}
-
-interface Options {
- /**
- * A [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) string tag. Locale default is english with a \u00a0 grouping symbol
- *
- * @default ""
- */
- locale: LocaleTag;
-
- /**
- * Should the formatter throw an error if a provided pattern is invalid. If not, a formatter will be constructed which only ever outputs an error string (see invalid in this table).
- * @default true
- */
- throws: boolean;
-
- /**
- * The string emitted when no-throw mode fails to parse a pattern.
- * @default "######"
- */
- invalid: string;
-
- /**
- * By default the formatters will emit [non-breaking-space](https://en.wikipedia.org/wiki/Non-breaking_space) rather than a regular space when emitting the formatted number. Setting this to false will make it use regular spaces instead.
- * @default true
- */
- nbsp: boolean;
-
- /**
- * Simulate the Lotus 1-2-3 [1900 leap year bug](https://docs.microsoft.com/en-us/office/troubleshoot/excel/wrongly-assumes-1900-is-leap-year). It is a requirement in the Ecma OOXML specification so it is on by default.
- *
- * @default false
- */
- leap1900: boolean;
-
- /**
- * Should the formatter throw an error when trying to format a date that is out of bounds?
- *
- * @default false
- */
- dateErrorThrows: boolean;
-
- /**
- * Should the formatter switch to a General number format when trying to format a date that is out of bounds?
- * @default true
- */
- dateErrorNumber: boolean;
-
- /**
- * The string emitted when a formatter fails to format a date that is out of bounds.
- * @default "######"
- */
- overflow: string;
-
- /**
- * Extends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
- * @default true
- */
- dateSpanLarge: boolean;
-
- /**
- * Normally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
- * @default false
- */
- ignoreTimezone: boolean;
-
- /**
- * when using the numfmt.parseDate, numfmt.parseValue and numfmt.dateFromSerial functions, the output will be a Date object.
- * @default false
- */
- nativeDate: boolean;
-}
-
-interface LocaleData {
- // non-breaking space
- group: string;
- decimal: string;
- positive: string;
- negative: string;
- percent: string;
- exponent: string;
- nan: string;
- infinity: string;
- ampm: [string, string];
-
- // gregorian calendar
- mmmm: string[];
- mmm: string[];
- dddd: string[];
- ddd: string[];
-
- // islamic calendar
- mmmm6: string[];
- mmm6: string[];
-}
-
-interface Formatter {
- isDate(): boolean;
- isPercent(): boolean;
- isText(): boolean;
- color(value: number): string;
- info: Info;
- dateInfo: DateInfo;
- (value: number): string;
-}
-
-export type LocaleTag =
- | 'zh-CN'
- | 'zh-TW'
- | 'cs'
- | 'da'
- | 'nl'
- | 'en'
- | 'fi'
- | 'fr'
- | 'de'
- | 'el'
- | 'hu'
- | 'is'
- | 'id'
- | 'it'
- | 'ja'
- | 'ko'
- | 'nb'
- | 'pl'
- | 'pt'
- | 'ru'
- | 'sk'
- | 'es'
- | 'sv'
- | 'th'
- | 'tr'
- | 'vi';
-
-export interface ParsedReturnType {
- /**
- * The parsed value. For dates, this will be an Excel style serial date unless the nativeDate option is used.
- */
- v: number | string | boolean | Date;
- /**
- * (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.
- */
- z?: string;
-}
-
-type _Year = number;
-type _MonthIndex = number;
-type _Date = number | undefined;
-type _Hours = number | undefined;
-type _Minutes = number | undefined;
-type _Seconds = number | undefined;
-type _Ms = number | undefined;
-type DateValue = [_Year, _MonthIndex, _Date, _Hours, _Minutes, _Seconds, _Ms];
-
-type ParseValue = number | boolean | DateValue | Date | null;
-
-export interface INumfmt {
- (value: string, opt?: Options): Formatter;
-
- format(pattern: string, value: ParseValue, opt?: Partial<Options>): string;
-
- round(value: number, places?: number): number;
-
- /**
- * @internal
- */
- parseLocale(tag: LocaleTag): void;
- getLocale(tag: LocaleTag): LocaleData | null;
-
- addLocale(data: Partial<LocaleData>, tag: LocaleTag): void;
-
- isDate(format: string): boolean;
- isPercent(format: string): boolean;
- isText(format: string): boolean;
-
- getInfo(format: string): Info;
-
- parseValue(value: string, op?: Options): ParsedReturnType;
- parseNumber(value: string, op?: Options): ParsedReturnType;
- parseDate(value: string, op?: Options): ParsedReturnType;
- parseTime(value: string, op?: Options): ParsedReturnType;
- parseBool(value: string, op?: Options): ParsedReturnType;
-
- dateToSerial(value: Date | [number, number, number], opt?: Options): number | string;
-
- dateFromSerial(value: number, opt?: Options): [number, number, number, number, number, number];
-
- options(op: Partial<Options>): void;
-}
diff --git a/packages/engine-formula/package.json b/packages/engine-formula/package.json
index 61ae736b5b..0fa9aef73c 100644
--- a/packages/engine-formula/package.json
+++ b/packages/engine-formula/package.json
@@ -76,8 +76,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/engine-numfmt": "workspace:*",
"@univerjs/rpc": "workspace:*",
- "decimal.js": "^10.5.0",
- "numfmt": "^2.5.2"
+ "decimal.js": "^10.5.0"
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
diff --git a/packages/engine-formula/src/basics/date.ts b/packages/engine-formula/src/basics/date.ts
index cff1b10f7f..be3f026a4a 100644
--- a/packages/engine-formula/src/basics/date.ts
+++ b/packages/engine-formula/src/basics/date.ts
@@ -169,7 +169,7 @@ export function parseFormattedTime(value: string) {
}
export function isDate(format: string) {
- return numfmt.isDate(format);
+ return numfmt.getFormatInfo(format).isDate;
}
// Weekend is a weekend number or string that specifies when weekends occur.
@@ -301,12 +301,12 @@ export function getDateSerialNumberByObject(serialNumberObject: BaseValueObject)
const dateValue = serialNumberObject.getValue();
if (serialNumberObject.isString()) {
- let dateSerial;
+ let dateSerial: any;
if (parseFormattedDate(`${dateValue}`)) {
- dateSerial = parseFormattedDate(`${dateValue}`).v;
+ dateSerial = parseFormattedDate(`${dateValue}`)!.v;
} else if (parseFormattedTime(`${dateValue}`)) {
- dateSerial = parseFormattedTime(`${dateValue}`).v;
+ dateSerial = parseFormattedTime(`${dateValue}`)!.v;
} else if (isRealNum(dateValue)) {
dateSerial = +dateValue;
} else {
diff --git a/packages/engine-formula/src/engine/utils/numfmt-kit.ts b/packages/engine-formula/src/engine/utils/numfmt-kit.ts
index 6eb47a40f7..9648aab69c 100644
--- a/packages/engine-formula/src/engine/utils/numfmt-kit.ts
+++ b/packages/engine-formula/src/engine/utils/numfmt-kit.ts
@@ -224,7 +224,7 @@ function getNumberFormatTypeRaw(pattern: string): NumberFormatType {
return NumberFormatType.Accounting;
}
- const type = numfmt.getInfo(pattern).type as FormatType || 'unknown';
+ const type = numfmt.getFormatInfo(pattern).type as FormatType || 'unknown';
return NumberFormatTypeMap[type];
}
diff --git a/packages/engine-formula/src/functions/date/datevalue/index.ts b/packages/engine-formula/src/functions/date/datevalue/index.ts
index e25c1bff1b..ec1a728a92 100644
--- a/packages/engine-formula/src/functions/date/datevalue/index.ts
+++ b/packages/engine-formula/src/functions/date/datevalue/index.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import { excelDateTimeSerial, isDate, parseFormattedValue } from '../../../basics/date';
-import { ErrorType } from '../../../basics/error-type';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { excelDateTimeSerial, isDate, parseFormattedDate, parseFormattedTime } from '../../../basics/date';
+import { ErrorType } from '../../../basics/error-type';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
@@ -41,13 +41,17 @@ export class Datevalue extends BaseFunction {
private _handleSingleObject(dateTextObject: BaseValueObject) {
if (dateTextObject.isString()) {
const value = `${dateTextObject.getValue()}`;
- const parsedDate = parseFormattedValue(value);
+ let parsedDate = parseFormattedDate(value);
+ if (parsedDate === null) {
+ parsedDate = parseFormattedTime(value);
+ }
if (parsedDate) {
let { v, z } = parsedDate;
+ // currently, we the v is a number by numfmt the 3.2
if (z && isDate(z)) {
- if (v instanceof Date) {
- v = excelDateTimeSerial(v);
+ if ((v as any) instanceof Date) {
+ v = excelDateTimeSerial(v as any);
}
return NumberValueObject.create(Math.trunc(+v));
diff --git a/packages/engine-formula/src/functions/date/timevalue/index.ts b/packages/engine-formula/src/functions/date/timevalue/index.ts
index 63f32254cf..a3fca50666 100644
--- a/packages/engine-formula/src/functions/date/timevalue/index.ts
+++ b/packages/engine-formula/src/functions/date/timevalue/index.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { excelDateTimeSerial, isDate, parseFormattedValue } from '../../../basics/date';
import { ErrorType } from '../../../basics/error-type';
import { getFractionalPart } from '../../../engine/utils/math-kit';
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
@@ -47,8 +47,8 @@ export class Timevalue extends BaseFunction {
let { v, z } = parsedTime;
if (z && isDate(z)) {
- if (v instanceof Date) {
- v = excelDateTimeSerial(v);
+ if ((v as any) instanceof Date) {
+ v = excelDateTimeSerial((v as any));
}
return NumberValueObject.create(getFractionalPart(+v));
diff --git a/packages/engine-formula/src/functions/text/dollar/__test__/index.spec.ts b/packages/engine-formula/src/functions/text/dollar/__test__/index.spec.ts
index 642487c225..e36ad877ad 100644
--- a/packages/engine-formula/src/functions/text/dollar/__test__/index.spec.ts
+++ b/packages/engine-formula/src/functions/text/dollar/__test__/index.spec.ts
@@ -32,7 +32,7 @@ describe('Test dollar function', () => {
const number = NumberValueObject.create(1234.567);
const decimals = NullValueObject.create();
const result = testFunction.calculate(number, decimals);
- expect(getObjectValue(result)).toStrictEqual('$1,234.57 ');
+ expect(getObjectValue(result)).toStrictEqual('$1,234.57 ');
});
it('Value is negative', () => {
@@ -46,15 +46,15 @@ describe('Test dollar function', () => {
const number = NumberValueObject.create(1234.567);
const decimals = NumberValueObject.create(-2);
const result = testFunction.calculate(number, decimals);
- expect(getObjectValue(result)).toStrictEqual('$1,200 ');
+ expect(getObjectValue(result)).toStrictEqual('$1,200 ');
const decimals2 = NumberValueObject.create(-4);
const result2 = testFunction.calculate(number, decimals2);
- expect(getObjectValue(result2)).toStrictEqual('$0 ');
+ expect(getObjectValue(result2)).toStrictEqual('$0 ');
const decimals3 = NumberValueObject.create(4);
const result3 = testFunction.calculate(number, decimals3);
- expect(getObjectValue(result3)).toStrictEqual('$1,234.5670 ');
+ expect(getObjectValue(result3)).toStrictEqual('$1,234.5670 ');
const decimals4 = NumberValueObject.create(128);
const result4 = testFunction.calculate(number, decimals4);
@@ -62,7 +62,7 @@ describe('Test dollar function', () => {
const decimals5 = NumberValueObject.create(-10);
const result5 = testFunction.calculate(number, decimals5);
- expect(getObjectValue(result5)).toStrictEqual('$0 ');
+ expect(getObjectValue(result5)).toStrictEqual('$0 ');
});
it('Value is normal string', () => {
@@ -76,7 +76,7 @@ describe('Test dollar function', () => {
const number = BooleanValueObject.create(true);
const decimals = NullValueObject.create();
const result = testFunction.calculate(number, decimals);
- expect(getObjectValue(result)).toStrictEqual('$1.00 ');
+ expect(getObjectValue(result)).toStrictEqual('$1.00 ');
});
it('Value is error', () => {
@@ -107,8 +107,8 @@ describe('Test dollar function', () => {
const decimals = NullValueObject.create();
const result = testFunction.calculate(number, decimals);
expect(getObjectValue(result)).toStrictEqual([
- ['$1.00 ', ErrorType.VALUE, '$1.23 ', '$1.00 ', '$0.00 ', '$0.00 '],
- ['$0.00 ', '$100.00 ', '$2.34 ', ErrorType.VALUE, '($3.00)', ErrorType.NAME],
+ ['$1.00 ', ErrorType.VALUE, '$1.23 ', '$1.00 ', '$0.00 ', '$0.00 '],
+ ['$0.00 ', '$100.00 ', '$2.34 ', ErrorType.VALUE, '($3.00)', ErrorType.NAME],
]);
});
});
diff --git a/packages/sheets-filter-ui/src/worker/generate-filter-values.service.ts b/packages/sheets-filter-ui/src/worker/generate-filter-values.service.ts
index 6b3434ece7..a0ab226fd0 100644
--- a/packages/sheets-filter-ui/src/worker/generate-filter-values.service.ts
+++ b/packages/sheets-filter-ui/src/worker/generate-filter-values.service.ts
@@ -177,7 +177,7 @@ export function getFilterTreeByValueItems(
}
const fmtStr = (cell.value?.v && !cell.value.p) ? styles.get(cell.value?.s)?.n?.pattern : '';
- const isDateValue = fmtStr && numfmt.isDate(fmtStr);
+ const isDateValue = fmtStr && numfmt.getFormatInfo(fmtStr).isDate;
if (fmtStr && isDateValue && canSplitPatternSet.has(fmtStr)) {
// const originValue = numfmt.parseDate(value).v as number;
const originValue = worksheet.getCellRaw(cell.row, cell.col)?.v as number;
diff --git a/packages/sheets-numfmt-ui/src/controllers/menu.ts b/packages/sheets-numfmt-ui/src/controllers/menu.ts
index 54cf9e4dc6..08d7fb549e 100644
--- a/packages/sheets-numfmt-ui/src/controllers/menu.ts
+++ b/packages/sheets-numfmt-ui/src/controllers/menu.ts
@@ -16,7 +16,7 @@
import type { IAccessor } from '@univerjs/core';
import type { IMenuSelectorItem } from '@univerjs/ui';
-import { fromCallback, ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
+import { fromCallback, ICommandService, isPatternEqualWithoutDecimal, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
import { DEFAULT_TEXT_FORMAT_EXCEL, isDefaultFormat } from '@univerjs/engine-numfmt';
import {
RangeProtectionPermissionEditPoint,
@@ -27,7 +27,7 @@ import {
WorksheetEditPermission,
WorksheetSetCellStylePermission,
} from '@univerjs/sheets';
-import { AddDecimalCommand, countryCurrencyMap, isPatternEqualWithoutDecimal, MenuCurrencyService, SetCurrencyCommand, SetPercentCommand, SubtractDecimalCommand } from '@univerjs/sheets-numfmt';
+import { AddDecimalCommand, countryCurrencyMap, MenuCurrencyService, SetCurrencyCommand, SetPercentCommand, SubtractDecimalCommand } from '@univerjs/sheets-numfmt';
import { deriveStateFromActiveSheet$, getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
import { filter, merge, Observable } from 'rxjs';
diff --git a/packages/sheets-numfmt-ui/src/controllers/numfmt.controller.ts b/packages/sheets-numfmt-ui/src/controllers/numfmt.controller.ts
index dfb13abc59..b07f18b792 100644
--- a/packages/sheets-numfmt-ui/src/controllers/numfmt.controller.ts
+++ b/packages/sheets-numfmt-ui/src/controllers/numfmt.controller.ts
@@ -270,7 +270,7 @@ export class SheetNumfmtUIController extends Disposable {
}
const info = getPatternPreviewIgnoreGeneral(this._previewPattern, value as number, this._sheetsNumfmtCellContentController.local);
if (info.color) {
- const color = this._themeService.getColorFromTheme(`${info.color}.500`);
+ const color = this._themeService.getColorFromTheme(`${info.color}.500`) ?? info.color;
return {
...defaultValue,
v: info.result,
diff --git a/packages/sheets-numfmt-ui/src/views/components/Currency.tsx b/packages/sheets-numfmt-ui/src/views/components/Currency.tsx
index f510620d20..aa7090902c 100644
--- a/packages/sheets-numfmt-ui/src/views/components/Currency.tsx
+++ b/packages/sheets-numfmt-ui/src/views/components/Currency.tsx
@@ -16,9 +16,9 @@
import type { FC } from 'react';
import type { IBusinessComponentProps } from './interface';
-import { LocaleService } from '@univerjs/core';
+import { isPatternEqualWithoutDecimal, LocaleService } from '@univerjs/core';
import { InputNumber, Select, SelectList } from '@univerjs/design';
-import { getCurrencyFormatOptions, getCurrencyType, getDecimalFromPattern, isPatternEqualWithoutDecimal, setPatternDecimal } from '@univerjs/sheets-numfmt';
+import { getCurrencyFormatOptions, getCurrencyType, getDecimalFromPattern, setPatternDecimal } from '@univerjs/sheets-numfmt';
import { useDependency } from '@univerjs/ui';
import { useContext, useMemo, useState } from 'react';
import { UserHabitCurrencyContext } from '../../controllers/user-habit.controller';
diff --git a/packages/sheets-numfmt-ui/src/views/components/Date.tsx b/packages/sheets-numfmt-ui/src/views/components/Date.tsx
index 7826dac726..9c46e5eaaf 100644
--- a/packages/sheets-numfmt-ui/src/views/components/Date.tsx
+++ b/packages/sheets-numfmt-ui/src/views/components/Date.tsx
@@ -22,7 +22,7 @@ import { useDependency } from '@univerjs/ui';
import { useMemo, useState } from 'react';
export const isDatePanel = (pattern: string) => {
- const info = numfmt.getInfo(pattern);
+ const info = numfmt.getFormatInfo(pattern);
return (
getDateFormatOptions()
.map((item) => item.value)
diff --git a/packages/sheets-numfmt-ui/src/views/components/ThousandthPercentile.tsx b/packages/sheets-numfmt-ui/src/views/components/ThousandthPercentile.tsx
index b0bd938fe3..d38e047064 100644
--- a/packages/sheets-numfmt-ui/src/views/components/ThousandthPercentile.tsx
+++ b/packages/sheets-numfmt-ui/src/views/components/ThousandthPercentile.tsx
@@ -15,9 +15,9 @@
*/
import type { IBusinessComponentProps } from './interface';
-import { LocaleService } from '@univerjs/core';
+import { isPatternEqualWithoutDecimal, LocaleService } from '@univerjs/core';
import { InputNumber, SelectList } from '@univerjs/design';
-import { getDecimalFromPattern, getNumberFormatOptions, isPatternEqualWithoutDecimal, isPatternHasDecimal, setPatternDecimal } from '@univerjs/sheets-numfmt';
+import { getDecimalFromPattern, getNumberFormatOptions, isPatternHasDecimal, setPatternDecimal } from '@univerjs/sheets-numfmt';
import { useDependency } from '@univerjs/ui';
import { useMemo, useState } from 'react';
diff --git a/packages/sheets-numfmt/src/__tests__/date.test.ts b/packages/sheets-numfmt/src/__tests__/date.test.ts
index a810fb9798..7a4117f7bf 100644
--- a/packages/sheets-numfmt/src/__tests__/date.test.ts
+++ b/packages/sheets-numfmt/src/__tests__/date.test.ts
@@ -20,12 +20,12 @@ 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('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
index c3a72f35b0..981d104288 100644
--- a/packages/sheets-numfmt/src/__tests__/utils.test.ts
+++ b/packages/sheets-numfmt/src/__tests__/utils.test.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { cellToRange } from '@univerjs/core';
+import { cellToRange, isPatternEqualWithoutDecimal } from '@univerjs/core';
import { RemoveNumfmtMutation, SetNumfmtMutation } from '@univerjs/sheets';
import { describe, expect, it } from 'vitest';
@@ -23,7 +23,6 @@ import { getCurrencyType } from '../utils/currency';
import {
getDecimalFromPattern,
getDecimalString,
- isPatternEqualWithoutDecimal,
setPatternDecimal,
} from '../utils/decimal';
import { mergeNumfmtMutations } from '../utils/mutation';
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 9fd61082fe..9f2055141a 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts
@@ -171,7 +171,7 @@ export class SheetsNumfmtCellContentController extends Disposable {
const res: ICellDataForSheetInterceptor = { v: numfmtRes, t: CellValueType.NUMBER };
if (info.color) {
- const color = this._themeService.getColorFromTheme(`${info.color}.500`);
+ const color = this._themeService.getColorFromTheme(`${info.color}.500`) ?? info.color;
if (color) {
res.interceptorStyle = { cl: { rgb: color } };
diff --git a/packages/sheets-numfmt/src/index.ts b/packages/sheets-numfmt/src/index.ts
index c8dd3c7d64..6a92443fdb 100644
--- a/packages/sheets-numfmt/src/index.ts
+++ b/packages/sheets-numfmt/src/index.ts
@@ -19,7 +19,7 @@ export { CURRENCYFORMAT, DATEFMTLISG, NUMBERFORMAT } from './base/const/formatde
export { UniverSheetsNumfmtPlugin } from './plugin';
export { MenuCurrencyService } from './service/menu.currency.service';
export { getPatternPreview, getPatternPreviewIgnoreGeneral, getPatternType } from './utils/pattern';
-export { getDecimalFromPattern, getDecimalString, isPatternEqualWithoutDecimal, isPatternHasDecimal, setPatternDecimal } from './utils/decimal';
+export { getDecimalFromPattern, getDecimalString, isPatternHasDecimal, setPatternDecimal } from './utils/decimal';
export { getCurrencyType } from './utils/currency';
export { currencySymbols } from './base/const/currency-symbols';
export { SheetsNumfmtCellContentController } from './controllers/numfmt-cell-content.controller';
diff --git a/packages/sheets-numfmt/src/utils/decimal.ts b/packages/sheets-numfmt/src/utils/decimal.ts
index 04f0427dfd..a7493226c5 100644
--- a/packages/sheets-numfmt/src/utils/decimal.ts
+++ b/packages/sheets-numfmt/src/utils/decimal.ts
@@ -24,41 +24,10 @@ export const getDecimalFromPattern = (pattern: string, defaultValue: number = 0)
return defaultValue;
}
- const info = numfmt.getInfo(pattern);
+ const info = numfmt.getFormatInfo(pattern);
return info.maxDecimals ?? defaultValue;
};
-/**
- * Determines whether two pattern are equal, excluding differences in decimal places
- */
-export const isPatternEqualWithoutDecimal = (patternA: string, patternB: string) => {
- if ((patternA && !patternB) || (!patternA && patternB)) {
- return false;
- }
- const getString = (tokens: unknown[]) =>
- (tokens as Array<{ type: string; num?: string; value?: string }>).reduce(
- (pre, cur) => {
- if (pre.isEnd) {
- return pre;
- }
- const str = cur.value || cur.num;
- if (cur.type === 'point') {
- pre.isEnd = true;
- return pre;
- }
- return { ...pre, result: pre.result + str };
- },
- { isEnd: false, result: '' }
- ).result;
- const partitionsA = numfmt.getInfo(patternA)._partitions;
- const partitionsB = numfmt.getInfo(patternB)._partitions;
- const A1 = getString(partitionsA[0].tokens);
- const B1 = getString(partitionsB[0].tokens);
- const A2 = getString(partitionsA[1].tokens);
- const B2 = getString(partitionsB[1].tokens);
- return A1 === B1 && A2 === B2 && partitionsA[1].color === partitionsB[1].color;
-};
-
export const getDecimalString = (length: number) =>
new Array(Math.min(Math.max(0, Number(length)), 30)).fill(0).join('');
diff --git a/packages/sheets-numfmt/src/utils/pattern.ts b/packages/sheets-numfmt/src/utils/pattern.ts
index ec14950e3d..d33882fe7f 100644
--- a/packages/sheets-numfmt/src/utils/pattern.ts
+++ b/packages/sheets-numfmt/src/utils/pattern.ts
@@ -19,21 +19,22 @@ import type { FormatType } from '@univerjs/sheets';
import { numfmt } from '@univerjs/core';
import { stripErrorMargin } from '@univerjs/engine-formula';
-export const getPatternType = (pattern: string): FormatType => numfmt.getInfo(pattern).type || 'unknown';
+export const getPatternType = (pattern: string): FormatType => numfmt.getFormatInfo(pattern).type || 'unknown';
interface IPatternPreview {
result: string;
color?: string;
}
export const getPatternPreview = (pattern: string, value: number, locale: INumfmtLocalTag = 'en'): IPatternPreview => {
- const info = numfmt.getInfo(pattern);
- const negInfo = info._partitions[1];
-
+ // in the source code of numfmt, the formatColor function will read the the partitions[3]
+ const color = String(numfmt.formatColor(pattern, value));
const result = numfmt.format(pattern, value, { locale, throws: false });
if (value < 0) {
+ // pay attention, controllers/numfmt.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: negInfo.color,
+ color,
};
}
return {
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index 1ec5254b1d..4894f453e0 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -80,7 +80,7 @@ class CalculateValueSet {
const { pattern } = style.n;
if (!patternInfoRecord[pattern]) {
- patternInfoRecord[pattern] = numfmt.getInfo(pattern);
+ patternInfoRecord[pattern] = numfmt.getFormatInfo(pattern);
}
const formatInfo = patternInfoRecord[pattern];
diff --git a/packages/sheets-ui/src/controllers/utils/char-tools.ts b/packages/sheets-ui/src/controllers/utils/char-tools.ts
index 69fa951f96..2261693333 100644
--- a/packages/sheets-ui/src/controllers/utils/char-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/char-tools.ts
@@ -169,7 +169,7 @@ function normalizeFormulaString(str: string, normalStr: string, lexerTreeBuilder
}
// Entering =.07/0.1 in a cell will automatically convert to =0.07/0.1
// Entering =1.0+2.00 in a cell will automatically convert to =1+2
- else if (typeof parsedValue.v === 'number' && (parsedValue.z === undefined || !numfmt.isDate(parsedValue.z))) {
+ else if (typeof parsedValue.v === 'number' && (parsedValue.z === undefined || !numfmt.getFormatInfo(parsedValue.z).isDate)) {
const v = `${parsedValue.v}`;
const startIndex = node.startIndex + totalOffset + 1;
const endIndex = node.endIndex + totalOffset + 2;
diff --git a/packages/sheets-ui/src/services/auto-fill/rules.ts b/packages/sheets-ui/src/services/auto-fill/rules.ts
index 4cd07fc59a..af962aca62 100644
--- a/packages/sheets-ui/src/services/auto-fill/rules.ts
+++ b/packages/sheets-ui/src/services/auto-fill/rules.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
-import { CellValueType, Direction, IUniverInstanceService, numfmt } from '@univerjs/core';
import type { Workbook } from '@univerjs/core';
+import type { IAutoFillRule } from './type';
+import { CellValueType, Direction, IUniverInstanceService, numfmt } from '@univerjs/core';
import {
chineseToNumber,
fillChnNumber,
@@ -34,7 +35,6 @@ import {
matchExtendNumber,
} from './tools';
import { APPLY_TYPE, DATA_TYPE } from './type';
-import type { IAutoFillRule } from './type';
export const dateRule: IAutoFillRule = {
type: DATA_TYPE.DATE,
@@ -51,9 +51,9 @@ export const dateRule: IAutoFillRule = {
const style = workbook.getStyles().get(cellData.s);
const pattern = style?.n?.pattern;
if (pattern) {
- return numfmt.getInfo(pattern).isDate;
+ return numfmt.getFormatInfo(pattern).isDate;
}
- } else if (cellData.s.n && numfmt.getInfo(cellData.s.n.pattern).isDate) {
+ } else if (cellData.s.n && numfmt.getFormatInfo(cellData.s.n.pattern).isDate) {
return true;
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d70ef34658..389b06d3d9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1122,8 +1122,8 @@ importers:
specifier: 5.1.5
version: 5.1.5
numfmt:
- specifier: ^2.5.2
- version: 2.5.2
+ specifier: ^3.2.2
+ version: 3.2.2
ot-json1:
specifier: ^1.0.2
version: 1.0.2
@@ -1765,9 +1765,6 @@ importers:
decimal.js:
specifier: ^10.5.0
version: 10.5.0
- numfmt:
- specifier: ^2.5.2
- version: 2.5.2
devDependencies:
'@univerjs-infra/shared':
specifier: workspace:*
@@ -9268,8 +9265,8 @@ packages:
resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
- resolution: {integrity: sha512-VXrB2bpU9Xa0oCHq8IsqE2CcUx5OLupLC3oryFT4DB9e/xe+OnUzBndhXfNHUzxFE4DYI3Sx4OtzS1Sdaf7tEw==}
+ resolution: {integrity: sha512-vAdkKhb+8D1ebZcPx5TdUmPnzNYhzKGA+oVy+BoENFydDWljaZDci0wWWjNfvOUcXCdgKhwS08ErdTe+VzuQ+w==}
resolution: {integrity: sha512-/ieB+mDe4MrrKMT8z+mQL8klXydZWGR5Dowt4RAGKbJ3kIGEx3X4ljUo+6V73IXtUPWgfOlU5B9MlGxFO5T+cA==}
@@ -17721,7 +17718,7 @@ snapshots:
dependencies:
boolbase: 1.0.0