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): support numfmt (#403)
Gpound.liu8bca8d52d99b
diff --git a/.github/workflows/preview-build.yml b/.github/workflows/preview-build.ymlindex 69e68222b9..8b816f4b05 100644--- a/.github/workflows/preview-build.yml+++ b/.github/workflows/preview-build.yml@@ -15,8 +15,6 @@ jobs:steps:- name: Checkoutuses: actions/checkout@v3- with:- ref: ${{ steps.ref.outputs.ref }}- name: Install Node.jsuses: actions/setup-node@v3diff --git a/.github/workflows/preview-deploy.yml b/.github/workflows/preview-deploy.ymlindex 903ea9452a..7f40eb865e 100644--- a/.github/workflows/preview-deploy.yml+++ b/.github/workflows/preview-deploy.yml@@ -3,8 +3,7 @@ name: 📤 Preview Deployon:workflow_run:workflows: ['📦 Preview Build']- types:- - completed+ types: [completed]permissions:contents: read@@ -12,7 +11,7 @@ permissions:jobs:build:- if: github.repository == 'dream-num/univer'+ if: ${{ github.event.workflow_run.conclusion == 'success' }}runs-on: ubuntu-latestenv:diff --git a/.storybook/main.ts b/.storybook/main.tsindex a1bf437e84..687119f0d2 100644--- a/.storybook/main.ts+++ b/.storybook/main.ts@@ -21,6 +21,11 @@ const config: StorybookConfig = {files: '*.stories.@(js|jsx|mjs|ts|tsx)',titlePrefix: 'Base UI'},+ {+ directory: '../packages/sheets-plugin-numfmt/src/**',+ files: '*.stories.@(js|jsx|mjs|ts|tsx)',+ titlePrefix: 'Numfmt'+ },],addons: [getAbsolutePath('@storybook/addon-links'),diff --git a/examples/univer-sheet-ts/src/locales.ts b/examples/univer-sheet-ts/src/locales.tsindex d89d89500e..8e4328d373 100644--- a/examples/univer-sheet-ts/src/locales.ts+++ b/examples/univer-sheet-ts/src/locales.ts@@ -4,7 +4,6 @@ import BaseUiZhCN from '@univerjs/base-ui/locale/zh-CN';import DeisgnZH from '@univerjs/design/locale/zh-CN';import FindPluginZhCN from '@univerjs/sheets-plugin-find/locale/zh-CN';import ImportXlsxPluginZhCN from '@univerjs/sheets-plugin-import-xlsx/locale/zh-CN';-import NumberfmtPluginZhCN from '@univerjs/sheets-plugin-numfmt/locale/zh-CN';import DocUIPluginZhCN from '@univerjs/ui-plugin-docs/locale/zh-CN';import SheetUIPluginZhCN from '@univerjs/ui-plugin-sheets/locale/zh-CN';@@ -16,7 +15,6 @@ export const locales = {...SheetPluginZhCN,...FindPluginZhCN,...ImportXlsxPluginZhCN,- ...NumberfmtPluginZhCN,...DocUIPluginZhCN,...SheetUIPluginZhCN,...SheetDebuggerPluginZhCN,diff --git a/examples/univer-sheet-ts/src/sheets-plugin-debugger/commands/operations/numfmt.operations.ts b/examples/univer-sheet-ts/src/sheets-plugin-debugger/commands/operations/numfmt.operations.tsnew file mode 100644index 0000000000..99767f8f42--- /dev/null+++ b/examples/univer-sheet-ts/src/sheets-plugin-debugger/commands/operations/numfmt.operations.ts@@ -0,0 +1,20 @@+import { CommandType, ICommand, ICommandService } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++export interface NumfmtOperationCommandParams {+ value: 'close' | 'open';+}++export const NumfmtOperation: ICommand = {+ id: 'debugger.operation.numfmt',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor, params: NumfmtOperationCommandParams) => {+ const confirmService = accessor.get(ICommandService);+ if (params.value === 'open') {+ confirmService.executeCommand('sheet.operation.open.numfmt.panel');+ } else {+ confirmService.executeCommand('sheet.operation.close.numfmt.panel');+ }+ return true;+ },+};diff --git a/examples/univer-sheet-ts/src/sheets-plugin-debugger/controllers/debugger.controller.ts b/examples/univer-sheet-ts/src/sheets-plugin-debugger/controllers/debugger.controller.tsindex 7733d4b141..5797da5b87 100644--- a/examples/univer-sheet-ts/src/sheets-plugin-debugger/controllers/debugger.controller.ts+++ b/examples/univer-sheet-ts/src/sheets-plugin-debugger/controllers/debugger.controller.ts@@ -7,6 +7,7 @@ import { DialogOperation } from '../commands/operations/dialog.operation';import { LocaleOperation } from '../commands/operations/locale.operation';import { MessageOperation } from '../commands/operations/message.operation';import { NotificationOperation } from '../commands/operations/notification.operation';+import { NumfmtOperation } from '../commands/operations/numfmt.operations';import { SetEditable } from '../commands/operations/set.editable.operation';import { SidebarOperation } from '../commands/operations/sidebar.operation';import { ThemeOperation } from '../commands/operations/theme.operation';@@ -16,6 +17,7 @@ import {LocaleMenuItemFactory,MessageMenuItemFactory,NotificationMenuItemFactory,+ NumfmtMenuItemFactory,SetEditableMenuItemFactory,SidebarMenuItemFactory,ThemeMenuItemFactory,@@ -39,6 +41,7 @@ export class DebuggerController extends Disposable {MessageOperation,SidebarOperation,SetEditable,+ NumfmtOperation,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}@@ -48,7 +51,7 @@ export class DebuggerController extends Disposable {ThemeMenuItemFactory,NotificationMenuItemFactory,MessageMenuItemFactory,-+ NumfmtMenuItemFactory,DialogMenuItemFactory,ConfirmMenuItemFactory,SidebarMenuItemFactory,diff --git a/examples/univer-sheet-ts/src/sheets-plugin-debugger/controllers/menu.ts b/examples/univer-sheet-ts/src/sheets-plugin-debugger/controllers/menu.tsindex a617719bc4..96e787cb32 100644--- a/examples/univer-sheet-ts/src/sheets-plugin-debugger/controllers/menu.ts+++ b/examples/univer-sheet-ts/src/sheets-plugin-debugger/controllers/menu.ts@@ -8,6 +8,7 @@ import { DialogOperation } from '../commands/operations/dialog.operation';import { LocaleOperation } from '../commands/operations/locale.operation';import { MessageOperation } from '../commands/operations/message.operation';import { NotificationOperation } from '../commands/operations/notification.operation';+import { NumfmtOperation } from '../commands/operations/numfmt.operations';import { SetEditable } from '../commands/operations/set.editable.operation';import { SidebarOperation } from '../commands/operations/sidebar.operation';import { ThemeOperation } from '../commands/operations/theme.operation';@@ -167,3 +168,23 @@ export function SetEditableMenuItemFactory(accessor: IAccessor): IMenuSelectorIt],};}++export function NumfmtMenuItemFactory(accessor: IAccessor): IMenuSelectorItem {+ return {+ id: NumfmtOperation.id,+ title: 'Numfmt',+ tooltip: 'Numfmt',+ type: MenuItemType.SELECTOR,+ positions: [MenuPosition.TOOLBAR_OTHERS],+ selections: [+ {+ label: 'Open numfmt',+ value: 'open',+ },+ {+ label: 'Close numfmt',+ value: 'close',+ },+ ],+ };+}diff --git a/packages/base-numfmt-engine/package.json b/packages/base-numfmt-engine/package.jsonindex f9b82fe454..c13aede4dd 100644--- a/packages/base-numfmt-engine/package.json+++ b/packages/base-numfmt-engine/package.json@@ -43,7 +43,8 @@"esbuild": "node ./esbuild.config.mjs && tsc -p tsconfig.esbuild.json"},"dependencies": {- "@univerjs/core": "workspace:*"+ "@univerjs/core": "workspace:*",+ "numfmt": "^2.5.2"},"devDependencies": {"@vitest/coverage-istanbul": "^0.34.6",diff --git a/packages/base-numfmt-engine/src/core/clamp.ts b/packages/base-numfmt-engine/src/core/clamp.tsdeleted file mode 100644index 120a798733..0000000000--- a/packages/base-numfmt-engine/src/core/clamp.ts+++ /dev/null@@ -1,8 +0,0 @@-export function clamp(number: number): number {- if (number === 0) {- return number;- }- const d = Math.ceil(Math.log10(number < 0 ? -number : number));- const mag = 10 ** (16 - Math.floor(d));- return Math.round(number * mag) / mag;-}diff --git a/packages/base-numfmt-engine/src/core/code-to-locale.ts b/packages/base-numfmt-engine/src/core/code-to-locale.tsdeleted file mode 100644index 2e09a52e40..0000000000--- a/packages/base-numfmt-engine/src/core/code-to-locale.ts+++ /dev/null@@ -1,188 +0,0 @@-export const codeToLocale = {- 1078: 'af', // Afrikaans- 1052: 'sq', // Albanian- 1118: 'am', // Amharic- 5121: 'ar_DZ', // Arabic - Algeria- 15361: 'ar_BH', // Arabic - Bahrain- 3073: 'ar_EG', // Arabic - Egypt- 2049: 'ar_IQ', // Arabic - Iraq- 11265: 'ar_JO', // Arabic - Jordan- 13313: 'ar_KW', // Arabic - Kuwait- 12289: 'ar_LB', // Arabic - Lebanon- 4097: 'ar_LY', // Arabic - Libya- 6145: 'ar_MA', // Arabic - Morocco- 8193: 'ar_OM', // Arabic - Oman- 16385: 'ar_QA', // Arabic - Qatar- 1025: 'ar_SA', // Arabic - Saudi Arabia- 10241: 'ar_SY', // Arabic - Syria- 7169: 'ar_TN', // Arabic - Tunisia- 14337: 'ar_AE', // Arabic - United Arab Emirates- 9217: 'ar_YE', // Arabic - Yemen- 1067: 'hy', // Armenian- 1101: 'as', // Assamese- 2092: 'az_AZ', // Azeri - Cyrillic- 1068: 'az_AZ', // Azeri - Latin- 1069: 'eu', // Basque- 1059: 'be', // Belarusian- 2117: 'bn', // Bengali - Bangladesh- 1093: 'bn_IN', // Bengali - India- 5146: 'bs', // Bosnian- 1026: 'bg', // Bulgarian- 1109: 'my', // Burmese- 1027: 'ca', // Catalan- 2052: 'zh_CN', // Chinese - China- 3076: 'zh_HK', // Chinese - Hong Kong SAR- 5124: 'zh_MO', // Chinese - Macau SAR- 4100: 'zh_SG', // Chinese - Singapore- 1028: 'zh_TW', // Chinese - Taiwan- 1050: 'hr', // Croatian- 1029: 'cs', // Czech- 1030: 'da', // Danish- 1125: 'dv', // Divehi; Dhivehi; Maldivian- 2067: 'nl_BE', // Dutch - Belgium- 1043: 'nl_NL', // Dutch - Netherlands- 1126: 'bin', // Edo- 3081: 'en_AU', // English - Australia- 10249: 'en_BZ', // English - Belize- 4105: 'en_CA', // English - Canada- 9225: 'en_CB', // English - Caribbean- 2057: 'en_GB', // English - Great Britain- 16393: 'en_IN', // English - India- 6153: 'en_IE', // English - Ireland- 8201: 'en_JM', // English - Jamaica- 5129: 'en_NZ', // English - New Zealand- 13321: 'en_PH', // English - Phillippines- 7177: 'en_ZA', // English - Southern Africa- 11273: 'en_TT', // English - Trinidad- 1033: 'en_US', // English - United States- 12297: 'en_ZW', // English - Zimbabwe- 1061: 'et', // Estonian- 1071: 'mk', // FYRO Macedonia- 1080: 'fo', // Faroese- 1065: 'fa', // Farsi - Persian- 1124: 'fil', // Filipino- 1035: 'fi', // Finnish- 2060: 'fr_BE', // French - Belgium- 11276: 'fr_CM', // French - Cameroon- 3084: 'fr_CA', // French - Canada- 9228: 'fr_CG', // French - Congo- 12300: 'fr_CI', // French - Cote d'Ivoire- 1036: 'fr_FR', // French - France- 5132: 'fr_LU', // French - Luxembourg- 13324: 'fr_ML', // French - Mali- 6156: 'fr_MC', // French - Monaco- 14348: 'fr_MA', // French - Morocco- 10252: 'fr_SN', // French - Senegal- 4108: 'fr_CH', // French - Switzerland- 7180: 'fr', // French - West Indies- 1122: 'fy_NL', // Frisian - Netherlands- 2108: 'gd_IE', // Gaelic - Ireland- 1084: 'gd', // Gaelic - Scotland- 1110: 'gl', // Galician- 1079: 'ka', // Georgian- 3079: 'de_AT', // German - Austria- 1031: 'de_DE', // German - Germany- 5127: 'de_LI', // German - Liechtenstein- 4103: 'de_LU', // German - Luxembourg- 2055: 'de_CH', // German - Switzerland- 1032: 'el', // Greek- 1140: 'gn', // Guarani - Paraguay- 1095: 'gu', // Gujarati- 1279: 'en', // HID (Human Interface Device)- 1037: 'he', // Hebrew- 1081: 'hi', // Hindi- 1038: 'hu', // Hungarian- 1039: 'is', // Icelandic- 1136: 'ig_NG', // Igbo - Nigeria- 1057: 'id', // Indonesian- 1040: 'it_IT', // Italian - Italy- 2064: 'it_CH', // Italian - Switzerland- 1041: 'ja', // Japanese- 1099: 'kn', // Kannada- 1120: 'ks', // Kashmiri- 1087: 'kk', // Kazakh- 1107: 'km', // Khmer- 1111: 'kok', // Konkani- 1042: 'ko', // Korean- 1088: 'ky', // Kyrgyz - Cyrillic- 1108: 'lo', // Lao- 1142: 'la', // Latin- 1062: 'lv', // Latvian- 1063: 'lt', // Lithuanian- 2110: 'ms_BN', // Malay - Brunei- 1086: 'ms_MY', // Malay - Malaysia- 1100: 'ml', // Malayalam- 1082: 'mt', // Maltese- 1112: 'mni', // Manipuri- 1153: 'mi', // Maori- 1102: 'mr', // Marathi- 1104: 'mn', // Mongolian- 2128: 'mn', // Mongolian- 1121: 'ne', // Nepali- 1044: 'no_NO', // Norwegian - Bokml- 2068: 'no_NO', // Norwegian - Nynorsk- 1096: 'or', // Oriya- 1045: 'pl', // Polish- 1046: 'pt_BR', // Portuguese - Brazil- 2070: 'pt_PT', // Portuguese - Portugal- 1094: 'pa', // Punjabi- 1047: 'rm', // Raeto-Romance- 2072: 'ro_MO', // Romanian - Moldova- 1048: 'ro_RO', // Romanian - Romania- 1049: 'ru', // Russian- 2073: 'ru_MO', // Russian - Moldova- 1083: 'se', // Sami Lappish- 1103: 'sa', // Sanskrit- 3098: 'sr_SP', // Serbian - Cyrillic- 2074: 'sr_SP', // Serbian - Latin- 1072: 'st', // Sesotho (Sutu)- 1074: 'tn', // Setsuana- 1113: 'sd', // Sindhi- 1115: 'si', // Sinhala; Sinhalese- 1051: 'sk', // Slovak- 1060: 'sl', // Slovenian- 1143: 'so', // Somali- 1070: 'sb', // Sorbian- 11274: 'es_AR', // Spanish - Argentina- 16394: 'es_BO', // Spanish - Bolivia- 13322: 'es_CL', // Spanish - Chile- 9226: 'es_CO', // Spanish - Colombia- 5130: 'es_CR', // Spanish - Costa Rica- 7178: 'es_DO', // Spanish - Dominican Republic- 12298: 'es_EC', // Spanish - Ecuador- 17418: 'es_SV', // Spanish - El Salvador- 4106: 'es_GT', // Spanish - Guatemala- 18442: 'es_HN', // Spanish - Honduras- 2058: 'es_MX', // Spanish - Mexico- 19466: 'es_NI', // Spanish - Nicaragua- 6154: 'es_PA', // Spanish - Panama- 15370: 'es_PY', // Spanish - Paraguay- 10250: 'es_PE', // Spanish - Peru- 20490: 'es_PR', // Spanish - Puerto Rico- 1034: 'es_ES', // Spanish - Spain (Traditional)- 14346: 'es_UY', // Spanish - Uruguay- 8202: 'es_VE', // Spanish - Venezuela- 1089: 'sw', // Swahili- 2077: 'sv_FI', // Swedish - Finland- 1053: 'sv_SE', // Swedish - Sweden- 1114: 'syc', // Syriac- 1064: 'tg', // Tajik- 1097: 'ta', // Tamil- 1092: 'tt', // Tatar- 1098: 'te', // Telugu- 1054: 'th', // Thai- 1105: 'bo', // Tibetan- 1073: 'ts', // Tsonga- 1055: 'tr', // Turkish- 1090: 'tk', // Turkmen- 1058: 'uk', // Ukrainian- 1056: 'ur', // Urdu- 2115: 'uz_UZ', // Uzbek - Cyrillic- 1091: 'uz_UZ', // Uzbek - Latin- 1075: 've', // Venda- 1066: 'vi', // Vietnamese- 1106: 'cy', // Welsh- 1076: 'xh', // Xhosa- 1085: 'yi', // Yiddish- 1077: 'zu', // Zulu-};diff --git a/packages/base-numfmt-engine/src/core/constants.ts b/packages/base-numfmt-engine/src/core/constants.tsdeleted file mode 100644index d240c0ad5e..0000000000--- a/packages/base-numfmt-engine/src/core/constants.ts+++ /dev/null@@ -1,86 +0,0 @@-export const u_YEAR: number = 2;-export const u_MONTH: number = 2 ** 2;-export const u_DAY: number = 2 ** 3;-export const u_HOUR: number = 2 ** 4;-export const u_MIN: number = 2 ** 5;-export const u_SEC: number = 2 ** 6;-export const u_DSEC: number = 2 ** 7;-export const u_CSEC: number = 2 ** 8;-export const u_MSEC: number = 2 ** 9;--export const MIN_S_DATE: number = 0;-export const MAX_S_DATE: number = 2958466;--export const MIN_L_DATE: number = -694324;-export const MAX_L_DATE: number = 35830291;--export const EPOCH_1904: number = -1;-export const EPOCH_1900: number = 1;-export const EPOCH_1317: number = 6;--export const _numchars: { [key: string]: string } = {- '#': '',- '0': '0',- '?': '\u00a0',-};--export const _sp_chars: { [key: string]: string } = {- '@': 'text',- '-': 'minus',- '+': 'plus',-};--export const indexColors: string[] = [- '#000',- '#FFF',- '#F00',- '#0F0',- '#00F',- '#FF0',- '#F0F',- '#0FF',- '#000',- '#FFF',- '#F00',- '#0F0',- '#00F',- '#FF0',- '#F0F',- '#0FF',- '#800',- '#080',- '#008',- '#880',- '#808',- '#088',- '#CCC',- '#888',- '#99F',- '#936',- '#FFC',- '#CFF',- '#606',- '#F88',- '#06C',- '#CCF',- '#008',- '#F0F',- '#FF0',- '#0FF',- '#808',- '#800',- '#088',- '#00F',- '#0CF',- '#CFF',- '#CFC',- '#FF9',- '#9CF',- '#F9C',- '#C9F',- '#FC9',- '#36F',- '#3CC',- '#9C0',- '#FC0',-];diff --git a/packages/base-numfmt-engine/src/core/dec2frac.ts b/packages/base-numfmt-engine/src/core/dec2frac.tsdeleted file mode 100644index 114571f614..0000000000--- a/packages/base-numfmt-engine/src/core/dec2frac.ts+++ /dev/null@@ -1,40 +0,0 @@-const PRECISION: number = 1e-10;--export function dec2frac(val: number, maxdigits_num: number, maxdigits_de: number): number[] {- const sign: number = val < 0 ? -1 : 1;- const maxdigits_n: number = 10 ** (maxdigits_num || 2);- const maxdigits_d: number = 10 ** (maxdigits_de || 2);-- let z: number = Math.abs(val);- let last_d: number = 0;- let last_n: number = 0;- let curr_n: number = 0;- let curr_d: number = 1;- let tmp: number;- let r: number[];-- val = z;- if (val % 1 === 0) {- // handles exact integers including 0- r = [val * sign, 1];- } else if (val < 1e-19) {- r = [sign, 1e19];- } else if (val > 1e19) {- r = [1e19 * sign, 1];- } else {- do {- z = 1 / (z - Math.floor(z));- tmp = curr_d;- curr_d = curr_d * Math.floor(z) + last_d;- last_d = tmp;- last_n = curr_n;- // round- curr_n = Math.floor(val * curr_d + 0.5);- if (curr_n >= maxdigits_n || curr_d >= maxdigits_d) {- return [sign * last_n, last_d];- }- } while (Math.abs(val - curr_n / curr_d) >= PRECISION && z !== Math.floor(z));- r = [sign * curr_n, curr_d];- }- return r;-}diff --git a/packages/base-numfmt-engine/src/core/format-number.ts b/packages/base-numfmt-engine/src/core/format-number.tsdeleted file mode 100644index 2d09a71b6e..0000000000--- a/packages/base-numfmt-engine/src/core/format-number.ts+++ /dev/null@@ -1,127 +0,0 @@-import { defaultLocale, getLocale } from './locale';-import { OptionsData } from './options';-import { parsePart, PartType } from './parse-part';-import { runPart } from './run-part';--const default_text = parsePart('@');-const default_color = 'black';--function getPart(value: number, parts: PartType[]): PartType | undefined {- for (let pi = 0; pi < 3; pi++) {- const part = parts[pi];- if (part) {- let cond;- if (part.condition) {- const operator = part.condition[0];- const operand = part.condition[1];- if (operator === '=') {- cond = value === operand;- } else if (operator === '>') {- cond = value > operand;- } else if (operator === '<') {- cond = value < operand;- } else if (operator === '>=') {- cond = value >= operand;- } else if (operator === '<=') {- cond = value <= operand;- } else if (operator === '<>') {- cond = value !== operand;- }- } else {- cond = true;- }- if (cond) {- return part;- }- }- }-}--/**- * 颜色类型- * @param value- * @param parts- */-export function color(value: number, parts: PartType[]): string {- if (typeof value !== 'number' || !isFinite(value)) {- const nan_color = parts[3] ? parts[3].color : default_text.color;- return nan_color || default_color;- }- const part = getPart(value, parts);- return part ? part.color || default_color : default_color;-}--/**- * 数字格式化- * @param value- * @param parts- * @param opts- */-export function formatNumber(value: string | number, parts: PartType[], opts: OptionsData): string {- const l10n = getLocale(opts.locale as any);- // not a number?- const text_part = parts[3] ? parts[3] : default_text;- if (typeof value === 'boolean') {- value = value ? 'TRUE' : 'FALSE';- }- if (value == null) {- return '';- }- // FIXME Both runPart and isFinite require Number type- if (typeof value === 'number') {- return runPart(value, text_part, opts, l10n);- }- // guard against non-finite numbers:- if (!isFinite(Number(value))) {- const loc: any = l10n || defaultLocale;- if (isNaN(Number(value))) {- return loc.nan;- }- return (Number(value) < 0 ? loc.negative : '') + loc.infinity;- }- // find and run the pattern part that applies to this number- const part = getPart(Number(value), parts);- return part ? runPart(Number(value), part, opts, l10n) : '';-}--/**- * 日期检查- * @param partitions- */-export function isDate(partitions: PartType[]): boolean {- return !!(- (partitions[0] && partitions[0].date) ||- (partitions[1] && partitions[1].date) ||- (partitions[2] && partitions[2].date) ||- (partitions[3] && partitions[3].date)- );-}--/**- * 文本检查- * @param partitions- */-export function isText(partitions: PartType[]): boolean {- const [part1, part2, part3, part4] = partitions;- return !!(- (!part1 || part1.generated) &&- (!part2 || part2.generated) &&- (!part3 || part3.generated) &&- part4 &&- part4.text &&- !part4.generated- );-}--/**- *- * @param partitions- */-export function isPercent(partitions: PartType[]): boolean {- return !!(- (partitions[0] && partitions[0].percent) ||- (partitions[1] && partitions[1].percent) ||- (partitions[2] && partitions[2].percent) ||- (partitions[3] && partitions[3].percent)- );-}diff --git a/packages/base-numfmt-engine/src/core/general.ts b/packages/base-numfmt-engine/src/core/general.tsdeleted file mode 100644index a27d508ab7..0000000000--- a/packages/base-numfmt-engine/src/core/general.ts+++ /dev/null@@ -1,97 +0,0 @@-import { LocaleData } from './locale';-import { numdec } from './numdec';-import { PartType } from './parse-part';-import { round } from './round';--const fixLocale = (s: string, l10n: any) => s.replace(/\./, l10n.decimal);--/**- *- * @param ret- * @param part- * @param value- * @param l10n- */-export function general(ret: any[], part: PartType, value: number, l10n: LocaleData) {- const int = value | 0;-- // sign is emitted if there is no condition or- // if condition operator is one of [ '<>', '>=', '>' ]- const showSign =- value < 0 &&- (!part.condition || part.condition[0] === '<>' || part.condition[0] === '>=' || part.condition[0] === '>');- if (typeof value === 'string') {- // special case- // [<-25]General;[>25]General;General;General- ret.push(value);- } else if (value === int) {- if (showSign) {- ret.push(l10n.negative);- }- ret.push(Math.abs(int));- } else {- if (showSign) {- ret.push(l10n.negative);- }- let exp = 0;- const v = Math.abs(value);-- // FIXME: it is best if numdec returns all of these- if (v) {- exp = Math.floor(Math.log10(v));- }- let n = exp < 0 ? v * 10 ** -exp : v / 10 ** exp;- if (n === 10) {- n = 1;- exp++;- }-- // The application shall attempt to display the full number- // up to 11 digits (inc. decimal point).- const num_dig = numdec(v);-- const getExp = () => {- const x = Math.abs(exp);- let m;- if (n === 1) {- m = n;- } else {- m = round(n, 5);- }- ret.push(- fixLocale(`${m}`, l10n),- l10n.exponent,- exp < 0 ? l10n.negative : l10n.positive,- x < 10 ? '0' : '',- x- );- };-- if (exp >= -4 && exp <= -1) {- const o = v.toPrecision(10 + exp).replace(/0+$/, '');- ret.push(fixLocale(o, l10n));- } else if (exp === 10) {- const o = v.toFixed(10).slice(0, 12).replace(/\.$/, '');- ret.push(fixLocale(o, l10n));- } else if (Math.abs(exp) <= 9) {- const w = 11;- if (num_dig.total <= w) {- const o = round(v, 9).toFixed(num_dig.frac);- ret.push(fixLocale(o, l10n));- } else if (exp === 9) {- ret.push(Math.floor(v));- } else if (exp >= 0 && exp < 9) {- ret.push(round(v, 9 - exp));- } else {- getExp();- }- } else if (num_dig.total >= 12) {- getExp();- } else if (Math.floor(v) === v) {- ret.push(Math.floor(v));- } else {- ret.push(fixLocale(round(v, 9).toFixed(num_dig.frac), l10n));- }- }- return ret;-}diff --git a/packages/base-numfmt-engine/src/core/locale.ts b/packages/base-numfmt-engine/src/core/locale.tsdeleted file mode 100644index 7e9e112d0f..0000000000--- a/packages/base-numfmt-engine/src/core/locale.ts+++ /dev/null@@ -1,723 +0,0 @@-import { codeToLocale } from './code-to-locale';--export interface LocaleData {- positive?: string;- decimal?: string;- negative?: string;- percent?: string;- nan?: string;- exponent?: string;- group?: string;- isDefault?: boolean;- infinity?: string;- colors?: string[];- ampm?: string[];- mmm6?: string[];- mmmm6?: string[];- mmm?: string[];- mmmm?: string[];- ddd?: string[];- dddd?: string[];-}--export interface LocaleType {- lang?: string;- language?: string;- codeset?: string;- modifier?: string;- territory?: string;-}--const REG_EXP_LOCALE = /^([a-z\d]+)(?:[_-]([a-z\d]+))?(?:\.([a-z\d]+))?(?:@([a-z\d]+))?$/i;--const defaultData: LocaleData = {- positive: '+',- decimal: '.',- negative: '-',- percent: '%',- isDefault: false,- nan: 'NaN',- exponent: 'E',- group: ' ',- infinity: '∞',- colors: ['black', 'blue', 'cyan', 'green', 'magenta', 'red', 'white', 'yellow'],- ampm: ['AM', 'PM'],- mmm: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],- mmmm: [- 'January',- 'February',- 'March',- 'April',- 'May',- 'June',- 'July',- 'August',- 'September',- 'October',- 'November',- 'December',- ],- mmm6: [- 'Muh.',- 'Saf.',- 'Rab. I',- 'Rab. II',- 'Jum. I',- 'Jum. II',- 'Raj.',- 'Sha.',- 'Ram.',- 'Shaw.',- 'Dhuʻl-Q.',- 'Dhuʻl-H.',- ],- mmmm6: [- 'Muharram',- 'Safar',- 'Rabiʻ I',- 'Rabiʻ II',- 'Jumada I',- 'Jumada II',- 'Rajab',- 'Shaʻban',- 'Ramadan',- 'Shawwal',- 'Dhuʻl-Qiʻdah',- 'Dhuʻl-Hijjah',- ],- ddd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],- dddd: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],-};--const locales: any = defaultData; // LocaleData--export function createLocale(data: LocaleData): LocaleData {- return { ...defaultData, ...data };-}--export function resolveLocale(l4e: string | number): string | null {- if (typeof l4e === 'number') {- return (codeToLocale as any)[l4e & 0xffff] || null;- }- const wincode: any = parseInt(l4e, 16);- if (isFinite(wincode) && (codeToLocale as any)[wincode & 0xffff]) {- return (codeToLocale as any)[wincode & 0xffff] || null;- }- if (REG_EXP_LOCALE.test(l4e)) {- return l4e;- }- return null;-}--export function parseLocale(l4e: string): LocaleType {- const lm = REG_EXP_LOCALE.exec(l4e);- if (!lm) {- throw new SyntaxError(`Malformed locale: ${l4e}`);- }- return {- lang: lm[1] + (lm[2] ? `_${lm[2]}` : ''),- language: lm[1],- territory: lm[2] || '',- codeset: lm[3] || '',- modifier: lm[4] || '',- };-}--export function getLocale(l4e: string | number): LocaleData {- const tag = resolveLocale(l4e);- let obj: any = null; // LocaleData- if (tag) {- const c: any = parseLocale(tag);- obj = locales[c.lang] || locales[c.language] || null;- }- return obj;-}--export function addLocale(options: LocaleData, id: string | LocaleType): LocaleData {- // parse language tag- const c: any = typeof id === 'object' ? id : parseLocale(id);- // add the language- locales[c.lang] = createLocale(options);- // if "xx_YY" is added also create "xx" if it is missing- if (c.language !== c.lang && !locales[c.language]) {- locales[c.language] = createLocale(options);- }- return locales[c.lang];-}--export const defaultLocale = createLocale({ group: ',' });--defaultLocale.isDefault = true;--addLocale(- {- group: ',',- ampm: ['上午', '下午'],- mmmm: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],- mmm: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],- dddd: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],- ddd: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],- },- 'zh_CN'-);--addLocale(- {- group: ',',- nan: '非數值',- ampm: ['上午', '下午'],- mmmm: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],- mmm: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],- dddd: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],- ddd: ['週日', '週一', '週二', '週三', '週四', '週五', '週六'],- },- 'zh_TW'-);--addLocale(- {- group: ',',- ampm: ['午前', '午後'],- mmmm: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],- mmm: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],- dddd: ['日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日'],- ddd: ['日', '月', '火', '水', '木', '金', '土'],- },- 'ja'-);--addLocale(- {- group: ',',- ampm: ['오전', '오후'],- mmmm: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],- mmm: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],- dddd: ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'],- ddd: ['일', '월', '화', '수', '목', '금', '토'],- },- 'ko'-);--addLocale(- {- group: ',',- ampm: ['ก่อนเที่ยง', 'หลังเที่ยง'],- mmmm: [- 'มกราคม',- 'กุมภาพันธ์',- 'มีนาคม',- 'เมษายน',- 'พฤษภาคม',- 'มิถุนายน',- 'กรกฎาคม',- 'สิงหาคม',- 'กันยายน',- 'ตุลาคม',- 'พฤศจิกายน',- 'ธันวาคม',- ],- mmm: ['ม.ค.', 'ก.พ.', 'มี.ค.', 'เม.ย.', 'พ.ค.', 'มิ.ย.', 'ก.ค.', 'ส.ค.', 'ก.ย.', 'ต.ค.', 'พ.ย.', 'ธ.ค.'],- dddd: ['วันอาทิตย์', 'วันจันทร์', 'วันอังคาร', 'วันพุธ', 'วันพฤหัสบดี', 'วันศุกร์', 'วันเสาร์'],- ddd: ['อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'],- },- 'th'-);--addLocale(- {- decimal: ',',- ampm: ['dop.', 'odp.'],- mmmm: [- 'ledna',- 'února',- 'března',- 'dubna',- 'května',- 'června',- 'července',- 'srpna',- 'září',- 'října',- 'listopadu',- 'prosince',- ],- mmm: ['led', 'úno', 'bře', 'dub', 'kvě', 'čvn', 'čvc', 'srp', 'zář', 'říj', 'lis', 'pro'],- dddd: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],- ddd: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],- },- 'cs'-);--addLocale(- {- group: '.',- decimal: ',',- mmmm: [- 'januar',- 'februar',- 'marts',- 'april',- 'maj',- 'juni',- 'juli',- 'august',- 'september',- 'oktober',- 'november',- 'december',- ],- mmm: ['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'dec.'],- dddd: ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'],- ddd: ['søn.', 'man.', 'tir.', 'ons.', 'tor.', 'fre.', 'lør.'],- },- 'da'-);--addLocale(- {- group: '.',- decimal: ',',- ampm: ['a.m.', 'p.m.'],- mmmm: [- 'januari',- 'februari',- 'maart',- 'april',- 'mei',- 'juni',- 'juli',- 'augustus',- 'september',- 'oktober',- 'november',- 'december',- ],- mmm: ['jan.', 'feb.', 'mrt.', 'apr.', 'mei', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'dec.'],- dddd: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],- ddd: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],- },- 'nl'-);--addLocale(- {- group: ',',- },- 'en'-);--addLocale(- {- decimal: ',',- nan: 'epäluku',- ampm: ['ap.', 'ip.'],- mmmm: [- 'tammikuuta',- 'helmikuuta',- 'maaliskuuta',- 'huhtikuuta',- 'toukokuuta',- 'kesäkuuta',- 'heinäkuuta',- 'elokuuta',- 'syyskuuta',- 'lokakuuta',- 'marraskuuta',- 'joulukuuta',- ],- mmm: [- 'tammik.',- 'helmik.',- 'maalisk.',- 'huhtik.',- 'toukok.',- 'kesäk.',- 'heinäk.',- 'elok.',- 'syysk.',- 'lokak.',- 'marrask.',- 'jouluk.',- ],- dddd: ['sunnuntaina', 'maanantaina', 'tiistaina', 'keskiviikkona', 'torstaina', 'perjantaina', 'lauantaina'],- ddd: ['su', 'ma', 'ti', 'ke', 'to', 'pe', 'la'],- },- 'fi'-);--addLocale(- {- group: ' ',- decimal: ',',- mmmm: [- 'janvier',- 'février',- 'mars',- 'avril',- 'mai',- 'juin',- 'juillet',- 'août',- 'septembre',- 'octobre',- 'novembre',- 'décembre',- ],- mmm: ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],- dddd: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],- ddd: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],- },- 'fr'-);--addLocale(- {- group: '.',- decimal: ',',- mmmm: [- 'Januar',- 'Februar',- 'März',- 'April',- 'Mai',- 'Juni',- 'Juli',- 'August',- 'September',- 'Oktober',- 'November',- 'Dezember',- ],- mmm: ['Jan.', 'Feb.', 'März', 'Apr.', 'Mai', 'Juni', 'Juli', 'Aug.', 'Sept.', 'Okt.', 'Nov.', 'Dez.'],- dddd: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],- ddd: ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'],- },- 'de'-);--addLocale(- {- group: '.',- decimal: ',',- ampm: ['π.μ.', 'μ.μ.'],- mmmm: [- 'Ιανουαρίου',- 'Φεβρουαρίου',- 'Μαρτίου',- 'Απριλίου',- 'Μαΐου',- 'Ιουνίου',- 'Ιουλίου',- 'Αυγούστου',- 'Σεπτεμβρίου',- 'Οκτωβρίου',- 'Νοεμβρίου',- 'Δεκεμβρίου',- ],- mmm: ['Ιαν', 'Φεβ', 'Μαρ', 'Απρ', 'Μαΐ', 'Ιουν', 'Ιουλ', 'Αυγ', 'Σεπ', 'Οκτ', 'Νοε', 'Δεκ'],- dddd: ['Κυριακή', 'Δευτέρα', 'Τρίτη', 'Τετάρτη', 'Πέμπτη', 'Παρασκευή', 'Σάββατο'],- ddd: ['Κυρ', 'Δευ', 'Τρί', 'Τετ', 'Πέμ', 'Παρ', 'Σάβ'],- },- 'el'-);--addLocale(- {- decimal: ',',- ampm: ['de.', 'du.'],- mmmm: [- 'január',- 'február',- 'március',- 'április',- 'május',- 'június',- 'július',- 'augusztus',- 'szeptember',- 'október',- 'november',- 'december',- ],- mmm: ['jan.', 'febr.', 'márc.', 'ápr.', 'máj.', 'jún.', 'júl.', 'aug.', 'szept.', 'okt.', 'nov.', 'dec.'],- dddd: ['vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat'],- ddd: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],- },- 'hu'-);--addLocale(- {- group: '.',- decimal: ',',- ampm: ['f.h.', 'e.h.'],- mmmm: [- 'janúar',- 'febrúar',- 'mars',- 'apríl',- 'maí',- 'júní',- 'júlí',- 'ágúst',- 'september',- 'október',- 'nóvember',- 'desember',- ],- mmm: ['jan.', 'feb.', 'mar.', 'apr.', 'maí', 'jún.', 'júl.', 'ágú.', 'sep.', 'okt.', 'nóv.', 'des.'],- dddd: ['sunnudagur', 'mánudagur', 'þriðjudagur', 'miðvikudagur', 'fimmtudagur', 'föstudagur', 'laugardagur'],- ddd: ['sun.', 'mán.', 'þri.', 'mið.', 'fim.', 'fös.', 'lau.'],- },- 'is'-);--addLocale(- {- group: '.',- decimal: ',',- mmmm: [- 'Januari',- 'Februari',- 'Maret',- 'April',- 'Mei',- 'Juni',- 'Juli',- 'Agustus',- 'September',- 'Oktober',- 'November',- 'Desember',- ],- mmm: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],- dddd: ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'],- ddd: ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab'],- },- 'id'-);--addLocale(- {- group: '.',- decimal: ',',- mmmm: [- 'gennaio',- 'febbraio',- 'marzo',- 'aprile',- 'maggio',- 'giugno',- 'luglio',- 'agosto',- 'settembre',- 'ottobre',- 'novembre',- 'dicembre',- ],- mmm: ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'],- dddd: ['domenica', 'lunedì', 'martedì', 'mercoledì', 'giovedì', 'venerdì', 'sabato'],- ddd: ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'],- },- 'it'-);--addLocale(- {- decimal: ',',- ampm: ['a.m.', 'p.m.'],- mmmm: [- 'januar',- 'februar',- 'mars',- 'april',- 'mai',- 'juni',- 'juli',- 'august',- 'september',- 'oktober',- 'november',- 'desember',- ],- mmm: ['jan.', 'feb.', 'mar.', 'apr.', 'mai', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'des.'],- dddd: ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'],- ddd: ['søn.', 'man.', 'tir.', 'ons.', 'tor.', 'fre.', 'lør.'],- },- 'nb'-);--addLocale(- {- decimal: ',',- mmmm: [- 'stycznia',- 'lutego',- 'marca',- 'kwietnia',- 'maja',- 'czerwca',- 'lipca',- 'sierpnia',- 'września',- 'października',- 'listopada',- 'grudnia',- ],- mmm: ['sty', 'lut', 'mar', 'kwi', 'maj', 'cze', 'lip', 'sie', 'wrz', 'paź', 'lis', 'gru'],- dddd: ['niedziela', 'poniedziałek', 'wtorek', 'środa', 'czwartek', 'piątek', 'sobota'],- ddd: ['niedz.', 'pon.', 'wt.', 'śr.', 'czw.', 'pt.', 'sob.'],- },- 'pl'-);--addLocale(- {- group: '.',- decimal: ',',- mmmm: [- 'janeiro',- 'fevereiro',- 'março',- 'abril',- 'maio',- 'junho',- 'julho',- 'agosto',- 'setembro',- 'outubro',- 'novembro',- 'dezembro',- ],- mmm: ['jan.', 'fev.', 'mar.', 'abr.', 'mai.', 'jun.', 'jul.', 'ago.', 'set.', 'out.', 'nov.', 'dez.'],- dddd: ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],- ddd: ['dom.', 'seg.', 'ter.', 'qua.', 'qui.', 'sex.', 'sáb.'],- },- 'pt'-);--addLocale(- {- decimal: ',',- nan: 'не число',- mmmm: [- 'января',- 'февраля',- 'марта',- 'апреля',- 'мая',- 'июня',- 'июля',- 'августа',- 'сентября',- 'октября',- 'ноября',- 'декабря',- ],- mmm: ['янв.', 'февр.', 'мар.', 'апр.', 'мая', 'июн.', 'июл.', 'авг.', 'сент.', 'окт.', 'нояб.', 'дек.'],- dddd: ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'],- ddd: ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'],- },- 'ru'-);--addLocale(- {- decimal: ',',- mmmm: [- 'januára',- 'februára',- 'marca',- 'apríla',- 'mája',- 'júna',- 'júla',- 'augusta',- 'septembra',- 'októbra',- 'novembra',- 'decembra',- ],- mmm: ['jan', 'feb', 'mar', 'apr', 'máj', 'jún', 'júl', 'aug', 'sep', 'okt', 'nov', 'dec'],- dddd: ['nedeľa', 'pondelok', 'utorok', 'streda', 'štvrtok', 'piatok', 'sobota'],- ddd: ['ne', 'po', 'ut', 'st', 'št', 'pi', 'so'],- },- 'sk'-);--addLocale(- {- group: '.',- decimal: ',',- ampm: ['a. m.', 'p. m.'],- mmmm: [- 'enero',- 'febrero',- 'marzo',- 'abril',- 'mayo',- 'junio',- 'julio',- 'agosto',- 'septiembre',- 'octubre',- 'noviembre',- 'diciembre',- ],- mmm: ['ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sept.', 'oct.', 'nov.', 'dic.'],- dddd: ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],- ddd: ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'],- },- 'es'-);--addLocale(- {- decimal: ',',- ampm: ['fm', 'em'],- mmmm: [- 'januari',- 'februari',- 'mars',- 'april',- 'maj',- 'juni',- 'juli',- 'augusti',- 'september',- 'oktober',- 'november',- 'december',- ],- mmm: ['jan.', 'feb.', 'mars', 'apr.', 'maj', 'juni', 'juli', 'aug.', 'sep.', 'okt.', 'nov.', 'dec.'],- dddd: ['söndag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag'],- ddd: ['sön', 'mån', 'tis', 'ons', 'tors', 'fre', 'lör'],- },- 'sv'-);--addLocale(- {- group: '.',- decimal: ',',- ampm: ['ÖÖ', 'ÖS'],- mmmm: [- 'Ocak',- 'Şubat',- 'Mart',- 'Nisan',- 'Mayıs',- 'Haziran',- 'Temmuz',- 'Ağustos',- 'Eylül',- 'Ekim',- 'Kasım',- 'Aralık',- ],- mmm: ['Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara'],- dddd: ['Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi'],- ddd: ['Paz', 'Pzt', 'Sal', 'Çar', 'Per', 'Cum', 'Cmt'],- },- 'tr'-);diff --git a/packages/base-numfmt-engine/src/core/numdec.ts b/packages/base-numfmt-engine/src/core/numdec.tsdeleted file mode 100644index 4189387407..0000000000--- a/packages/base-numfmt-engine/src/core/numdec.ts+++ /dev/null@@ -1,70 +0,0 @@-import { round } from './round';--const zero = {- total: 1,- sign: 0,- period: 0,- int: 1,- frac: 0,-};--// returns the count of digits (including - and .) need to represent the number-export function numdec(value: number, incl_sign = true) {- const v = Math.abs(value);-- // shortcut zero- if (!v) {- return zero;- }-- const signSize = incl_sign && value < 0 ? 1 : 0;- const intPart = Math.floor(v);- const intSize = Math.floor(Math.log10(v) + 1);- let periodSize = 0;- let fracSize = 0;-- // is not an integer- if (intPart !== v) {- periodSize = 1;-- // B: this has turned out to be much faster than all pure math- // based solutions I was able to come up with ¯\_(ツ)_/¯- const n = String(round(intSize < 0 ? v * 10 ** -intSize : v / 10 ** intSize, 15));- let f = n.length;- let z = true;- let i = 0;- while (i <= n.length) {- if (n[i] === '.') {- // discount period- f--;- break;- } else if (n[i] === '0' && z) {- // leading zeros before period are discounted- f--;- } else {- // non-zero digit- z = false;- }- i++;- }- fracSize = f - intSize;-- if (fracSize < 0) {- // the number is not representable [by Excel]- // this would be something like 1000.0000000000001- // it would normally get truncated to 15 significant figures and- // end up in the same place as the following does:- fracSize = 0;- periodSize = 0;- }- }-- return {- total: signSize + Math.max(intSize, 1) + periodSize + fracSize,- digits: Math.max(intSize, 0) + fracSize,- sign: signSize,- period: periodSize,- int: Math.max(intSize, 1),- frac: fracSize,- };-}diff --git a/packages/base-numfmt-engine/src/core/options.ts b/packages/base-numfmt-engine/src/core/options.tsdeleted file mode 100644index c9e94c5034..0000000000--- a/packages/base-numfmt-engine/src/core/options.ts+++ /dev/null@@ -1,59 +0,0 @@-export interface OptionsData {- overflow?: string;- dateErrorThrows?: boolean;- dateSpanLarge?: boolean;- dateErrorNumber?: boolean;- invalid?: string;- locale?: string;- leap1900?: boolean;- nbsp?: boolean;- throws?: boolean;- ignoreTimezone?: boolean;-}--const defaultOptions: OptionsData = {- // Overflow error string- overflow: '######', // dateErrorThrow needs to be off! [prev in locale]- // Should it throw when there is an overflow error?- dateErrorThrows: false,- // Should it emit a number is an overflow error? (Sheets does this)- dateErrorNumber: true, // dateErrorThrow needs to be off!- // Sheets mode (see #3)- dateSpanLarge: true,- // Simulate the Lotus 1-2-3 leap year bug- leap1900: true,- // Emit regular vs. non-breaking spaces- nbsp: true,- // Robust/throw mode- throws: true,- // What is emitted when robust mode fails to parse (###### currently)- invalid: '######',- // Locale- locale: '',- // Don't adjust dates to UTC when converting them to serial time- ignoreTimezone: false,-};--const globalOptions = { ...defaultOptions };--export function options(opts: OptionsData = {}): OptionsData {- // passing in a null will reset to defaults- if (opts === null) {- opts = defaultOptions;- }- if (opts) {- for (const key in opts) {- if (key in defaultOptions) {- const k = key as keyof OptionsData;- const value = opts[k];- if (value == null) {- // set back to default- globalOptions[k] = defaultOptions[k] as undefined;- } else {- globalOptions[k] = value as any;- }- }- }- }- return { ...globalOptions };-}diff --git a/packages/base-numfmt-engine/src/core/parse-part.ts b/packages/base-numfmt-engine/src/core/parse-part.tsdeleted file mode 100644index d56583fb84..0000000000--- a/packages/base-numfmt-engine/src/core/parse-part.ts+++ /dev/null@@ -1,600 +0,0 @@-import {- _numchars,- _sp_chars,- EPOCH_1317,- EPOCH_1900,- indexColors,- u_CSEC,- u_DAY,- u_DSEC,- u_HOUR,- u_MIN,- u_MONTH,- u_MSEC,- u_SEC,- u_YEAR,-} from './constants';-import { resolveLocale } from './locale';--export interface TokensType {- type?: string;- value?: string;- short?: boolean;- used?: boolean;- indeterminate?: boolean;- size?: number;- date?: number;- pad?: number;- num?: number[];- rule?: string;- raw?: string;- volatile?: boolean;- plus?: boolean;- decimals?: number;-}--export interface PartType {- scale?: number;- percent?: boolean;- int_max?: number;- generated?: boolean;- denominator?: number;- num_min?: number;- den_min?: number;- text?: boolean;- group_sec?: number;- frac_max?: number;- num_max?: number;- den_max?: number;- date?: number;- exponential?: boolean;- group_pri?: number;- exp_plus?: boolean;- condition?: [string, number];- fractions?: boolean;- grouping?: boolean;- date_eval?: boolean;- date_system?: number;- dec_fractions?: boolean;- sec_decimals?: number;- pattern?: string;- general?: boolean;- integer?: boolean;- clock?: number;- locale?: string;- color?: string;- int_pattern?: number[];- frac_pattern?: number[];- man_pattern?: number[];- den_pattern?: number[];- num_pattern?: number[];- tokens?: TokensType[];- int_padding?: string;- man_padding?: string;- num_padding?: string;- den_padding?: string;-}--const _pattcache: {- [key: string]: string;-} = {};--function minMaxPad(str: string, part: object | any, prefix: string): object {- part[`${prefix}_max`] = str.length;- part[`${prefix}_min`] = str.replace(/#/g, '').length;- return part;-}--function patternToPadding(ss: string): string {- if (!(ss in _pattcache)) {- const nch = [];- const chars = ss.replace(/^[#,]+/, '').replace(/[1-9]\d*/g, (m) => '?'.repeat(m.length));- for (let i = 0; i < chars.length; i++) {- const c = chars.charAt(i);- nch[i] = c in _numchars ? _numchars[c] : c;- }- _pattcache[ss] = nch.join('');- }- return _pattcache[ss];-}--/**- * 添加Token- * @param s- * @param tokens- */-function add(s: TokensType | string, tokens: TokensType[] | any) {- // allow adding string tokens without wrapping- if (typeof s === 'string') {- s = s.replace(/ /g, _numchars['?']);- s = { type: 'string', value: s };- }- // automatically join adjacent string tokens- if (s.type === 'string' && tokens.length && tokens[tokens.length - 1].type === 'string') {- tokens[tokens.length - 1].value += s.value;- } else {- tokens.push(s as TokensType);- }-}--export function parsePart(pattern: string): PartType {- const tokens: any = [];- const part: any = {- scale: 1,- percent: false,- text: false,- denominator: 0,- date: 0,- generated: false,- exponential: false,- exp_plus: false,- grouping: false,- date_eval: false,- locale: '',- condition: null,- date_system: null,- sec_decimals: 0,- general: false,- integer: false,- group_sec: 0,- fractions: false,- group_pri: 0,- color: '',- clock: 24,- int_padding: '',- man_padding: '',- num_padding: '',- den_padding: '',- dec_fractions: false,- pattern: '',- int_pattern: [],- frac_pattern: [],- man_pattern: [],- den_pattern: [],- num_pattern: [],- tokens,- }; // PartType-- let s = `${pattern}`;- let current_pattern = 'int';- let part_over = false;- let last_number_chunk = null;- const date_chunks = [];- let last;- let have_locale = false;- let m: RegExpExecArray | string[] | any;-- while (s && !part_over) {- if ((m = /^General/i.exec(s))) {- part.general = true;- add({ type: 'general' }, tokens);- }-- // new partition- else if (- (current_pattern === 'int' && (m = /^[#?0]+(?:,[#?0]+)*/.exec(s))) ||- (current_pattern === 'den' && (m = /^[#?\d]+/.exec(s))) ||- (m = /^[#?0]+/.exec(s))- ) {- part[`${current_pattern}_pattern`].push(m[0]);- last_number_chunk = { type: current_pattern, num: m[0] };- add(last_number_chunk as any, tokens);- }-- // vulgar fractions- else if ((m = /^\//.exec(s)) && part[`${current_pattern}_pattern`].length) {- if (!last_number_chunk) {- // need to have a numerator present- throw new SyntaxError(`Missing a numerator in pattern ${pattern}`);- }- part.fractions = true;- // ... we just passed the numerator - correct that item- part.num_pattern.push(part[`${current_pattern}_pattern`].pop());- last_number_chunk.type = 'num';- // next up... the denominator- current_pattern = 'den';- add({ type: 'div' }, tokens);- } else if ((m = /^,+/.exec(s))) {- // decimal scaling- // * must directly follow a "number character" [#0?] and- // * must not be followed by a number character- const followed_by_num = s.charAt(1) in _numchars;- const following_num = last.slice(-1) in _numchars;- if (following_num && (m[0].length > 1 || !followed_by_num)) {- part.scale = 0.001 ** m[0].length;- } else {- // regular comma- add(m[0], tokens);- }- } else if ((m = /^;/.exec(s))) {- part_over = true;- break; // leave the ";" hanging- }-- // handlers- else if ((m = /^[@+-]/.exec(s))) {- if (m[0] === '@') {- part.text = true;- }- add({ type: _sp_chars[m[0]] }, tokens);- }-- // [h] [m] [s]- else if ((m = /^(?:\[(h+|m+|s+)\])/i.exec(s))) {- const token = m[1].toLowerCase();- const tok = token[0];- const bit = {- type: '',- size: 0,- date: 1,- raw: m[0],- pad: token.length,- };- if (tok === 'h') {- bit.size = u_HOUR;- bit.type = 'hour-elap';- } else if (tok === 'm') {- bit.size = u_MIN;- bit.type = 'min-elap';- } else {- bit.size = u_SEC;- bit.type = 'sec-elap';- }- // signal date calc and track smallest needed unit- part.date |= bit.size;- date_chunks.push(bit);- add(bit, tokens);- }-- // Use Hijri calendar system- else if ((m = /^(?:B2)/i.exec(s))) {- // signal date system (ignored if defined with [$-xxx])- if (!have_locale) {- // TODO: B2 does more than this, it switches locale to [$-060401] (ar) which affects display (RTL)- part.date_system = EPOCH_1317;- }- }-- // Use Gregorian calendar system- else if ((m = /^(?:B1)/i.exec(s))) {- // signal date system (ignored if defined with [$-xxx])- if (!have_locale) {- part.date_system = EPOCH_1900;- }- }-- // hh:mm:ss YYYY-MM-DD- else if ((m = /^(?:([hHmMsSyYbBdDegG])\1*)/.exec(s))) {- // Excel is "mostly" case insensitive here but checks the last used date token- // if it was s or h, minutes is used – same is true if we hit m or s, and last is m- // m and mm are spurious, mmm is always month- const bit: TokensType = {- type: '',- size: 0,- date: 1,- raw: m[0],- pad: 0,- indeterminate: false,- used: false,- };- const token = m[0].toLowerCase();- const tok = token[0];-- if (token === 'y' || token === 'yy') {- bit.size = u_YEAR;- bit.type = 'year-short';- } else if (tok === 'y' || tok === 'e') {- bit.size = u_YEAR;- bit.type = 'year';- } else if (token === 'b' || token === 'bb') {- bit.size = u_YEAR;- bit.type = 'b-year-short';- } else if (tok === 'b') {- bit.size = u_YEAR;- bit.type = 'b-year';- } else if (token === 'd' || token === 'dd') {- bit.size = u_DAY;- bit.type = 'day';- bit.pad = /dd/.test(token) ? 1 : 0;- } else if (token === 'ddd') {- bit.size = u_DAY;- bit.type = 'weekday-short';- } else if (tok === 'd') {- bit.size = u_DAY;- bit.type = 'weekday';- } else if (tok === 'h') {- bit.size = u_HOUR;- bit.type = 'hour';- bit.pad = /hh/i.test(token) ? 1 : 0;- } else if (tok === 'm') {- if (token.length === 3) {- bit.size = u_MONTH;- bit.type = 'monthname-short';- } else if (token.length === 5) {- bit.size = u_MONTH;- bit.type = 'monthname-single';- } else if (token.length >= 4) {- bit.size = u_MONTH;- bit.type = 'monthname';- }- // m or mm can be either minute or month based on context- const last_date_chunk: any = date_chunks[date_chunks.length - 1];- if (!bit.type && last_date_chunk && !last_date_chunk.used && last_date_chunk.size & (u_HOUR | u_SEC)) {- // if this token follows hour or second, it is a minute- last_date_chunk.used = true;- bit.size = u_MIN;- bit.type = 'min';- bit.pad = /mm/.test(token) ? 1 : 0;- }- // if we still don't know, we treat as a month- // and defer, a later 'sec' token may switch it- if (!bit.type) {- bit.size = u_MONTH;- bit.type = 'month';- bit.pad = /mm/.test(token) ? 1 : 0;- bit.indeterminate = true;- }- } else if (tok === 's') {- bit.size = u_SEC;- bit.type = 'sec';- bit.pad = /ss/.test(token) ? 1 : 0;- // if last date chunk was m, flag this used- const last_date_chunk: any = date_chunks[date_chunks.length - 1];- if (last_date_chunk && last_date_chunk.size & u_MIN) {- bit.used = true;- }- // if last date chunk is undecided, we know that it is a minute- else if (last_date_chunk && last_date_chunk.indeterminate) {- delete last_date_chunk.indeterminate;- last_date_chunk.size = u_MIN;- last_date_chunk.type = 'min';- bit.used = true;- }- } else if (tok === 'g') {- // FIXME: Don't know what this does? (yet!)- }- // signal date calc and track smallest needed unit- part.date |= bit.size!;- part.date_eval = true;- date_chunks.push(bit);- add(bit, tokens);- }-- // AM/PM- // See: https://github.com/SheetJS/sheetjs/issues/676- else if ((m = /^(?:AM\/PM|am\/pm|A\/P)/.exec(s))) {- part.clock = 12;- // TEST: size is here is just a guess, can possibly detect this by rounding?- part.date |= u_HOUR;- part.date_eval = true;- add({ type: 'am', short: m[0] === 'A/P' }, tokens);- }-- // Note: In locales where decimal symbol is set to "," Excel expects that rather than "."- // .0 .00 .000- else if (part.date && (m = /^\.0{1,3}/i.exec(s))) {- const dec = m[0].length - 1;- const size = [u_SEC, u_DSEC, u_CSEC, u_MSEC][dec];- part.date |= size;- part.date_eval = true;- part.sec_decimals = Math.max(part.sec_decimals, dec);- add(- {- type: 'subsec',- size,- decimals: dec,- date: 1,- raw: m[0],- },- tokens- );- }-- // escaped character, string- else if ((m = /^\\(.)/.exec(s)) || (m = /^"([^"]*?)"/.exec(s))) {- add(m[1], tokens);- }-- // condition- else if ((m = /^\[(<[=>]?|>=?|=)\s*(-?[.\d]+)\]/.exec(s))) {- part.condition = [m[1], parseFloat(m[2])]; // [ operator, operand ]- }-- // locale code -- we allow std. "en-US" style codes- // https://stackoverflow.com/questions/54134729/what-does-the-130000-in-excel-locale-code-130000-mean/54540455#54540455- else if ((m = /^\[\$([^\]]+)\]/.exec(s))) {- const bits = m[1].split('-');- const code = bits.length < 2 ? '' : bits[bits.length - 1];-- const currency = bits[0];- if (currency) {- add(currency, tokens);- }-- const l4e = resolveLocale(code);- if (l4e) {- part.locale = l4e;- }- const wincode = parseInt(code, 16);- if (isFinite(wincode) && wincode & 0xff0000) {- const cal = (wincode >> 16) & 0xff;- // only Hijri is supported atm.- if (cal === 6) {- part.date_system = EPOCH_1317;- }- }-- have_locale = true; // ignore any B2 & B1 tokens- }-- // color- else if ((m = /^\[(black|blue|cyan|green|magenta|red|white|yellow|color\s*(\d+))\]/i.exec(s))) {- part.color = m[2] ? indexColors[parseInt(m[2], 10)] || '#000' : m[1].toLowerCase();- }-- // WTF- else if ((m = /^\[(DBNum1|ENG|HIJ|JPN|TWN)\]/i.exec(s))) {- // ...- }-- // percentage- else if ((m = /^%/.exec(s))) {- part.scale = 100;- part.percent = true;- add('%', tokens);- }-- // skip width- else if ((m = /^_(\\.|.)/.exec(s))) {- // UNSUPPORTED: This does what Excel's TEXT function does in this case: Emits a space.- // It might be worth considering emitting U+200B (zero width space) for the most common pattern, "* ".- // That way a recipent of the string might still be able to make the spacing work by splitting the number?- add(' ', tokens);- }-- // decimal fraction- else if ((m = /^\./.exec(s))) {- add({ type: 'point', value: m[0] }, tokens);- part.dec_fractions = true;- current_pattern = 'frac';- }-- // exponent- else if ((m = /^[Ee]([+-]?|(?=[0#?]))/.exec(s))) {- // Exponent pattern requires symbol to directly follow "E" but the- // signature symbol, however, prefixes the first digit of the mantissa- part.exponential = true;- part.exp_plus = m[1] === '+';- current_pattern = 'man';- add({ type: 'exp', plus: m[1] === '+' }, tokens);- }-- // fill space with next char- else if ((m = /^\*(\\.|.)/.exec(s))) {- // UNSUPPORTED: This does what Excel's TEXT function does in this case: Emits nothing.- }-- // characters that throw ... because reasons?- // Excel also throws on ÈÉÊËèéêëĒēĔĕĖėĘęĚěȄȅȆȇȨȩNnÑñŃńŅņŇňǸǹ...- // but there is limited point in replicating that behaviour- else if ((m = /^[BENn[]/.exec(s))) {- throw new SyntaxError(`Unexpected char ${s.charAt(0)} in pattern ${pattern}`);- }-- // characters are generally allowed to pass directly through- else {- m = [s[0]];- add(m[0], tokens);- }-- // advance parser- last = m[0];- s = s.slice(m ? m[0].length : 1);- }-- part.pattern = pattern.slice(0, pattern.length - s.length);-- // Quickly determine if this pattern is condition only- // if so, then add String(value) but using the condition- if (/^((?:\[[^\]]+\])+)(;|$)/.test(part.pattern) && !/^\[(?:h+|m+|s+)\]/.test(part.pattern)) {- add({ type: 'text' }, tokens);- }-- // Make sure we don't have an illegal pattern. We could support this but- // lets side with Excel here and don't because they make absolutely no sense.- if ((part.fractions && part.dec_fractions) || (part.fractions && part.exponential)) {- throw new SyntaxError(`Invalid pattern: ${part.pattern}`);- }-- // parse number grouping- const ipatt = part.int_pattern.join('');- part.grouping = ipatt.indexOf(',') >= 0;- if (part.grouping) {- const si = ipatt.split(',');- const sl = si.length;- if (sl === 2) {- part.group_pri = si[1].length;- part.group_sec = part.group_pri;- }- // next block should only- else if (sl > 2) {- part.group_pri = si[sl - 1].length;- part.group_sec = si[sl - 2].length;- }- } else {- part.group_pri = 0;- part.group_sec = 0;- }-- minMaxPad(ipatt.replace(/[,]/g, ''), part, 'int');- minMaxPad(part.frac_pattern.join(''), part, 'frac');- minMaxPad(part.man_pattern.join(''), part, 'man');-- let num_pat = part.num_pattern.join('');- let den_pat = part.den_pattern.join('');-- const enforce_padded = /\?/.test(den_pat) || /\?/.test(num_pat);-- // numberical denominator padding type is inherited from numerator padding type- den_pat = den_pat.replace(/\d/g, enforce_padded ? '?' : '#');- if (enforce_padded) {- // this needs to be _before_ min/max- den_pat = den_pat.replace(/#$/g, '?');- }-- minMaxPad(num_pat, part, 'num');- minMaxPad(den_pat, part, 'den');- if (enforce_padded) {- // this needs to be _after_ min/max- num_pat = num_pat.replace(/#$/g, '?');- }-- part.int_padding = patternToPadding(part.int_pattern.join(''));- part.man_padding = patternToPadding(part.man_pattern.join(''));-- part.num_padding = patternToPadding(num_pat);- part.den_padding = patternToPadding(den_pat);-- if (part.den_pattern.length) {- // detect and set rounding factor for denominator- part.denominator = parseInt(part.den_pattern.join('').replace(/\D/g, ''), 10);- }- part.integer = !!part.int_pattern.join('').length;-- // extra whitespace rules for vulgar fractions- if (part.fractions) {- // fragment bits affect surrounding whitespace- // if either bit is "#", the whitespace around it, and- // the div symbol, is removed if the bit is not shown- tokens.forEach((tok: any, i: number) => {- // is next token a "num", "den", or "div"?- const next = tokens[i + 1];- if (tok.type === 'string' && next) {- if (next.type === 'num') {- tok.rule = 'num+int';- } else if (next.type === 'div') {- tok.rule = 'num';- } else if (next.type === 'den') {- tok.rule = 'den';- }- }- });- }-- // dates cannot blend with non-date tokens- // general cannot blend with non-date tokens- // -- this is doess not match excel 100% (it seems to allow , as a text token with general)- // -- excel also does something strange when mixing general with dates (but that can hardly be expected to work)- if (- (part.date || part.general) &&- (part.int_pattern.length || part.frac_pattern.length || part.scale !== 1 || part.text)- ) {- throw new Error('Illegal format');- }-- if (!part.date_system) {- part.date_system = EPOCH_1900;- }-- return part;-}diff --git a/packages/base-numfmt-engine/src/core/parse-pattern.ts b/packages/base-numfmt-engine/src/core/parse-pattern.tsdeleted file mode 100644index a7ddcc7ca3..0000000000--- a/packages/base-numfmt-engine/src/core/parse-pattern.ts+++ /dev/null@@ -1,118 +0,0 @@-import { resolveLocale } from './locale';-import { parsePart, PartType } from './parse-part';--export interface PatternType {- pattern?: string;- locale?: string;- error?: string;- partitions?: PartType[];-}--export function parsePattern(pattern: string): PatternType {- const partitions = [];- let conditional = false;- let l10n_override;- let text_partition = null;-- let p = pattern;- let more = 0;- let part = null;- let i = 0;- let conditions = 0;- do {- part = parsePart(p);- if (part.condition) {- conditions++;- conditional = true;- }- if (part.text) {- // only one text partition is allowed per pattern- if (text_partition) {- throw new Error('Unexpected partition');- }- text_partition = part;- }- if (part.locale) {- l10n_override = resolveLocale(part.locale);- }- partitions.push(part);- more = part.pattern && p.charAt((part.pattern || '').length) === ';' ? 1 : 0;- p = p.slice((part.pattern || '').length + more);- i++;- } while (more && i < 4 && conditions < 3);-- // No more than 4 sections and only 2 conditional statements: "1;2;else;txt"- if (conditions > 2) {- throw new Error('Unexpected condition');- }- if (more) {- throw new Error('Unexpected partition');- }-- // if this is not a conditional, then we ensure we have all 4 partitions- if (!conditional) {- // if we have less than 4 partitions - and one of them is .text, use it as the text one- if (partitions.length < 4 && text_partition) {- for (let pi = 0, pl = partitions.length; pi < pl; pi++) {- if (partitions[pi] === text_partition) {- partitions.splice(pi, 1);- }- }- }- // missing positive- if (partitions.length < 1 && text_partition) {- partitions[0] = parsePart('General');- partitions[0].generated = true;- }- // missing negative- if (partitions.length < 2) {- const part = parsePart(partitions[0].pattern || '');- // the volatile minus only happens if there is a single pattern- if (part.tokens) {- part.tokens.unshift({ type: 'minus', volatile: true });- }- part.generated = true;- partitions.push(part);- }- // missing zero- if (partitions.length < 3) {- const part = parsePart(partitions[0].pattern || '');- part.generated = true;- partitions.push(part);- }- // missing text- if (partitions.length < 4) {- if (text_partition) {- partitions.push(text_partition);- } else {- const part = parsePart('@');- part.generated = true;- partitions.push(part);- }- }-- partitions[0].condition = ['>', 0];- partitions[1].condition = ['<', 0];- partitions[2].condition = undefined;- }-- return {- pattern,- partitions,- locale: l10n_override as string | undefined,- };-}--export function parseCatch(pattern: string): PatternType {- try {- return parsePattern(pattern);- } catch (err: unknown) {- const errPart = { tokens: [{ type: 'error' }] };- return {- pattern,- locale: undefined,- partitions: [errPart, errPart, errPart, errPart],- error: (err as Error).message,- };- }-}diff --git a/packages/base-numfmt-engine/src/core/parse-value.ts b/packages/base-numfmt-engine/src/core/parse-value.tsdeleted file mode 100644index 9d026ec365..0000000000--- a/packages/base-numfmt-engine/src/core/parse-value.ts+++ /dev/null@@ -1,512 +0,0 @@-import { dateFromSerial } from './serial-date';--/*-This is a list of the allowed date formats. The test file contains-the full list of permuations and the resulting values and formats.--Legend:- "-" - Date separator (any of "/" | "-" | " " | "."⁽¹⁾ | ", "⁽²⁾)- " " - Whitespace- "j" - Day without leading zero (1-31)- "d" - Day with leading zero (00-31)- "D" - Abbreviated day name ("Sun"-"Sat")- "l" - Full day name ("Sunday"-"Saturday")- "n" - Month without leading zero (1-12)- "m" - Month with leading zero (01-12)- "F" - Full month name ("Janary"-"December")- "M" - Abbreviated month name ("Jan"-"Dec")- "y" - Year without century (00-99)- "Y" - Year of our lord (1900-9999)- "x" - Time of day (all formats: "10 PM", "10:11:12", ...)--¹ Only considered valid if there are three or more sections to the date.-² Comma is only allowed if followed by a space.--Time is appended to each of these as they are inserted into the-collection of valid dates below.-*/-const okDateFormats = [- 'd-F-y',- 'd-F-Y',- 'd-M-y',- 'd-M-Y',- 'F-d-y',- 'F-d-Y',- 'F-j-y',- 'F-j-Y',- 'j-F-y',- 'j-F-Y',- 'j-M-y',- 'j-M-Y',- 'M-d-y',- 'M-d-Y',- 'M-j-y',- 'M-j-Y',- 'm-d-y',- 'm-d-Y',- 'm-j-y',- 'm-j-Y',- 'n-d-y',- 'n-d-Y',- 'n-j-y',- 'n-j-Y',- 'y-F-d',- 'y-F-j',- 'y-M-d',- 'y-M-j',- 'Y-F-d',- 'Y-F-j',- 'Y-M-d',- 'Y-m-d',- 'Y-M-j',- 'Y-m-j',- 'Y-n-d',- 'Y-n-j',- 'M-d',- 'M-j',- 'd-F',- 'd-M',- 'n-d',- 'n-j',- 'j-F',- 'j-M',- 'M-Y',- 'n-Y',- 'm-d',- 'F-d',- 'm-j',- 'F-j',- 'm-Y',- 'F-Y',- 'Y-M',- 'Y-n',- 'Y-m',- 'Y-F',- 'Y-M',-];--// date formats are stored as a token-tree in a trie-// for minimal looping and branching while parsing-const dateTrie = {};-function packDate(f: any, node: { [key: string]: any }) {- if (f) {- const char = f[0];- node[char] = node[char] || {};- packDate(f.slice(1), node[char]);- } else {- node.$ = true;- }-}-okDateFormats.forEach((fmt: any) => {- // add date to token tree- packDate(fmt, dateTrie);- // add a variant of the date with time suffixed- // Excel allows time first, but Sheets and GRID do not- packDate(`${fmt} x`, dateTrie);- // add a variant of the date with weekdats pre/suffixed- packDate(`${fmt} l`, dateTrie);- packDate(`${fmt} l x`, dateTrie);- packDate(`l ${fmt}`, dateTrie);- packDate(`l ${fmt} x`, dateTrie);- packDate(`${fmt} D`, dateTrie);- packDate(`${fmt} D x`, dateTrie);- packDate(`D ${fmt}`, dateTrie);- packDate(`D ${fmt} x`, dateTrie);-});--/* eslint-disable object-property-newline */-const monthsM = {- jan: 1,- feb: 2,- mar: 3,- apr: 4,- may: 5,- jun: 6,- jul: 7,- aug: 8,- sep: 9,- oct: 10,- nov: 11,- dec: 12,-};-// note: May is missing here, it is always parsed as M-const monthsF = {- january: 1,- february: 2,- march: 3,- april: 4,- june: 6,- july: 7,- august: 8,- september: 9,- october: 10,- november: 11,- december: 12,-};-const days = {- sunday: 'l',- monday: 'l',- tuesday: 'l',- wednesday: 'l',- thursday: 'l',- friday: 'l',- saturday: 'l',- sun: 'D',- mon: 'D',- tue: 'D',- wed: 'D',- thu: 'D',- fri: 'D',- sat: 'D',-};-/* eslint-enable */--const currentYear = new Date().getUTCFullYear();--export function parseNumber(str: string) {- // this horrifying expression assumes that we only need #,###.### and never #.###,###- const parts = /^([\s+%$(-]*)(((?:(?:\d[\d,]*)(?:\.\d*)?|(?:\.\d+)))([eE][+-]?\d+)?)([\s%$)]*)$/.exec(str);- if (parts) {- const [, prefix, number, numpart, exp, suffix] = parts;- let sign = 1;- let format = '';- let minus = false;- let openParen = false;- let closeParen = false;- let percent = false;- let dollar = false;- let dollarTailing = false;- let value = parseFloat(number.replace(/,/g, ''));- // is number ok?- if (!isFinite(value)) {- return null;- }- // is prefix ok?- for (let i = 0; i < prefix.length; i++) {- const char = prefix[i];- // only 1 occurance of these is allowed- if (char === '-') {- if (minus || openParen) {- return null;- }- minus = true;- sign = -1;- } else if (char === '$') {- if (dollar) {- return null;- }- dollar = true;- } else if (char === '(') {- if (openParen || minus) {- return null;- }- openParen = true;- sign = -1;- } else if (char === '%') {- if (percent) {- return null;- }- percent = true;- }- }- // is suffix ok?- for (let i = 0; i < suffix.length; i++) {- const char = suffix[i];- // only 1 occurance of these is allowed- if (char === '$') {- if (dollar) {- return null;- }- dollar = true;- dollarTailing = true;- } else if (char === ')') {- if (closeParen || !openParen) {- return null;- }- closeParen = true;- } else if (char === '%') {- if (percent) {- return null;- }- percent = true;- }- }- if (exp) {- if (percent || dollar) {- return null;- }- // allow parens and minus, but not %$- format = '0.00E+00';- } else if (percent) {- if (dollar) {- // Sheets allows this: $123% => $1.23 (Excel does not)- return null;- }- // numpart dictates how "deep" the format is: "0" vs "0.00"- format = numpart.includes('.') ? '0.00%' : '0%';- value *= 0.01;- } else if (dollar) {- // numpart dictates how "deep" the format is: "0" vs "0.00"- if (dollarTailing) {- format = numpart.includes('.') ? '#,##0.00$' : '#,##0$';- } else {- format = numpart.includes('.') ? '$#,##0.00' : '$#,##0';- }- } else if (numpart.includes(',')) {- format = numpart.includes('.') ? '#,##0.00' : '#,##0';- }- // we may want to lower the fidelity of the number: +p.value.toFixed(13)- const ret = { v: value * sign, z: '' };- if (format) {- ret.z = format;- }- return ret;- }-}--export function isValidDate(y: number, m: number, d: number) {- // day can't be 0- if (d < 1) {- return false;- }- // month must be 1-12- if (m < 1 || m > 12) {- return false;- }- // february- if (m === 2) {- const isLeapYear = (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;- // 1900 is a leap year in Excel- const febDays = isLeapYear || y === 1900 ? 29 : 28;- if (d > febDays) {- return false;- }- }- // test any other month- else if (- ((m === 4 || m === 6 || m === 9 || m === 11) && d > 30) ||- ((m === 1 || m === 3 || m === 5 || m === 7 || m === 8 || m === 10 || m === 12) && d > 31)- ) {- return false;- }- return true;-}--const nextToken = (str: string, node: any, data: any): any => {- const path = data.path || '';- const matchOrder = Object.keys(node);- for (let i = 0; i < matchOrder.length; i++) {- let r;- const t: any = matchOrder[i];- if (!node[t]) {- continue;- }- if (t === '$') {- // if string is done, then we can return- if (!str) {- r = data;- }- } else if (t === '-') {- const m = /^(\s*([./-]|,\s)\s*|\s+)/.exec(str);- if (m) {- // const sep = (!m[1] || m[1] === '.' || m[1] === ',') ? ' ' : m[0].trim();- const sep = m[1] === '-' || m[1] === '/' || m[1] === '.' ? m[1] : ' ';- // don't allow mixing date separators- if (!data.sep || data.sep === sep) {- const s = m[0].replace(/\s+/g, ' ');- r = nextToken(str.slice(m[0].length), node[t], { ...data, sep, path: path + s });- // r = nextToken(str.slice(m[0].length), node[t], { ...data, sep, path: path + sep });- }- }- } else if (t === ' ') {- const m = /^[,.]?\s+/.exec(str);- if (m) {- const s = m[0].replace(/\s+/g, ' ');- r = nextToken(str.slice(m[0].length), node[t], { ...data, path: path + s });- }- } else if (t === 'j' || t === 'd') {- const m = /^(0?[1-9]|1\d|2\d|3[01])\b/.exec(str);- if (m) {- r = nextToken(str.slice(m[0].length), node[t], { ...data, day: m[0], path: path + t });- }- } else if (t === 'n' || t === 'm') {- const m = /^(0?[1-9]|1[012])\b/.exec(str);- if (m) {- r = nextToken(str.slice(m[0].length), node[t], {- ...data,- month: +m[0],- _mon: m[0],- path: path + t,- });- }- } else if (t === 'F' || t === 'M') {- const m: any = /^([a-z]{3,9})\b/i.exec(str);- const v: string = m && (t === 'F' ? (monthsF as any) : monthsM)[m[0].toLowerCase()];- if (v) {- r = nextToken(str.slice(m[0].length), node[t], {- ...data,- month: v,- _mon: m[0],- path: path + t,- });- }- } else if (t === 'l' || t === 'D') {- const m: any = /^([a-z]{3,9})\b/i.exec(str);- const v = m && (days as any)[m[0].toLowerCase()];- if (v === t) {- // the value is ignored- r = nextToken(str.slice(m[0].length), node[t], { ...data, path: path + t });- }- } else if (t === 'y') {- const m = /^\d\d\b/.exec(str);- if (m) {- const y = +m[0] >= 30 ? +m[0] + 1900 : +m[0] + 2000;- r = nextToken(str.slice(m[0].length), node[t], { ...data, year: y, path: path + t });- }- } else if (t === 'Y') {- const m = /^\d\d\d\d\b/.exec(str);- if (m) {- r = nextToken(str.slice(m[0].length), node[t], { ...data, year: +m[0], path: path + t });- }- } else if (t === 'x') {- const time = parseTime(str);- if (time) {- r = nextToken('', node[t], {- ...data,- time: time.v,- tf: time.z,- path: path + t,- });- }- } else {- throw new Error(`Unknown date token "${t}"`);- }- if (r) {- return r;- }- }-};--export function parseDate(str: string, opts: any) {- if (!str) return null;- // possible shortcut: quickly dismiss if there isn't a number?- const date = nextToken(str.trim(), dateTrie, { path: '' });- if (date) {- // disallow matches where two tokens are separated by a period- if (date.sep === '.' && date.path.length === 3) {- return null;- }- const year = +(date.year ?? currentYear);- if (!date.day) {- date.day = 1;- }- // don't allow input of 31st apr, or 29th feb on non-leap years- if (!isValidDate(year, date.month, date.day)) {- return null;- }- let epoch = -Infinity;- if (year < 1900) {- return null;- }- if (year <= 1900 && date.month <= 2) {- epoch = 25568;- } else if (year < 10000) {- epoch = 25569;- }- const value = Date.UTC(year, date.month - 1, date.day) / 864e5 + epoch + (date.time || 0);- if (value >= 0 && value <= 2958465) {- const lead0 =- // either has a leading zero- date._mon[0] === '0' ||- date.day[0] === '0' ||- // both are 2-digits long- (date._mon.length === 2 && date.day.length === 2);- // console.error(date.path);- const format = date.path.replace(/[jdlDnmMFyYx-]/g, (a: string) => {- if (a === 'j' || a === 'd') {- return lead0 ? 'dd' : 'd';- }- if (a === 'D') {- return 'ddd';- }- if (a === 'l') {- return 'dddd';- }- if (a === 'n' || a === 'm') {- return lead0 ? 'mm' : 'm';- }- if (a === 'M') {- return 'mmm';- }- if (a === 'F') {- return 'mmmm';- }- if (a === 'y') {- return 'yy';- }- if (a === 'x') {- return date.tf || '';- }- if (a === 'Y') {- return 'yyyy';- }- return a;- });- if (opts && opts.nativeDate) {- return { v: dateFromSerial(value, opts), z: format };- }- return { v: value, z: format };- }- }- return null;-}--export function parseTime(str: string) {- const parts = /^\s*([10]?\d|2[0-4])(?::([0-5]\d|\d))?(?::([0-5]\d|\d))?(\.\d{1,10})?(?:\s*([AP])M?)?\s*$/i.exec(- str- );- if (parts) {- const [, h, m, s, f, am] = parts;- // don't allow milliseconds without seconds- if (f && !s) {- return null;- }- // single number must also include AM/PM part- if (!am && !m && !s) {- return null;- }- // AM/PM part must align with hours- let hrs = parseFloat(h) || 0;- if (am) {- // 00:00 AM - 12:00 AM- if (hrs >= 13) {- return null;- }- if (am[0] === 'p' || am[0] === 'P') {- hrs += 12;- }- }- const min = parseFloat(m) || 0;- const sec = parseFloat(s) || 0;- const mss = parseFloat(f) || 0;- return {- v: (hrs * 60 * 60 + min * 60 + sec + mss) / (60 * 60 * 24),- z: `${h.length === 2 ? 'hh' : 'h'}:mm${s ? ':ss' : ''}${am ? ' AM/PM' : ''}`,- };- }- return null;-}--export function parseBool(str: string) {- if (/^\s*true\s*$/i.test(str)) {- return { v: true };- }- if (/^\s*false\s*$/i.test(str)) {- return { v: false };- }- return null;-}--export function parseValue(s: string, opts?: string): any {- return parseNumber(s) ?? parseDate(s, opts) ?? parseTime(s) ?? parseBool(s);-}diff --git a/packages/base-numfmt-engine/src/core/round.ts b/packages/base-numfmt-engine/src/core/round.tsdeleted file mode 100644index 5bbfc1956d..0000000000--- a/packages/base-numfmt-engine/src/core/round.ts+++ /dev/null@@ -1,14 +0,0 @@-// Excel uses symmetric arithmetic rounding-export function round(value: number, places: number = 0): number {- if (typeof value !== 'number') {- return value;- }- if (value < 0) {- return -round(-value, places);- }- if (places) {- const p = 10 ** (places || 0) || 1;- return round(value * p, 0) / p;- }- return Math.round(value);-}diff --git a/packages/base-numfmt-engine/src/core/run-part.ts b/packages/base-numfmt-engine/src/core/run-part.tsdeleted file mode 100644index 95c7d02950..0000000000--- a/packages/base-numfmt-engine/src/core/run-part.ts+++ /dev/null@@ -1,452 +0,0 @@-import { clamp } from './clamp';-import {- _numchars,- EPOCH_1317,- MAX_L_DATE,- MAX_S_DATE,- MIN_L_DATE,- MIN_S_DATE,- u_CSEC,- u_DSEC,- u_HOUR,- u_MIN,- u_MSEC,- u_SEC,-} from './constants';-import { dec2frac } from './dec2frac';-import { general } from './general';-import { defaultLocale, LocaleData } from './locale';-import { OptionsData } from './options';-import { PartType } from './parse-part';-import { round } from './round';-import { toYMD } from './to-ymd';--const short_to_long = {- int: 'integer',- frac: 'fraction',- man: 'mantissa',- num: 'numerator',- den: 'denominator',-};-const DAYSIZE = 86400;--/**- * @param value- * @param bigRange- * @returns- */-const dateOverflows = (value: number, bigRange: any) => {- if (bigRange) {- return value < MIN_L_DATE || value >= MAX_L_DATE;- }- return value < MIN_S_DATE || value >= MAX_S_DATE;-};--/**- *- * @param value- * @param part- * @param opts- * @param l10n_- */-export function runPart(value: number, part: PartType | any, opts: OptionsData, l10n_: LocaleData): any {- let mantissa = '';- let numerator = '';- let denominator = '';- let fraction = '';- let integer = '';- let exp = 0;-- let date = value | 0;- let time = 0;- let year = 0;- let month = 1;- let day = 0;- let weekday = 0;- let hour = 0;- let minute = 0;- let second = 0;- let subsec = 0;-- const l10n: any = l10n_ || defaultLocale;-- // scale number- if (!part.text && isFinite(part.scale) && part.scale !== 1) {- value = clamp(value * part.scale);- }- // calc exponent- if (part.exponential) {- let v = Math.abs(value);- if (v) {- exp = Math.round(Math.log10(v));- }- if (part.int_max > 1) {- exp = Math.floor(exp / part.int_max) * part.int_max;- }- v = exp < 0 ? v * 10 ** -exp : v / 10 ** exp;- value = value < 0 ? -v : v;- mantissa += Math.abs(exp);- }- // integer to text- if (part.integer) {- const i = Math.abs(round(value, part.fractions ? 1 : part.frac_max));- integer += i < 1 ? '' : Math.floor(i);- }-- // grouping- if (part.grouping) {- let gtmp = '';- let ipos = integer.length;- if (ipos > part.group_pri) {- ipos -= part.group_pri;- gtmp = l10n.group + integer.slice(ipos, ipos + part.group_pri) + gtmp;- }- while (ipos > part.group_sec) {- ipos -= part.group_sec;- gtmp = l10n.group + integer.slice(ipos, ipos + part.group_sec) + gtmp;- }- integer = ipos ? integer.slice(0, ipos) + gtmp : gtmp;- }-- // fraction to text- if (part.dec_fractions) {- fraction = String(round(value, part.frac_max)).split('.')[1] || '';- }-- // using vulgar fractions- let have_fraction = false;- if (part.fractions) {- const _dec = Math.abs(part.integer ? value % 1 : value);- if (_dec) {- have_fraction = true;- if (isFinite(part.denominator)) {- // predefined denominator- denominator += part.denominator;- numerator += round(_dec * part.denominator);- if (numerator === '0') {- numerator = '';- denominator = '';- have_fraction = false;- if (!integer) {- integer = '0';- }- }- } else {- const nmax = part.integer ? part.num_max : Infinity;- const frt = dec2frac(_dec, nmax, part.den_max);- numerator += frt[0];- denominator += frt[1];- if (part.integer) {- if (numerator === '0') {- if (!integer) {- integer = '0';- }- numerator = '';- denominator = '';- have_fraction = false;- }- }- }- }- }-- // using date/time- if (part.date_eval && dateOverflows(value, opts.dateSpanLarge)) {- // if value is out of bounds and formatting is date Excel emits "#########" (full cell)- // this does not happen, if the only date tokens are elapsed time- // This copies the TEXT function which emits a #VALUE! error- if (opts.dateErrorThrows) {- throw new Error('Date out of bounds');- }- if (opts.dateErrorNumber) {- return general([], {}, value, l10n).join('');- }- return opts.overflow;- }- if (part.date) {- date = value | 0;- const t = DAYSIZE * (value - date);- time = Math.floor(t); // in seconds-- // "epsilon" correction- subsec = t - time;- if (Math.abs(subsec) < 1e-6) {- // 0.000001- subsec = 0;- } else if (subsec > 0.9999) {- subsec = 0;- time += 1;- if (time === DAYSIZE) {- time = 0;- date += 1;- }- }-- // serial date/time to gregorian calendar- if (date || part.date_system) {- const dout = toYMD(value, part.date_system, opts.leap1900);- year = dout[0];- month = dout[1];- day = dout[2];- }- if (time || subsec) {- // round time based on smallest used unit- const minU =- part.date & u_MSEC ||- part.date & u_CSEC ||- part.date & u_DSEC ||- part.date & u_SEC ||- part.date & u_MIN ||- part.date & u_HOUR;- if (- (minU === u_MSEC && subsec > 0.9995) ||- (minU === u_CSEC && subsec > 0.995) ||- (minU === u_DSEC && subsec > 0.95) ||- (minU === u_SEC && subsec >= 0.5) ||- (minU === u_MIN && subsec >= 0.5) ||- (minU === u_HOUR && subsec >= 0.5)- ) {- time++;- subsec = 0;- }- const x = time < 0 ? DAYSIZE + time : time;- second = Math.floor(x) % 60;- minute = Math.floor(x / 60) % 60;- hour = Math.floor(x / 60 / 60) % 60;- }- weekday = (6 + date) % 7;- }-- // integer padding- if (part.int_padding) {- integer =- part.int_padding.length === 1- ? integer || part.int_padding- : part.int_padding.substring(0, part.int_padding.length - integer.length) + integer;- }- // numerator padding- if (part.num_padding) {- numerator =- part.num_padding.length === 1- ? numerator || part.num_padding- : part.num_padding.substring(0, part.num_padding.length - numerator.length) + numerator;- }- // denominator padding- if (part.den_padding) {- denominator =- part.den_padding.length === 1- ? denominator || part.den_padding- : denominator + part.den_padding.slice(denominator.length);- }- // mantissa padding- if (part.man_padding) {- const m_sign = part.exp_plus ? '+' : '';- mantissa =- part.man_padding.length === 1- ? (exp < 0 ? '-' : m_sign) + (mantissa || part.man_padding)- : (exp < 0 ? '-' : m_sign) +- part.man_padding.slice(0, part.man_padding.length - mantissa.length) +- mantissa;- }-- const ret = [];- let integer_bits_counter = 0;- const counter: any = {- int: 0,- frac: 0,- man: 0,- num: 0,- den: 0,- };- for (let ti = 0, tl = part.tokens.length; ti < tl; ti++) {- const tok = part.tokens[ti];- const len = tok.num ? tok.num.length : 0;-- if (tok.type === 'string') {- // special rules may apply if next or prev is numerator or denominator- if (tok.rule) {- if (tok.rule === 'num') {- if (have_fraction) {- ret.push(tok.value);- } else if (part.num_min > 0 || part.den_min > 0) {- ret.push(tok.value.replace(/./g, _numchars['?']));- }- } else if (tok.rule === 'num+int') {- if (have_fraction && integer) {- ret.push(tok.value);- } else if (part.den_min > 0 && (integer || part.num_min)) {- ret.push(tok.value.replace(/./g, _numchars['?']));- }- } else if (tok.rule === 'den') {- if (have_fraction) {- ret.push(tok.value);- } else if (part.den_min > 0 || part.den_min > 0) {- ret.push(tok.value.replace(/./g, _numchars['?']));- }- }- } else {- ret.push(tok.value);- }- } else if (tok.type === 'error') {- // token used to define invalid pattern- ret.push(opts.invalid);- } else if (tok.type === 'point') {- // Excel always emits a period: TEXT(0, "#.#") => "."- ret.push(part.date ? tok.value : l10n.decimal);- } else if (tok.type === 'general') {- general(ret, part, value, l10n);- } else if (tok.type === 'exp') {- ret.push(l10n.exponent);- } else if (tok.type === 'minus') {- if (tok.volatile && part.date) {- // don't emit the prepended minus if this is a date- } else if (tok.volatile && !part.fractions && (part.integer || part.dec_fractions)) {- // minus is only shown if there is a non-zero digit present- if ((integer && integer !== '0') || fraction) {- ret.push(l10n.negative);- }- } else {- ret.push(l10n.negative);- }- } else if (tok.type === 'plus') {- ret.push(l10n.positive);- } else if (tok.type === 'text') {- ret.push(value);- } else if (tok.type === 'div') {- if (have_fraction) {- ret.push('/');- } else if (part.num_min > 0 || part.den_min > 0) {- ret.push(_numchars['?']);- } else {- ret.push(_numchars['#']);- }- } else if (tok.type === 'int') {- if (part.int_pattern.length === 1) {- // number isn't fragmented- ret.push(integer);- } else {- const c_s = !integer_bits_counter ? Infinity : part.int_pattern.join('').length - counter.int;- const c_e =- integer_bits_counter === part.int_pattern.length - 1- ? 0- : part.int_pattern.join('').length - (counter.int + tok.num.length);- ret.push(integer.substring(integer.length - c_s, integer.length - c_e));- integer_bits_counter++;- counter.int += tok.num.length;- }- } else if (tok.type === 'frac') {- const o = counter.frac;- for (let i = 0; i < len; i++) {- ret.push(fraction[i + o] || _numchars[tok.num[i]]);- }- counter.frac += len;- } else if (tok.type in short_to_long) {- if (part[`${tok.type}_pattern`].length === 1) {- // number isn't fragmented- if (tok.type === 'int') {- ret.push(integer);- }- if (tok.type === 'frac') {- ret.push(fraction);- }- if (tok.type === 'man') {- ret.push(mantissa);- }- if (tok.type === 'num') {- ret.push(numerator);- }- if (tok.type === 'den') {- ret.push(denominator);- }- } else {- ret.push((short_to_long as any)[tok.type].slice(counter[tok.type], counter[tok.type] + len));- counter[tok.type] += len;- }- } else if (tok.type === 'year') {- if (year < 0) {- ret.push(l10n.negative);- }- ret.push(String(Math.abs(year)).padStart(4, '0'));- } else if (tok.type === 'year-short') {- const y = year % 100;- ret.push(y < 10 ? '0' : '', y);- } else if (tok.type === 'month') {- ret.push(tok.pad && month < 10 ? '0' : '', month);- } else if (tok.type === 'monthname-single') {- // This is what Excel does.- // The Vietnamese list goes from ["Tháng 1", "Tháng 2", ... ] to [ "T", "T", ... ]- // Simplified Chinese goes from [ 1月, ... 9月, 10月, 11月, 12月 ] to [ 1, ... 9, 1, 1, 1 ]- if (part.date_system === EPOCH_1317) {- ret.push(l10n.mmmm6[month - 1].charAt(0));- } else {- ret.push(l10n.mmmm[month - 1].charAt(0));- }- } else if (tok.type === 'monthname-short') {- if (part.date_system === EPOCH_1317) {- ret.push(l10n.mmm6[month - 1]);- } else {- ret.push(l10n.mmm[month - 1]);- }- } else if (tok.type === 'monthname') {- if (part.date_system === EPOCH_1317) {- ret.push(l10n.mmmm6[month - 1]);- } else {- ret.push(l10n.mmmm[month - 1]);- }- } else if (tok.type === 'weekday-short') {- ret.push(l10n.ddd[weekday]);- } else if (tok.type === 'weekday') {- ret.push(l10n.dddd[weekday]);- } else if (tok.type === 'day') {- ret.push(tok.pad && day < 10 ? '0' : '', day);- } else if (tok.type === 'hour') {- const h = hour % part.clock || (part.clock < 24 ? part.clock : 0);- ret.push(tok.pad && h < 10 ? '0' : '', h);- } else if (tok.type === 'min') {- ret.push(tok.pad && minute < 10 ? '0' : '', minute);- } else if (tok.type === 'sec') {- ret.push(tok.pad && second < 10 ? '0' : '', second);- } else if (tok.type === 'subsec') {- ret.push(l10n.decimal);- // decimals is pre-determined by longest subsec token- // but the number emitted is per-token- const f = subsec.toFixed(part.sec_decimals);- ret.push(f.slice(2, 2 + tok.decimals));- } else if (tok.type === 'am') {- const idx = hour < 12 ? 0 : 1;- if (tok.short && !l10n_) {- ret.push('AP'[idx]);- } else {- ret.push(l10n.ampm[idx]);- }- } else if (tok.type === 'hour-elap') {- if (value < 0) {- ret.push(l10n.negative);- }- const hh = date * 24 + Math.floor(Math.abs(time) / (60 * 60));- ret.push(String(Math.abs(hh)).padStart(tok.pad, '0'));- } else if (tok.type === 'min-elap') {- if (value < 0) {- ret.push(l10n.negative);- }- const mm = date * 1440 + Math.floor(Math.abs(time) / 60);- ret.push(String(Math.abs(mm)).padStart(tok.pad, '0'));- } else if (tok.type === 'sec-elap') {- if (value < 0) {- ret.push(l10n.negative);- }- const ss = date * DAYSIZE + Math.abs(time);- ret.push(String(Math.abs(ss)).padStart(tok.pad, '0'));- } else if (tok.type === 'b-year') {- ret.push(year + 543);- } else if (tok.type === 'b-year-short') {- const y = (year + 543) % 100;- ret.push(y < 10 ? '0' : '', y);- }- }- if (opts.nbsp) {- // can we detect ? or string tokens and only do this if needed?- return ret.join('');- }- return ret.join('').replace(/\u00a0/g, ' ');-}diff --git a/packages/base-numfmt-engine/src/core/serial-date.ts b/packages/base-numfmt-engine/src/core/serial-date.tsdeleted file mode 100644index 3f66c3636d..0000000000--- a/packages/base-numfmt-engine/src/core/serial-date.ts+++ /dev/null@@ -1,51 +0,0 @@-import { toYMD } from './to-ymd';--export function dateToSerial(value: Date | any[], opts?: { ignoreTimezone?: boolean }): number | any[] | Date {- let ts = null;- if (Array.isArray(value)) {- const [y, m, d, hh, mm, ss] = value;- ts = Date.UTC(y, m == null ? 0 : m - 1, d ?? 1, hh || 0, mm || 0, ss || 0);- }- // dates are changed to serial- else if (value instanceof Date) {- ts = value.getTime();- if (!opts || !opts.ignoreTimezone) {- ts -= value.getTimezoneOffset() * 60 * 1000;- }- }- if (ts != null && isFinite(ts)) {- const d = ts / 864e5;- return d - (d <= -25509 ? -25568 : -25569);- }- // everything else is passed through- return value;-}--export function dateFromSerial(value: number, opts?: { leap1900?: boolean; nativeDate?: boolean }): number[] | Date {- let date = value | 0;- const t = 86400 * (value - date);- let time = Math.floor(t); // in seconds- // date "epsilon" correction- if (t - time > 0.9999) {- time += 1;- if (time === 86400) {- time = 0;- date += 1;- }- }- // serial date/time to gregorian calendar- const x = time < 0 ? 86400 + time : time;- const [y, m, d] = toYMD(value, 0, opts && opts.leap1900);- const hh = Math.floor(x / 3600) % 24;- const mm = Math.floor(x / 60) % 60;- const ss = Math.floor(x) % 60;- // return it as a native date object- if (opts && opts.nativeDate) {- const dt = new Date(0);- dt.setUTCFullYear(y, m - 1, d);- dt.setUTCHours(hh, mm, ss);- return dt;- }- // return the parts- return [y, m, d, hh, mm, ss];-}diff --git a/packages/base-numfmt-engine/src/core/to-ymd.ts b/packages/base-numfmt-engine/src/core/to-ymd.tsdeleted file mode 100644index 82aee68fec..0000000000--- a/packages/base-numfmt-engine/src/core/to-ymd.ts+++ /dev/null@@ -1,71 +0,0 @@-import { EPOCH_1317, EPOCH_1904 } from './constants';--const floor = Math.floor;--// https://www.codeproject.com/Articles/2750/Excel-Serial-Date-to-Day-Month-Year-and-Vice-Versa-export function toYMD_1900(ord: number, leap1900 = true) {- if (leap1900 && ord >= 0) {- if (ord === 0) {- return [1900, 1, 0];- }- if (ord === 60) {- return [1900, 2, 29];- }- if (ord < 60) {- return [1900, ord < 32 ? 1 : 2, ((ord - 1) % 31) + 1];- }- }- let l = ord + 68569 + 2415019;- const n = Math.floor((4 * l) / 146097);- l -= Math.floor((146097 * n + 3) / 4);- const i = Math.floor((4000 * (l + 1)) / 1461001);- l = l - Math.floor((1461 * i) / 4) + 31;- const j = Math.floor((80 * l) / 2447);- const nDay = l - Math.floor((2447 * j) / 80);- l = Math.floor(j / 11);- const nMonth = j + 2 - 12 * l;- const nYear = 100 * (n - 49) + i + l;- return [nYear | 0, nMonth | 0, nDay | 0];-}--export function toYMD_1904(ord: number) {- return toYMD_1900(ord + 1462);-}--// https://web.archive.org/web/20080209173858/https://www.microsoft.com/globaldev/DrIntl/columns/002/default.mspx-// > [algorithm] is used in many Microsoft products, including all operating systems that-// > support Arabic locales, Microsoft Office, COM, Visual Basics, VBA, and SQL Server 2000.-export function toYMD_1317(ord: number) {- if (ord === 60) {- throw new Error('#VALUE!');- }- if (ord <= 1) {- return [1317, 8, 29];- }- if (ord < 60) {- return [1317, ord < 32 ? 9 : 10, 1 + ((ord - 2) % 30)];- }- const y = 10631 / 30;- const shift1 = 8.01 / 60;- let z = ord + 466935;- const cyc = Math.floor(z / 10631);- z -= 10631 * cyc;- const j = Math.floor((z - shift1) / y);- z -= Math.floor(j * y + shift1);- const m = Math.floor((z + 28.5001) / 29.5);- if (m === 13) {- return [30 * cyc + j, 12, 30];- }- return [30 * cyc + j, m, z - Math.floor(29.5001 * m - 29)];-}--export function toYMD(ord: number, system = 0, leap1900 = true) {- const int = Math.floor(ord);- if (system === EPOCH_1317) {- return toYMD_1317(int);- }- if (system === EPOCH_1904) {- return toYMD_1904(int);- }- return toYMD_1900(int, leap1900);-}diff --git a/packages/base-numfmt-engine/src/index.ts b/packages/base-numfmt-engine/src/index.tsindex 682130910a..f2b116bfb8 100644--- a/packages/base-numfmt-engine/src/index.ts+++ b/packages/base-numfmt-engine/src/index.ts@@ -1,121 +1,6 @@-import { codeToLocale } from './core/code-to-locale';-import { dec2frac } from './core/dec2frac';-import { color, formatNumber, isDate, isPercent, isText } from './core/format-number';-import { addLocale, getLocale, LocaleData, parseLocale } from './core/locale';-import { options, OptionsData } from './core/options';-import { PartType } from './core/parse-part';-import { parseCatch, parsePattern, PatternType } from './core/parse-pattern';-import { parseBool, parseDate, parseNumber, parseTime, parseValue } from './core/parse-value';-import { round } from './core/round';-import { dateFromSerial, dateToSerial } from './core/serial-date';+// @ts-ignore+import numfmt from 'numfmt';-export interface FormatterType {- pattern: string | undefined;- error: string;- options: (opts?: OptionsData) => {- overflow?: string | undefined;- dateErrorThrows?: boolean | undefined;- dateSpanLarge?: boolean | undefined;- dateErrorNumber?: boolean | undefined;- invalid?: string | undefined;- locale?: string | undefined;- leap1900?: boolean | undefined;- nbsp?: boolean | undefined;- throws?: boolean | undefined;- ignoreTimezone?: boolean | undefined;- };- locale: string;- (value: number | string | null | unknown | void, opts?: OptionsData): string;- color(value: number | string | null | unknown | void, ops?: OptionsData | undefined): string;- isDate(): boolean;- isText(): boolean;- isPercent(): boolean;-}+import type { Numfmt } from './type';-const _cache: { [key: string]: PatternType } = {};--function getFormatter(parseData: PatternType, initOpts: OptionsData = {}): FormatterType {- const { pattern, partitions, locale } = parseData;-- const getRuntimeOptions = (opts: OptionsData = {}) => {- const runOpts = { ...options(), ...initOpts, ...opts };- if (locale) {- runOpts.locale = locale;- }- return runOpts;- };-- const formatter: FormatterType = (value: number | string | null | unknown | void, opts?: OptionsData) => {- if (value) {- const o = getRuntimeOptions(opts);- return formatNumber(dateToSerial(value as any[] | Date, o) as string | number, partitions as PartType[], o);- }- return String();- };- formatter.color = (value, opts = {}) => {- const o = getRuntimeOptions(opts);- return color(dateToSerial(value as any[] | Date, o) as number, partitions as PartType[]);- };- formatter.isPercent = () => isPercent(partitions as PartType[]);- formatter.isDate = () => isDate(partitions as PartType[]);- formatter.isText = () => isText(partitions as PartType[]);- formatter.pattern = pattern;- if (parseData.error) {- formatter.error = parseData.error;- }- formatter.options = getRuntimeOptions;- formatter.locale = locale || (initOpts && initOpts.locale) || '';- return Object.freeze(formatter);-}--function numfmt(pattern?: string, opts: OptionsData = {}): FormatterType {- if (!pattern) {- pattern = 'General';- }- let parseData = null;- if (_cache[pattern]) {- parseData = _cache[pattern];- } else {- const constructOpts = { ...options(), ...opts };- parseData = constructOpts.throws ? parsePattern(pattern) : parseCatch(pattern);- if (!parseData.error) {- _cache[pattern] = parseData;- }- }- return getFormatter(parseData, opts);-}--numfmt.isDate = (d: string) => numfmt(d, { throws: false }).isDate();-numfmt.isPercent = (d: string) => numfmt(d, { throws: false }).isPercent();-numfmt.isText = (d: string) => numfmt(d, { throws: false }).isText();--numfmt.dateToSerial = dateToSerial;-numfmt.dateFromSerial = dateFromSerial;-numfmt.options = options;-numfmt.dec2frac = dec2frac;-numfmt.round = round;-numfmt.codeToLocale = codeToLocale;-numfmt.getLocale = getLocale;-numfmt.parseLocale = parseLocale;-numfmt.addLocale = (options: LocaleData, l4e: string) => {- const c = parseLocale(l4e);- // when locale is changed, expire all cached patterns- delete _cache[c.lang || ''];- delete _cache[c.language || ''];- return addLocale(options, c);-};--// SSF interface compatibility-function format(pattern: string | undefined, value: any[] | Date, l4e: any, noThrows = false) {- const opts = l4e && typeof l4e === 'object' ? l4e : { locale: l4e, throws: !noThrows };- return numfmt(pattern, opts)(dateToSerial(value, opts), opts);-}-numfmt.format = format;-numfmt.is_date = numfmt.isDate;-numfmt.parseNumber = parseNumber;-numfmt.parseDate = parseDate;-numfmt.parseTime = parseTime;-numfmt.parseBool = parseBool;-numfmt.parseValue = parseValue;--export { numfmt };+export default numfmt as Numfmt;diff --git a/packages/base-numfmt-engine/src/type.ts b/packages/base-numfmt-engine/src/type.tsnew file mode 100644index 0000000000..6cc0f3962d--- /dev/null+++ b/packages/base-numfmt-engine/src/type.ts@@ -0,0 +1,287 @@+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;+}++type LocaleTag =+ | 'zh-CN'+ | 'zh'+ | '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';++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 Numfmt {+ (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): Date;++ options(op: Partial<Options>): void;+}diff --git a/packages/base-numfmt-engine/src/types/index.d.ts b/packages/base-numfmt-engine/src/types/index.d.tsindex 92ee2e92aa..f19863cb9f 100644--- a/packages/base-numfmt-engine/src/types/index.d.ts+++ b/packages/base-numfmt-engine/src/types/index.d.ts@@ -1,2 +1 @@-export * from '../index';-declare module '@univerjs/base-numfmt-engine' {}+declare module 'numfmt' {}diff --git a/packages/base-numfmt-engine/tsconfig.json b/packages/base-numfmt-engine/tsconfig.jsonindex 9972dfa9b5..1ba7bc8eec 100644--- a/packages/base-numfmt-engine/tsconfig.json+++ b/packages/base-numfmt-engine/tsconfig.json@@ -5,6 +5,7 @@"outDir": "lib","baseUrl": "./","esModuleInterop": true,+ "types": ["./src/types/index.d.ts"]},"include": ["src/**/*",diff --git a/packages/base-render/src/components/sheets/sheet-skeleton.ts b/packages/base-render/src/components/sheets/sheet-skeleton.tsindex a213c97ab8..2183c2408e 100644--- a/packages/base-render/src/components/sheets/sheet-skeleton.ts+++ b/packages/base-render/src/components/sheets/sheet-skeleton.ts@@ -405,7 +405,10 @@ export class SpreadsheetSkeleton extends Skeleton {const { columnCount, columnData, mergeData, defaultRowHeight } = this._config;const data = Tools.createObjectArray(columnData);let height = defaultRowHeight;-+ const worksheet = this._worksheet;+ if (!worksheet) {+ return height;+ }for (let i = 0; i < columnCount; i++) {// When calculating the automatic height of a row, if a cell is in a merged cell,// skip the cell directly, which currently follows the logic of Excel@@ -414,8 +417,8 @@ export class SpreadsheetSkeleton extends Skeleton {if (isMerged || isMergedMainCell) {continue;}-- const modelObject = this._getCellDocumentModel(rowNum, i);+ const cell = worksheet.getCell(rowNum, i);+ const modelObject = cell && this.getCellDocumentModel(cell);if (modelObject == null) {continue;}@@ -971,8 +974,8 @@ export class SpreadsheetSkeleton extends Skeleton {}// Only used for cell edit, and no need to rotate text when edit cell content!- getBlankCellDocumentModel(row: number, column: number, isFull: boolean = true): IDocumentLayoutObject {- const documentModelObject = this._getCellDocumentModel(row, column, undefined, undefined, undefined, true);+ getBlankCellDocumentModel(cell: Nullable<ICellData>, isFull: boolean = true): IDocumentLayoutObject {+ const documentModelObject = this._getCellDocumentModel(cell, undefined, undefined, undefined, true);if (documentModelObject != null) {if (documentModelObject.documentModel == null) {@@ -1006,24 +1009,22 @@ export class SpreadsheetSkeleton extends Skeleton {};}- getCellDocumentModel(row: number, column: number) {- return this._getCellDocumentModel(row, column);+ getCellDocumentModel(cell: ICellData) {+ return this._getCellDocumentModel(cell);}// Only used for cell edit, and no need to rotate text when edit cell content!- getCellDocumentModelWithFormula(row: number, column: number) {- return this._getCellDocumentModel(row, column, true, true, true, true);+ getCellDocumentModelWithFormula(cell: ICellData) {+ return this._getCellDocumentModel(cell, true, true, true, true);}private _getCellDocumentModel(- row: number,- column: number,+ cell: Nullable<ICellData>,isFull: boolean = false,isDeepClone: boolean = false,formulaFirst: boolean = false,ignoreTextRotation: boolean = false): Nullable<IDocumentLayoutObject> {- const cell = this._cellData.getValue(row, column);const style = this._styles.getStyleByCell(cell);if (!cell) {@@ -1296,7 +1297,7 @@ export class SpreadsheetSkeleton extends Skeleton {const columnCount = this._columnWidthAccumulation.length - 1;for (let i = startColumn; i >= endColumn; i--) {const column = i;- const cell = this._cellData.getValue(row, column);+ const cell = this._worksheet?.getCell(row, column);if ((!isEmptyCell(cell) && column !== startColumn) || this.intersectMergeRange(row, column)) {if (column === startColumn) {return column;@@ -1325,7 +1326,7 @@ export class SpreadsheetSkeleton extends Skeleton {}for (let i = startColumn; i <= endColumn; i++) {const column = i;- const cell = this._cellData.getValue(row, column);+ const cell = this._worksheet?.getCell(row, column);if ((!isEmptyCell(cell) && column !== startColumn) || this.intersectMergeRange(row, column)) {if (column === startColumn) {return column;@@ -1485,7 +1486,7 @@ export class SpreadsheetSkeleton extends Skeleton {this._setBorderProps(r, c, BORDER_TYPE.RIGHT, style, cache);}- const modelObject = this._getCellDocumentModel(r, c);+ const modelObject = cell && this.getCellDocumentModel(cell);if (modelObject == null) {return;diff --git a/packages/base-sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/clear-selection.command.spec.tsindex 83268c1172..afd9fd1870 100644--- a/packages/base-sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts+++ b/packages/base-sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts@@ -149,7 +149,7 @@ describe('Test clear selection content commands', () => {expect(await commandService.executeCommand(ClearSelectionFormatCommand.id)).toBeTruthy();expect(getValue()).toStrictEqual({v: 'A1',- t: 0,+ t: 4,});// undo@@ -161,7 +161,7 @@ describe('Test clear selection content commands', () => {expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();expect(getValue()).toStrictEqual({v: 'A1',- t: 0,+ t: 4,});});it('clear formats with merged cells', async () => {@@ -228,7 +228,7 @@ describe('Test clear selection content commands', () => {// clear formatsexpect(getValue()).toStrictEqual({v: 'A1',- t: 0,+ t: 4,});// remove mergeexpect(getMerge()).toStrictEqual([]);@@ -245,7 +245,7 @@ describe('Test clear selection content commands', () => {expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();expect(getValue()).toStrictEqual({v: 'A1',- t: 0,+ t: 4,});expect(getMerge()).toStrictEqual([]);});diff --git a/packages/base-sheets/src/commands/commands/set-range-values.command.ts b/packages/base-sheets/src/commands/commands/set-range-values.command.tsindex 0b5477d28b..169d14af19 100644--- a/packages/base-sheets/src/commands/commands/set-range-values.command.ts+++ b/packages/base-sheets/src/commands/commands/set-range-values.command.ts@@ -111,7 +111,7 @@ export const SetRangeValuesCommand: ICommand = {params: { ...setRangeValuesMutationParams, range: currentSelections },});- const result = sequenceExecute([...redos], commandService);+ const result = await sequenceExecute([...redos], commandService);if (setValueMutationResult && result.result) {undoRedoService.pushUndoRedo({diff --git a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.tsindex 33705c5d8e..2a5985e2aa 100644--- a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts+++ b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts@@ -151,6 +151,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bocellMatrix?.setValue(row, col, {});} else {const oldVal = cellMatrix.getValue(row, col) || {};+ const type = newVal.t ? newVal.t : checkCellValueType(newVal.v);if (newVal.f !== undefined) {oldVal.f = newVal.f;@@ -166,7 +167,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo// Set to null, clear contentif (newVal.v !== undefined) {- oldVal.v = newVal.v;+ oldVal.v = type === CellValueType.NUMBER ? Number(newVal.v) : newVal.v;oldVal.m = String(oldVal.v);}@@ -177,7 +178,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, boif (newVal.t !== undefined) {oldVal.t = newVal.t;} else if (oldVal.v !== undefined) {- oldVal.t = checkCellValueType(oldVal.v);+ oldVal.t = type;}// handle style@@ -224,6 +225,9 @@ function checkCellValueType(v: Nullable<ICellV>): Nullable<CellValueType> {if (v === null) return null;if (typeof v === 'string') {+ if (isNumeric(v)) {+ return CellValueType.NUMBER;+ }return CellValueType.STRING;}if (typeof v === 'number') {@@ -374,3 +378,7 @@ export function mergeRichTextStyle(p: IDocumentData, newStyle: Nullable<IStyleDa}});}++function isNumeric(str: string) {+ return /^-?\d+(\.\d+)?$/.test(str);+}diff --git a/packages/base-ui/src/services/sidebar/desktop-sidebar.service.ts b/packages/base-ui/src/services/sidebar/desktop-sidebar.service.tsindex 3974c39ccc..8b0e05001c 100644--- a/packages/base-ui/src/services/sidebar/desktop-sidebar.service.ts+++ b/packages/base-ui/src/services/sidebar/desktop-sidebar.service.ts@@ -27,8 +27,8 @@ export class DesktopSidebarService implements ISidebarService {...this.sidebarOptions,visible: false,};-this.sidebarOptions$.next(this.sidebarOptions);+ this.sidebarOptions.onClose && this.sidebarOptions.onClose();}getObservableSidebar() {diff --git a/packages/base-ui/src/views/components/doc-bars/Button/index.module.less b/packages/base-ui/src/views/components/doc-bars/Button/index.module.lessindex 75eacb9590..4632543d38 100644--- a/packages/base-ui/src/views/components/doc-bars/Button/index.module.less+++ b/packages/base-ui/src/views/components/doc-bars/Button/index.module.less@@ -7,7 +7,7 @@align-items: center;justify-content: center;- width: @toolbar-btn-size;+ min-width: @toolbar-btn-size;height: @toolbar-btn-size;padding: 0;diff --git a/packages/base-ui/src/views/components/doc-bars/ToolbarItem.tsx b/packages/base-ui/src/views/components/doc-bars/ToolbarItem.tsxindex 3991457e62..7c7de250a4 100644--- a/packages/base-ui/src/views/components/doc-bars/ToolbarItem.tsx+++ b/packages/base-ui/src/views/components/doc-bars/ToolbarItem.tsx@@ -5,6 +5,7 @@ import { useDependency } from '@wendellhu/redi/react-bindings';import React, { useEffect, useState } from 'react';import { Subscription } from 'rxjs';+import { ComponentManager } from '../../../common/component-manager';import { CustomLabel } from '../../../components/custom-label/CustomLabel';import { Menu } from '../../../components/menu/Menu';import {@@ -45,14 +46,12 @@ export function ToolbarItem(props: IDisplayMenuItem<IMenuItem>) {);}- if (props.type === MenuItemType.SELECTOR) {- props.value$ &&- subscriptions.push(- props.value$.subscribe((value) => {- setValue(value);- })- );- }+ props.value$ &&+ subscriptions.push(+ props.value$.subscribe((value) => {+ setValue(value);+ })+ );return () => {subscriptions.forEach((subscription) => {@@ -106,6 +105,9 @@ export function ToolbarItem(props: IDisplayMenuItem<IMenuItem>) {}function renderButtonType() {+ const componentManager = useDependency(ComponentManager);+ const isCustomComponent = componentManager.get(typeof label === 'string' ? label : label?.name ?? '');+return (<ToolbarButtonclassName={styles.toolbarItemTextButton}@@ -114,7 +116,11 @@ export function ToolbarItem(props: IDisplayMenuItem<IMenuItem>) {onClick={() => commandService.executeCommand(props.id)}onDoubleClick={() => props.subId && commandService.executeCommand(props.subId)}>- <CustomLabel icon={icon} />+ {isCustomComponent ? (+ <CustomLabel title={title!} value={value} label={label} />+ ) : (+ <CustomLabel icon={icon} />+ )}</ToolbarButton>);}diff --git a/packages/base-ui/src/views/components/sidebar/Sidebar.tsx b/packages/base-ui/src/views/components/sidebar/Sidebar.tsxindex 8dafc40426..129fe29ff9 100644--- a/packages/base-ui/src/views/components/sidebar/Sidebar.tsx+++ b/packages/base-ui/src/views/components/sidebar/Sidebar.tsx@@ -56,9 +56,9 @@ export function Sidebar() {};setSidebarOptions(options);-const sidebar$ = sidebarService.getObservableSidebar();sidebar$.next(options);+ options?.onClose?.();}return (diff --git a/packages/core/src/services/locale/locale.service.ts b/packages/core/src/services/locale/locale.service.tsindex 6db0b3da3d..b9280ffd08 100644--- a/packages/core/src/services/locale/locale.service.ts+++ b/packages/core/src/services/locale/locale.service.ts@@ -55,11 +55,11 @@ export class LocaleService extends Disposable {this.locales = Tools.deepMerge(this.locales ?? {}, locales);}- t(key: string): string {+ t = (key: string): string => {if (!this.locales) throw new Error('Locale not initialized');return getValue(this.locales[this.currentLocale], key) ?? key;- }+ };setLocale(locale: LocaleType): void {this.currentLocale = locale;diff --git a/packages/core/src/services/sheet-interceptor/interceptor-const.ts b/packages/core/src/services/sheet-interceptor/interceptor-const.tsindex 758f7b2dff..43d62daa00 100644--- a/packages/core/src/services/sheet-interceptor/interceptor-const.ts+++ b/packages/core/src/services/sheet-interceptor/interceptor-const.ts@@ -5,7 +5,7 @@ import { createInterceptorKey } from './utils/interceptor';const CELL_CONTENT = createInterceptorKey<ICellData, ISheetLocation>('CELL_CONTENT');const BEFORE_CELL_EDIT = createInterceptorKey<ICellData, ISheetLocation>('BEFORE_CELL_EDIT');-const AFTER_CELL_EDIT = createInterceptorKey<ICellData>('AFTER_CELL_EDIT');+const AFTER_CELL_EDIT = createInterceptorKey<ICellData, ISheetLocation>('AFTER_CELL_EDIT');const PERMISSION = createInterceptorKey<boolean, ICommandInfo>('PERMISSION');export const INTERCEPTOR_POINT = {diff --git a/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts b/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.tsindex 556a4ee321..644a01f399 100644--- a/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts+++ b/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts@@ -68,6 +68,16 @@ export class SheetInterceptorService extends Disposable {priority: -1,handler: () => true,});++ this.intercept(INTERCEPTOR_POINT.BEFORE_CELL_EDIT, {+ priority: -1,+ handler: (_value) => _value,+ });++ this.intercept(INTERCEPTOR_POINT.AFTER_CELL_EDIT, {+ priority: -1,+ handler: (_value) => _value,+ });}override dispose(): void {@@ -122,7 +132,7 @@ export class SheetInterceptorService extends Disposable {fetchThroughInterceptors<T, C>(name: IInterceptor<T, C>) {const key = name as unknown as string;const interceptors = this._interceptorsByName.get(key) as unknown as Array<typeof name>;- return composeInterceptors<T>(interceptors || []);+ return composeInterceptors<T, C>(interceptors || []);}private _interceptWorkbook(workbook: Workbook): void {diff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.tsindex 361a68b202..9041e029af 100644--- a/packages/core/src/shared/object-matrix.ts+++ b/packages/core/src/shared/object-matrix.ts@@ -133,6 +133,11 @@ export class ObjectMatrix<T> {objectArray.set(column, value as T);}+ /**+ * !!+ * Please +1 ‘!’, who fell into this pit.+ * @deprecated use `realDelete` or `splice`+ */deleteValue(row: number, column: number): void {const objectArray = this.getRow(row);if (objectArray) {diff --git a/packages/core/src/types/enum/text-style.ts b/packages/core/src/types/enum/text-style.tsindex 8d0df2f65a..6006631158 100644--- a/packages/core/src/types/enum/text-style.ts+++ b/packages/core/src/types/enum/text-style.ts@@ -121,7 +121,7 @@ export enum BooleanNumber {* General Boolean Enum*/export enum CellValueType {- STRING,+ STRING = 1,NUMBER,BOOLEAN,FORCE_STRING,diff --git a/packages/sheets-plugin-numfmt/package.json b/packages/sheets-plugin-numfmt/package.jsonindex 3e750ce338..0896967f2f 100644--- a/packages/sheets-plugin-numfmt/package.json+++ b/packages/sheets-plugin-numfmt/package.json@@ -1,7 +1,7 @@{"name": "@univerjs/sheets-plugin-numfmt","version": "0.0.1",- "description": "UniverSheet normal plugin UI manager",+ "description": "UniverSheet numfmt plugin","keywords": [],"author": "DreamNum <[email protected]>","license": "MIT",@@ -52,9 +52,12 @@"@univerjs/base-sheets": "workspace:*","@univerjs/base-ui": "workspace:*","@univerjs/core": "workspace:*",+ "@univerjs/icons": "^0.1.12","@univerjs/design": "workspace:*","@univerjs/ui-plugin-sheets": "workspace:*",- "@wendellhu/redi": "^0.12.11"+ "@wendellhu/redi": "^0.12.11",+ "react": "^18.2.0",+ "rxjs": "^7.8.1"},"devDependencies": {"@types/react": "^18.2.38",diff --git a/packages/sheets-plugin-numfmt/src/__tests__/date.test.ts b/packages/sheets-plugin-numfmt/src/__tests__/date.test.tsnew file mode 100644index 0000000000..e1801e37be--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/__tests__/date.test.ts@@ -0,0 +1,15 @@+import numfmt from '@univerjs/base-numfmt-engine';+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-plugin-numfmt/src/__tests__/utils.test.ts b/packages/sheets-plugin-numfmt/src/__tests__/utils.test.tsnew file mode 100644index 0000000000..91b02822c0--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/__tests__/utils.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';++import { currencySymbols } from '../base/const/CURRENCY-SYMBOLS';+import { getCurrencyType } from '../utils/currency';+import {+ getDecimalFromPattern,+ getDecimalString,+ isPatternEqualWithoutDecimal,+ setPatternDecimal,+} from '../utils/decimal';++describe('test numfmt utils function', () => {+ it('getCurrencyType', () => {+ expect(getCurrencyType(`_(${currencySymbols[3]} 123123`)).toBe(currencySymbols[3]);+ expect(getCurrencyType(`_(# 123123`)).toBeUndefined();+ expect(getCurrencyType(`_(${currencySymbols[3]} 123123 ${currencySymbols[4]}`)).toBe(currencySymbols[3]);+ });+ 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+ });+});diff --git a/packages/sheets-plugin-numfmt/src/base/const/CURRENCY-SYMBOLS.ts b/packages/sheets-plugin-numfmt/src/base/const/CURRENCY-SYMBOLS.tsnew file mode 100644index 0000000000..a50d49b3e7--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/base/const/CURRENCY-SYMBOLS.ts@@ -0,0 +1,29 @@+export const currencySymbols = [+ '¤',+ '$',+ '£',+ '¥',+ '֏',+ '؋',+ '৳',+ '฿',+ '៛',+ '₡',+ '₦',+ '₩',+ '₪',+ '₫',+ '€',+ '₭',+ '₮',+ '₱',+ '₲',+ '₴',+ '₸',+ '₹',+ '₺',+ '₼',+ '₽',+ '₾',+ '₿',+];diff --git a/packages/sheets-plugin-numfmt/src/base/const/FORMATDETAIL.ts b/packages/sheets-plugin-numfmt/src/base/const/FORMATDETAIL.tsnew file mode 100644index 0000000000..529f02e89c--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/base/const/FORMATDETAIL.ts@@ -0,0 +1,105 @@+export const DATEFMTLISG = [+ {+ label: '1930-08-05',+ suffix: 'yyyy-MM-dd',+ },+ {+ label: '1930/08/05',+ suffix: 'yyyy/MM/dd',+ },+ {+ label: '1930年08月05日',+ suffix: 'yyyy"年"MM"月"dd"日"',+ },+ {+ label: '08-05',+ suffix: 'MM-dd',+ },+ {+ label: '8月5日',+ suffix: 'M"月"d"日"',+ },+ {+ label: '13:30:30',+ suffix: 'h:mm:ss',+ },+ {+ label: '13:30',+ suffix: 'h:mm',+ },+ {+ label: '下午01:30',+ suffix: 'A/P hh:mm',+ },+ {+ label: '下午1:30',+ suffix: 'A/P h:mm',+ },+ {+ label: '下午1:30:30',+ suffix: 'A/P h:mm:ss',+ },+ {+ label: '08-05 下午 01:30',+ suffix: 'MM-dd A/P hh:mm',+ },+];++export const NUMBERFORMAT = [+ {+ label: '(1,235)',+ suffix: '#,##0_);(#,##0)',+ },+ {+ label: '(1,235) ',+ suffix: '#,##0_);[Red](#,##0)',+ color: 'red',+ },+ {+ label: '1,234.56',+ suffix: '#,##0.00_);#,##0.00',+ },+ {+ label: '1,234.56',+ suffix: '#,##0.00_);[Red]#,##0.00',+ color: 'red',+ },+ {+ label: '-1,234.56',+ suffix: '#,##0.00_);-#,##0.00',+ },+ {+ label: '-1,234.56',+ suffix: '#,##0.00_);[Red]-#,##0.00',+ color: 'red',+ },+];+export const CURRENCYFORMAT = [+ {+ label: (suffix: string) => `${suffix}1,235`,+ suffix: (suffix: string) => `"${suffix}"#,##0.00_);"${suffix}"#,##0.00`,+ },+ {+ label: (suffix: string) => `${suffix}1,235`,+ suffix: (suffix: string) => `"${suffix}"#,##0.00_);[Red]"${suffix}"#,##0.00`,+ color: 'red',+ },+ {+ label: (suffix: string) => `(${suffix}1,235)`,+ suffix: (suffix: string) => `"${suffix}"#,##0.00_);("${suffix}"#,##0.00)`,+ },+ {+ label: (suffix: string) => `(${suffix}1,235)`,+ suffix: (suffix: string) => `"${suffix}"#,##0.00_);[Red]("${suffix}"#,##0.00)`,+ color: 'red',+ },+ {+ label: (suffix: string) => `-${suffix}1,235`,+ suffix: (suffix: string) => `"${suffix}"#,##0.00_);-"${suffix}"#,##0.00`,+ },+ {+ label: (suffix: string) => `-${suffix}1,235`,+ suffix: (suffix: string) => `"${suffix}"#,##0.00_);[Red]-"${suffix}"#,##0.00`,+ color: 'red',+ },+];diff --git a/packages/sheets-plugin-numfmt/src/base/const/PLUGIN_NAME.ts b/packages/sheets-plugin-numfmt/src/base/const/PLUGIN_NAME.tsnew file mode 100644index 0000000000..01c76f42ef--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/base/const/PLUGIN_NAME.ts@@ -0,0 +1 @@+export const SHEET_NUMFMT_PLUGIN = 'SHEET_NUMFMT_PLUGIN';diff --git a/packages/sheets-plugin-numfmt/src/base/types/index.ts b/packages/sheets-plugin-numfmt/src/base/types/index.tsnew file mode 100644index 0000000000..9be354fe95--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/base/types/index.ts@@ -0,0 +1,24 @@+export type BusinessComponentProps = {+ onChange: (result: string) => void;+ defaultValue: number;+ defaultPattern: string;+};+export interface NumfmtItem {+ pattern: string;+ type: FormatType;+}++export type FormatType =+ | 'currency'+ | 'date'+ | 'datetime'+ | 'error'+ | 'fraction'+ | 'general'+ | 'grouped'+ | 'number'+ | 'percent'+ | 'scientific'+ | 'text'+ | 'time'+ | 'unknown';diff --git a/packages/sheets-plugin-numfmt/src/basics/const/config.ts b/packages/sheets-plugin-numfmt/src/basics/const/config.tsdeleted file mode 100644index 9217b882a2..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/const/config.ts+++ /dev/null@@ -1,3 +0,0 @@-export const NumfmtConfig = {- show: true,-};diff --git a/packages/sheets-plugin-numfmt/src/basics/const/default-data.ts b/packages/sheets-plugin-numfmt/src/basics/const/default-data.tsdeleted file mode 100644index 56419efa49..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/const/default-data.ts+++ /dev/null@@ -1,175 +0,0 @@-import { NUMFMT_PLUGIN_NAME } from './plugin-name';--export const DEFAULT_DATA = [- {- label: 'defaultFmt.Automatic.text',- value: 'Automatic',- selected: true,- },- {- label: 'defaultFmt.PlainText.text',- value: 'PlainText',- // border: true,- },- {- // label: 'defaultFmt.Number.text',- // suffix: 'defaultFmt.Number.example',- value: 'Number',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Number.text',- suffix: 'defaultFmt.Number.example',- },- },- },- {- // label: 'defaultFmt.Percent.text',- // suffix: 'defaultFmt.Percent.example',- value: 'Percent',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Percent.text',- suffix: 'defaultFmt.Percent.example',- },- },- },- {- // label: 'defaultFmt.Scientific.text',- // suffix: 'defaultFmt.Scientific.example',- value: 'Scientific',- // border: true,- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Scientific.text',- suffix: 'defaultFmt.Scientific.example',- },- },- },- {- // label: 'defaultFmt.Accounting.text',- // suffix: 'defaultFmt.Accounting.example',- value: 'Accounting',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Accounting.text',- suffix: 'defaultFmt.Accounting.example',- },- },- },- {- // label: 'defaultFmt.Thousand.text',- // suffix: 'defaultFmt.Thousand.example',- value: 'Thousand',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Thousand.text',- suffix: 'defaultFmt.Thousand.example',- },- },- },- {- // label: 'defaultFmt.Currency.text',- // suffix: 'defaultFmt.Currency.example',- value: 'Currency',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Currency.text',- suffix: 'defaultFmt.Currency.example',- },- },- },- {- // label: 'defaultFmt.Digit.text',- // suffix: 'defaultFmt.Digit.example',- value: 'Digit',- // border: true,- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Digit.text',- suffix: 'defaultFmt.Digit.example',- },- },- },- {- // label: 'defaultFmt.Date.text',- // suffix: 'defaultFmt.Date.example',- value: 'Date',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Date.text',- suffix: 'defaultFmt.Date.example',- },- },- },- {- // label: 'defaultFmt.Time.text',- // suffix: 'defaultFmt.Time.example',- value: 'Time',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Time.text',- suffix: 'defaultFmt.Time.example',- },- },- },- {- // label: 'defaultFmt.Time24H.text',- // suffix: 'defaultFmt.Time24H.example',- value: 'Time24H',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.Time24H.text',- suffix: 'defaultFmt.Time24H.example',- },- },- },- {- // label: 'defaultFmt.DateTime.text',- // suffix: 'defaultFmt.DateTime.example',- value: 'DateTime',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.DateTime.text',- suffix: 'defaultFmt.DateTime.example',- },- },- },- {- // label: 'defaultFmt.DateTime24H.text',- // suffix: 'defaultFmt.DateTime.example',- value: 'DateTime24H',- label: {- name: `${NUMFMT_PLUGIN_NAME}FormatItem`,- props: {- labelText: 'defaultFmt.DateTime24H.text',- suffix: 'defaultFmt.DateTime.example',- },- },- },-];--export const MORE_FORMATS_SELECTIONS = [- {- label: 'format.moreCurrency',- value: 'currency',- },- {- label: 'format.moreDateTime',- value: 'date',- },- {- label: 'format.moreNumber',- value: 'number',- },-];diff --git a/packages/sheets-plugin-numfmt/src/basics/const/formatdetail.ts b/packages/sheets-plugin-numfmt/src/basics/const/formatdetail.tsdeleted file mode 100644index da04a4945d..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/const/formatdetail.ts+++ /dev/null@@ -1,160 +0,0 @@-export const CURRENCYDETAIL = [- {- locale: 'currencyDetail.RMB',- suffix: '¥',- },- {- locale: 'currencyDetail.USdollar',- suffix: '$',- },- {- locale: 'currencyDetail.EUR',- suffix: '€',- },- {- locale: 'currencyDetail.GBP',- suffix: '£',- },- {- locale: 'currencyDetail.HK',- suffix: '$',- },- {- locale: 'currencyDetail.JPY',- suffix: '¥',- },- {- locale: 'currencyDetail.AlbanianLek',- suffix: 'Lek',- },- {- locale: 'currencyDetail.AlgerianDinar',- suffix: 'din',- },- {- locale: 'currencyDetail.Afghani',- suffix: 'Af',- },- {- locale: 'currencyDetail.ArgentinePeso',- suffix: '$',- },- {- locale: 'currencyDetail.UnitedArabEmiratesDirham',- suffix: 'dh',- },- {- locale: 'currencyDetail.ArubanFlorin',- suffix: 'Afl',- },- {- locale: 'currencyDetail.OmaniRial',- suffix: 'Rial',- },- {- locale: 'currencyDetail.Azerbaijanimanat',- suffix: '?',- },- {- locale: 'currencyDetail.EgyptianPound',- suffix: '£',- },- {- locale: 'currencyDetail.EthiopianBirr',- suffix: 'Birr',- },- {- locale: 'currencyDetail.AngolaKwanza',- suffix: 'Birr',- },-];--export const DATEFMTLISG = [- {- label: '1930-08-05',- suffix: 'yyyy-MM-dd',- },- {- label: '1930/08/05',- suffix: 'yyyy/MM/dd',- },- {- label: '1930年08月05日',- suffix: 'yyyy"年"MM"月"dd"日"',- },- {- label: '08-05',- suffix: 'MM-dd',- },- {- label: '8月5日',- suffix: 'M"月"d"日"',- },- {- label: '13:30:30',- suffix: 'h:mm:ss',- },- {- label: '13:30',- suffix: 'h:mm',- },- {- label: '下午01:30',- suffix: '上午/下午 hh:mm',- },- {- label: '下午1:30',- suffix: '上午/下午 h:mm',- },- {- label: '下午1:30:30',- suffix: '上午/下午 h:mm:ss',- },- {- label: '08-05 下午 01:30',- suffix: 'MM-dd 上午/下午 hh:mm',- },-];--export const NUMBERFORMAT = [- {- label: '1235',- suffix: '0',- },- {- label: '1234.56',- suffix: '0.00',- },- {- label: '12345',- suffix: '#,##0',- },- {- label: '1,234.56',- suffix: '#,##0.00',- },- {- label: '1,235',- suffix: '#,##0_);(#,##0)',- },- {- label: '1,235',- suffix: '#,##0_);[Red](#,##0)',- },- {- label: '1,234.56',- suffix: '#,##0.00_);(#,##0.00)',- },- {- label: '1,234.56',- suffix: '#,##0.00_);[Red](#,##0.00)',- },- {- label: '$1,235',- suffix: '$#,##0_);($#,##0)',- },- {- label: '$1,235',- suffix: '$#,##0_);[Red]($#,##0)',- },-];diff --git a/packages/sheets-plugin-numfmt/src/basics/const/index.ts b/packages/sheets-plugin-numfmt/src/basics/const/index.tsdeleted file mode 100644index 102f4b781d..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/const/index.ts+++ /dev/null@@ -1,6 +0,0 @@-// @index('./*.ts', f => `export * from '${f.path}'`)-export * from './config';-export * from './default-data';-export * from './formatdetail';-export * from './plugin-name';-// @endindexdiff --git a/packages/sheets-plugin-numfmt/src/basics/const/plugin-name.ts b/packages/sheets-plugin-numfmt/src/basics/const/plugin-name.tsdeleted file mode 100644index ffb4c1c1d0..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/const/plugin-name.ts+++ /dev/null@@ -1 +0,0 @@-export const NUMFMT_PLUGIN_NAME = 'NUMFMT_PLUGIN_NAME';diff --git a/packages/sheets-plugin-numfmt/src/basics/enum/action-names.ts b/packages/sheets-plugin-numfmt/src/basics/enum/action-names.tsdeleted file mode 100644index a6c742785d..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/enum/action-names.ts+++ /dev/null@@ -1,3 +0,0 @@-export enum ACTION_NAMES {- SET_NUMFMT_RANGE_DATA_ACTION = 'SetNumfmtRangeDataAction',-}diff --git a/packages/sheets-plugin-numfmt/src/basics/enum/index.ts b/packages/sheets-plugin-numfmt/src/basics/enum/index.tsdeleted file mode 100644index 7328659810..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/enum/index.ts+++ /dev/null@@ -1,3 +0,0 @@-// @index('./*.ts', f => `export * from '${f.path}'`)-export * from './action-names';-// @endindexdiff --git a/packages/sheets-plugin-numfmt/src/basics/index.ts b/packages/sheets-plugin-numfmt/src/basics/index.tsdeleted file mode 100644index 21b6720daa..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './const';-export * from './enum';diff --git a/packages/sheets-plugin-numfmt/src/basics/register/index.ts b/packages/sheets-plugin-numfmt/src/basics/register/index.tsdeleted file mode 100644index 62511f51e1..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/register/index.ts+++ /dev/null@@ -1,2 +0,0 @@-// @index('./*.ts', f => `export * from '${f.path}'`)-// @endindexdiff --git a/packages/sheets-plugin-numfmt/src/basics/register/numfmt-action-extension.ts b/packages/sheets-plugin-numfmt/src/basics/register/numfmt-action-extension.tsdeleted file mode 100644index 0b7b08d919..0000000000--- a/packages/sheets-plugin-numfmt/src/basics/register/numfmt-action-extension.ts+++ /dev/null@@ -1,88 +0,0 @@-// import { numfmt } from '@univerjs/base-numfmt-engine';-// import {-// ACTION_NAMES,-// ActionOperation,-// BaseActionExtension,-// BaseActionExtensionFactory,-// IActionData,-// IUniverInstanceService,-// ISetRangeDataActionData,-// ISheetActionData,-// ObjectMatrix,-// } from '@univerjs/core';-// import { Inject, Injector } from '@wendellhu/redi';--// import { NumfmtModel } from '../../model';-// import { NumfmtPlugin } from '../../numfmt-plugin';-// import { INumfmtPluginData } from '../../symbol';-// import { ACTION_NAMES as PLUGIN_ACTION_NAMES } from '../enum';--// export class NumfmtActionExtension extends BaseActionExtension {-// constructor(-// actionDataList: IActionData[],-// @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,-// @Inject(INumfmtPluginData) private _numfmtPluginData: NumfmtModel,-// @Inject(Injector) private readonly _sheetInjector: Injector-// ) {-// super(actionDataList);-// }--// override execute() {-// const numfmtMatrix = new ObjectMatrix<string>();-// const actionDataList = this.actionDataList as ISetRangeDataActionData[];--// actionDataList.forEach((actionData) => {-// if (actionData.operation != null && !ActionOperation.hasExtension(actionData)) {-// return false;-// }--// if (actionData.actionName !== ACTION_NAMES.SET_RANGE_DATA_ACTION) {-// return false;-// }--// const { cellValue, sheetId } = actionData;-// const numfmtConfig = this._numfmtPluginData.getNumfmtBySheetIdConfig(sheetId);-// const currSheetNumfmtMatrix = new ObjectMatrix(numfmtConfig);-// const rangeMatrix = new ObjectMatrix(cellValue);--// rangeMatrix.forValue((r, c, cell) => {-// const typed = numfmt.parseValue(cell.v) as unknown as { z: string; v: string };--// if (typed) {-// // format already set,get format, e.g. 100% => =sum(2), we will set 200%-// const currNumfmtValue = currSheetNumfmtMatrix.getValue(r, c);-// // if (currNumfmtValue) {-// // typed.z = ;-// // }--// const format = numfmt(typed.z);-// cell.m = format(typed.v);-// cell.v = typed.v || String();-// numfmtMatrix.setValue(r, c, typed.z);-// }-// });--// const setNumfmtRangeDataAction = {-// actionName: PLUGIN_ACTION_NAMES.SET_NUMFMT_RANGE_DATA_ACTION,-// sheetId,-// cellValue: numfmtMatrix.toJSON(),-// injector: this._sheetInjector,-// };-// this.push(setNumfmtRangeDataAction);-// });-// }-// }--// export class NumfmtActionExtensionFactory extends BaseActionExtensionFactory {-// constructor(_plugin: NumfmtPlugin, @Inject(Injector) private readonly _sheetInjector: Injector) {-// super(_plugin);-// }--// override get zIndex(): number {-// return 2;-// }--// override create(actionDataList: ISheetActionData[]): BaseActionExtension {-// return this._sheetInjector.createInstance(NumfmtActionExtension, actionDataList);-// }-// }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.tsnew file mode 100644index 0000000000..1c00636222--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/commands/commands/add.decimal.command.ts@@ -0,0 +1,69 @@+import { SelectionManagerService } from '@univerjs/base-sheets';+import { CommandType, ICommand, ICommandService, IUniverInstanceService, Range } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import { NumfmtService } from '../../service/numfmt.service';+import { getDecimalFromPattern, isPatternEqualWithoutDecimal, setPatternDecimal } from '../../utils/decimal';+import { SetNumfmtCommand, SetNumfmtCommandParams } from './set.numfmt.command';++export const AddDecimalCommand: ICommand = {+ id: 'sheet.command.numfmt.add.decimal.command',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor) => {+ const commandService = accessor.get(ICommandService);+ const selectionManagerService = accessor.get(SelectionManagerService);+ const numfmtService = accessor.get(NumfmtService);+ const univerInstanceService = accessor.get(IUniverInstanceService);++ const selections = selectionManagerService.getSelections();+ if (!selections || !selections.length) {+ return false;+ }+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();+ const sheet = workbook.getActiveSheet();+ const workbookId = workbook.getUnitId();+ const worksheetId = sheet.getSheetId();++ let maxDecimals = 0;+ selections.forEach((selection) => {+ Range.foreach(selection.range, (row, col) => {+ const numfmtValue = numfmtService.getValue(workbookId, worksheetId, row, col);+ if (!numfmtValue) {+ return;+ }+ const decimals = getDecimalFromPattern(numfmtValue.pattern);+ maxDecimals = decimals > maxDecimals ? decimals : maxDecimals;+ });+ });+ const decimals = maxDecimals + 1;+ const pattern = setPatternDecimal(`0${decimals > 0 ? '.0' : ''}`, decimals);+ const values: SetNumfmtCommandParams['values'] = [];++ selections.forEach((selection) => {+ Range.foreach(selection.range, (row, col) => {+ const numfmtValue = numfmtService.getValue(workbookId, worksheetId, row, col);+ if (!numfmtValue || isPatternEqualWithoutDecimal(numfmtValue.pattern, '0.0')) {+ values.push({+ row,+ col,+ pattern,+ });+ } else {+ const decimals = getDecimalFromPattern(numfmtValue.pattern);+ const pattern = setPatternDecimal(numfmtValue.pattern, decimals + 1);+ pattern !== numfmtValue.pattern &&+ values.push({+ row,+ col,+ pattern,+ });+ }+ });+ });+ if (values.length) {+ const result = await commandService.executeCommand(SetNumfmtCommand.id, { values });+ return result;+ }+ return false;+ },+};diff --git a/packages/sheets-plugin-numfmt/src/commands/commands/set-numfmt-range-data.command.ts b/packages/sheets-plugin-numfmt/src/commands/commands/set-numfmt-range-data.command.tsdeleted file mode 100644index fe6f81c298..0000000000--- a/packages/sheets-plugin-numfmt/src/commands/commands/set-numfmt-range-data.command.ts+++ /dev/null@@ -1,16 +0,0 @@-import { CommandType, ICommand } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';--export interface SetNumfmtRangeDataCommandParams {- value: string;-}--export const SetNumfmtRangeDataCommand: ICommand<SetNumfmtRangeDataCommandParams> = {- id: 'numfmt.command.set-range-data',- type: CommandType.COMMAND,- handler: async (accessor: IAccessor, params: SetNumfmtRangeDataCommandParams) => {- const { value } = params;- console.info('set-numfmt-range-data', value);- return true;- },-};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.tsnew file mode 100644index 0000000000..0e5d9e97e5--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/commands/commands/set.currency.command.ts@@ -0,0 +1,31 @@+import { SelectionManagerService } from '@univerjs/base-sheets';+import { CommandType, ICommand, ICommandService, Range } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import { CURRENCYFORMAT } from '../../base/const/FORMATDETAIL';+import { SetNumfmtCommand, SetNumfmtCommandParams } from './set.numfmt.command';++export const SetCurrencyCommand: ICommand = {+ id: 'sheet.command.numfmt.set.currency',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor) => {+ const commandService = accessor.get(ICommandService);+ const selectionManagerService = accessor.get(SelectionManagerService);++ const selections = selectionManagerService.getSelections();+ if (!selections || !selections.length) {+ return false;+ }+ const values: SetNumfmtCommandParams['values'] = [];++ const suffix = CURRENCYFORMAT[0].suffix('¥');++ selections.forEach((selection) => {+ Range.foreach(selection.range, (row, col) => {+ values.push({ row, col, pattern: suffix, type: 'currency' });+ });+ });+ const result = await commandService.executeCommand(SetNumfmtCommand.id, { values });+ return result;+ },+};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.tsnew file mode 100644index 0000000000..57b7fb47b0--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/commands/commands/set.numfmt.command.ts@@ -0,0 +1,38 @@+import { CommandType, ICommand, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import { FormatType } from '../../base/types';+import { factorySetNumfmtUndoMutation, SetNumfmtMutation } from '../mutations/set.numfmt.mutation';++export type SetNumfmtCommandParams = {+ values: Array<{ pattern?: string; row: number; col: number; type?: FormatType }>;+};++export const SetNumfmtCommand: ICommand<SetNumfmtCommandParams> = {+ id: 'sheet.command.numfmt.set.numfmt',+ type: CommandType.COMMAND,+ handler: (accessor: IAccessor, params) => {+ if (!params) {+ return false;+ }+ const commandService = accessor.get(ICommandService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const undoRedoService = accessor.get(IUndoRedoService);++ const workbook = univerInstanceService.getCurrentUniverSheetInstance();+ const workbookId = workbook.getUnitId();+ const worksheet = workbook.getActiveSheet();+ const worksheetId = worksheet.getSheetId();+ const redoOption = { ...params, workbookId, worksheetId };+ const undoOption = factorySetNumfmtUndoMutation(accessor, redoOption);+ const result = commandService.syncExecuteCommand(SetNumfmtMutation.id, redoOption);+ if (result) {+ undoRedoService.pushUndoRedo({+ unitID: workbookId,+ undoMutations: [{ id: SetNumfmtMutation.id, params: undoOption }],+ redoMutations: [{ id: SetNumfmtMutation.id, params: redoOption }],+ });+ }+ return result;+ },+};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.tsnew file mode 100644index 0000000000..7ac2ff9f82--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/commands/commands/subtract.decimal.command.ts@@ -0,0 +1,66 @@+import { SelectionManagerService } from '@univerjs/base-sheets';+import { CommandType, ICommand, ICommandService, IUniverInstanceService, Range } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import { NumfmtService } from '../../service/numfmt.service';+import { getDecimalFromPattern, isPatternEqualWithoutDecimal, setPatternDecimal } from '../../utils/decimal';+import { SetNumfmtCommand, SetNumfmtCommandParams } from './set.numfmt.command';++export const SubtractDecimalCommand: ICommand = {+ id: 'sheet.command.numfmt.subtract.decimal.command',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor) => {+ const commandService = accessor.get(ICommandService);+ const selectionManagerService = accessor.get(SelectionManagerService);+ const numfmtService = accessor.get(NumfmtService);+ const univerInstanceService = accessor.get(IUniverInstanceService);++ const selections = selectionManagerService.getSelections();+ if (!selections || !selections.length) {+ return false;+ }+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();+ const sheet = workbook.getActiveSheet();+ const workbookId = workbook.getUnitId();+ const worksheetId = sheet.getSheetId();++ let maxDecimals = 0;+ selections.forEach((selection) => {+ Range.foreach(selection.range, (row, col) => {+ const numfmtValue = numfmtService.getValue(workbookId, worksheetId, row, col);+ if (!numfmtValue) {+ return;+ }+ const decimals = getDecimalFromPattern(numfmtValue.pattern);+ maxDecimals = decimals > maxDecimals ? decimals : maxDecimals;+ });+ });+ const decimals = maxDecimals - 1;++ const pattern = setPatternDecimal(`0${decimals > 0 ? '.0' : '.'}`, decimals);+ const values: SetNumfmtCommandParams['values'] = [];++ selections.forEach((selection) => {+ Range.foreach(selection.range, (row, col) => {+ const numfmtValue = numfmtService.getValue(workbookId, worksheetId, row, col);+ if (!numfmtValue || isPatternEqualWithoutDecimal(numfmtValue.pattern, '0.0')) {+ values.push({+ row,+ col,+ pattern,+ });+ } else {+ const decimals = getDecimalFromPattern(numfmtValue.pattern);+ values.push({+ row,+ col,+ pattern: setPatternDecimal(numfmtValue.pattern, decimals - 1),+ });+ }+ });+ });++ const result = await commandService.executeCommand(SetNumfmtCommand.id, { values });+ return result;+ },+};diff --git a/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.ts b/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.tsnew file mode 100644index 0000000000..6c72545d71--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/commands/mutations/set.numfmt.mutation.ts@@ -0,0 +1,48 @@+import { CommandType, ICommand } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import { FormatType } from '../../base/types';+import { NumfmtService } from '../../service/numfmt.service';++export const factorySetNumfmtUndoMutation = (+ accessor: IAccessor,+ option: SetNumfmtMutationParams+): SetNumfmtMutationParams => {+ const numfmtService = accessor.get(NumfmtService);+ const undos: SetNumfmtMutationParams = {+ ...option,+ values: option.values+ .map((item) => {+ const { row, col } = item;+ const oldValue = numfmtService.getValue(option.workbookId, option.worksheetId, row, col);+ return { pattern: oldValue?.pattern, type: oldValue?.type, row, col };+ })+ .reverse(),+ };+ return undos;+};++export type SetNumfmtMutationParams = {+ values: Array<{ pattern?: string; row: number; col: number; type?: FormatType }>;+ workbookId: string;+ worksheetId: string;+};++export const SetNumfmtMutation: ICommand<SetNumfmtMutationParams> = {+ id: 'sheet.mutation.set.numfmt',+ type: CommandType.MUTATION,+ handler: (accessor: IAccessor, params) => {+ if (!params) {+ return false;+ }+ const values = params.values;+ const numfmtService = accessor.get(NumfmtService);+ const workbookId = params.workbookId;+ const sheetId = params.worksheetId;+ values.forEach((item) => {+ const value = item.pattern ? { pattern: item.pattern!, type: item.type! } : null;+ numfmtService.setValue(workbookId, sheetId, Number(item.row), Number(item.col), value);+ });+ return true;+ },+};diff --git a/packages/sheets-plugin-numfmt/src/commands/operations/show-modal.operation.ts b/packages/sheets-plugin-numfmt/src/commands/operations/show-modal.operation.tsdeleted file mode 100644index d6ab69adf3..0000000000--- a/packages/sheets-plugin-numfmt/src/commands/operations/show-modal.operation.ts+++ /dev/null@@ -1,20 +0,0 @@-import { CommandType, ICommand } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';--import { NumfmtService } from '../../services/numfmt.service';--export interface ShowModalCommandParams {- value: string;-}--export const ShowModalOperation: ICommand<ShowModalCommandParams> = {- id: 'numfmt.operation.show-modal',- type: CommandType.OPERATION,- handler: async (accessor: IAccessor, params: ShowModalCommandParams) => {- const { value } = params;- const numfmtService = accessor.get(NumfmtService);- console.info('numfmt-command-show-modal', value);- numfmtService.showModal(value);- return true;- },-};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.tsnew file mode 100644index 0000000000..759d85ac9b--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/commands/operators/close.numfmt.panel.operator.ts@@ -0,0 +1,9 @@+import { CommandType, ICommand } from '@univerjs/core';++export const CloseNumfmtPanelOperator: ICommand = {+ id: 'sheet.operation.close.numfmt.panel',+ type: CommandType.OPERATION,+ handler: () =>+ // do nothing,just notify panel is closed+ true,+};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.tsnew file mode 100644index 0000000000..25a032c9f9--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/commands/operators/open.numfmt.panel.operator.ts@@ -0,0 +1,14 @@+import { CommandType, ICommand } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import { NumfmtController } from '../../controllers/numfmt.controller';++export const OpenNumfmtPanelOperator: ICommand = {+ id: 'sheet.operation.open.numfmt.panel',+ type: CommandType.OPERATION,+ handler: (accessor: IAccessor) => {+ const numfmtController = accessor.get(NumfmtController);+ numfmtController.openPanel();+ return true;+ },+};diff --git a/packages/sheets-plugin-numfmt/src/components/accounting/index.tsx b/packages/sheets-plugin-numfmt/src/components/accounting/index.tsxnew file mode 100644index 0000000000..41edc5f612--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/accounting/index.tsx@@ -0,0 +1,56 @@+import { LocaleService } from '@univerjs/core';+import { InputNumber, Select } from '@univerjs/design';+import { useDependency } from '@wendellhu/redi/react-bindings';+import React, { FC, useEffect, useMemo, useState } from 'react';++import { BusinessComponentProps } from '../../base/types';+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) => {+ const [decimal, decimalSet] = useState(() => getDecimalFromPattern(props.defaultPattern || '', 2));+ const [suffix, suffixSet] = useState(+ () => getCurrencyType(props.defaultPattern || '') || getCurrencyOptions()[0].value+ );+ const localeService = useDependency(LocaleService);+ const t = localeService.t;+ const pattern = useMemo(+ () => setPatternDecimal(`_("${suffix}"* #,##0${decimal > 0 ? '.0' : ''}_)`, decimal),+ [suffix, decimal]+ );++ const currencyOptions = useMemo(getCurrencyOptions, []);++ useEffect(() => {+ props.onChange(pattern);+ }, [pattern]);++ return (+ <div>+ <div className="m-t-16 options ">+ <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)} />+ </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>+ </div>+ </div>+ </div>++ <div className="describe m-t-14">{t('sheet.numfmt.accountingDes')}</div>+ </div>+ );+};diff --git a/packages/sheets-plugin-numfmt/src/components/currency/index.less b/packages/sheets-plugin-numfmt/src/components/currency/index.lessnew file mode 100644index 0000000000..492c0a86a2--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/currency/index.less@@ -0,0 +1,12 @@+.options{+ display: flex;+ justify-content: space-between;++ .w-140{+ width: 140px;+ }++ .w-120{+ width: 120px;+ }+}\ No newline at end of filediff --git a/packages/sheets-plugin-numfmt/src/components/currency/index.tsx b/packages/sheets-plugin-numfmt/src/components/currency/index.tsxnew file mode 100644index 0000000000..fc0e50dbda--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/currency/index.tsx@@ -0,0 +1,94 @@+import './index.less';++import { LocaleService } from '@univerjs/core';+import { InputNumber, Select, SelectList } from '@univerjs/design';+import { useDependency } from '@wendellhu/redi/react-bindings';+import React, { FC, useEffect, useMemo, useRef, useState } from 'react';++import { BusinessComponentProps } from '../../base/types';+import { getCurrencyType } from '../../utils/currency';+import { getDecimalFromPattern, isPatternEqualWithoutDecimal, setPatternDecimal } from '../../utils/decimal';+import { getCurrencyFormatOptions, getCurrencyOptions } 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) => {+ const localeService = useDependency(LocaleService);+ const t = localeService.t;+ 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 resultPattern = useMemo(() => setPatternDecimal(pattern, decimal), [pattern, decimal]);++ const currencyOptions = useMemo(getCurrencyOptions, []);++ useEffect(() => {+ props.onChange(resultPattern);+ }, [resultPattern]);++ useEffectWithoutFirst(() => {+ patternSet(negativeOptions[0].value);+ return () => {};+ }, [negativeOptions]);++ return (+ <div>+ <div className="m-t-16 options ">+ <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)} />+ </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>+ </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>+ </div>++ <div className="describe m-t-14">{t('sheet.numfmt.currencyDes')}</div>+ </div>+ );+};diff --git a/packages/sheets-plugin-numfmt/src/components/date/index.tsx b/packages/sheets-plugin-numfmt/src/components/date/index.tsxnew file mode 100644index 0000000000..d89c2212e6--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/date/index.tsx@@ -0,0 +1,45 @@+import numfmt from '@univerjs/base-numfmt-engine';+import { LocaleService } from '@univerjs/core';+import { SelectList } from '@univerjs/design';+import { useDependency } from '@wendellhu/redi/react-bindings';+import React, { FC, useEffect, useMemo, useState } from 'react';++import { BusinessComponentProps } from '../../base/types';+import { getDateFormatOptions } from '../../utils/options';++export const isDatePanel = (pattern: string) => {+ const info = numfmt.getInfo(pattern);+ return (+ getDateFormatOptions()+ .map((item) => item.value)+ .includes(pattern) || ['date', 'datetime', 'time'].includes(info.type)+ );+};++export const DatePanel: FC<BusinessComponentProps> = (props) => {+ const options = useMemo(getDateFormatOptions, []);+ const localeService = useDependency(LocaleService);+ const t = localeService.t;+ const [suffix, suffixSet] = useState(() => {+ if (props.defaultPattern) {+ const item = options.find((item) => item.value === props.defaultPattern);+ if (item) {+ return item.value;+ }+ }+ return options[0].value;+ });++ useEffect(() => {+ props.onChange(suffix);+ }, [suffix]);+ 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>+ </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.tsxnew file mode 100644index 0000000000..65fac2d857--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/general/index.tsx@@ -0,0 +1,20 @@+import { LocaleService } from '@univerjs/core';+import { useDependency } from '@wendellhu/redi/react-bindings';+import React, { FC, useEffect } from 'react';++import { BusinessComponentProps } from '../../base/types';++export const isGeneralPanel = (pattern: string) => !pattern;++export const GeneralPanel: FC<BusinessComponentProps> = (props) => {+ const localeService = useDependency(LocaleService);+ const t = localeService.t;+ useEffect(() => {+ props.onChange('');+ }, []);+ return (+ <div>+ <div className="describe m-t-14">{t('sheet.numfmt.generalDes')}</div>+ </div>+ );+};diff --git a/packages/sheets-plugin-numfmt/src/components/index.less b/packages/sheets-plugin-numfmt/src/components/index.lessnew file mode 100644index 0000000000..964ee7c63a--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/index.less@@ -0,0 +1,61 @@+.numfmt-panel {+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ justify-content: space-between;++ height: 100%;++ .group-title {+ font-size: 16px;+ color: rgba(var(--color-black));+ }++ .label {+ font-size: 15px;+ color: rgba(var(--grey-400));+ }++ .describe {+ font-size: 13px;+ line-height: 20px;+ color: rgba(var(--grey-600));+ }++ .preview {+ height: 36px;+ padding: 0 16px;++ font-size: 14px;+ line-height: 36px;+ color: var(--color-black);++ border: 1px solid rgb(var(--grey-200));+ border-radius: 4px;+ }++ .btn-list {+ display: flex;+ justify-content: end;+ }++ .m-r-12 {+ margin-right: 12px;+ }++ .m-t-16 {+ margin-top: 16px;+ }++ .m-t-14 {+ margin-top: 14px;+ }++ .m-t-8 {+ margin-top: 8px;+ }++ .m-b-20 {+ margin-bottom: 20px;+ }+}diff --git a/packages/sheets-plugin-numfmt/src/components/index.tsx b/packages/sheets-plugin-numfmt/src/components/index.tsxnew file mode 100644index 0000000000..119ba30b0d--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/index.tsx@@ -0,0 +1,93 @@+import './index.less';++import { LocaleService } from '@univerjs/core';+import { Button, ISelectProps, Select } from '@univerjs/design';+import { useDependency } from '@wendellhu/redi/react-bindings';+import React, { FC, useEffect, useMemo, useRef, useState } from 'react';++import { BusinessComponentProps } from '../base/types';+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 type SheetNumfmtPanelProps = {+ value: { defaultValue: number; defaultPattern: string };+ onChange: (config: { type: 'change' | 'cancel' | 'confirm'; value: string }) => void;+};+export const SheetNumfmtPanel: FC<SheetNumfmtPanelProps> = (props) => {+ const { defaultValue, defaultPattern } = props.value;+ const localeService = useDependency(LocaleService);+ const t = localeService.t;+ const options = useMemo(+ () =>+ [+ { label: 'sheet.numfmt.general', component: GeneralPanel },+ { label: 'sheet.numfmt.accounting', component: AccountingPanel },+ { label: 'sheet.numfmt.currency', component: CurrencyPanel },+ { label: 'sheet.numfmt.date', component: DatePanel },+ { label: 'sheet.numfmt.thousandthPercentile', component: ThousandthPercentilePanel },+ ].map((item) => ({ ...item, label: t(item.label) })),+ []+ );+ const findDefaultType = () => {+ const list = [isGeneralPanel, isAccountingPanel, isCurrencyPanel, isDatePanel, isThousandthPercentilePanel];+ return (+ list.reduce((pre, curFn, index) => pre || (curFn(defaultPattern) ? options[index].label : ''), '') ||+ options[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) => ({+ label: option.label,+ value: option.label,+ }));+ const handleSelect: ISelectProps['onChange'] = (value) => {+ typeSet(value);+ };+ const handleChange = (v: string) => {+ pattern.current = v;+ props.onChange({ type: 'change', value: v });+ };+ const handleConfirm = () => {+ props.onChange({ type: 'confirm', value: pattern.current });+ };+ const handleCancel = () => {+ props.onChange({ type: 'cancel', value: pattern.current });+ };++ const subProps: BusinessComponentProps = {+ onChange: handleChange,+ defaultValue,+ defaultPattern,+ };++ useEffect(() => {+ typeSet(findDefaultType());+ }, [defaultPattern, defaultValue]);++ return (+ <div className="numfmt-panel p-b-20">+ <div>+ <div className="label m-t-14">{t('sheet.numfmt.numfmtType')}</div>+ <div className="m-t-8">+ <Select onChange={handleSelect} options={selectOptions} value={type}></Select>+ </div>+ <div>{BusinessComponent && <BusinessComponent {...subProps} />}</div>+ </div>++ <div className="btn-list m-t-14 m-b-20">+ <Button size="small" onClick={handleCancel} className="m-r-12">+ {t('sheet.numfmt.cancel')}+ </Button>+ <Button type="primary" size="small" onClick={handleConfirm}>+ {t('sheet.numfmt.confirm')}+ </Button>+ </div>+ </div>+ );+};diff --git a/packages/sheets-plugin-numfmt/src/components/more-numfmt-type/MoreNumfmtType.tsx b/packages/sheets-plugin-numfmt/src/components/more-numfmt-type/MoreNumfmtType.tsxnew file mode 100644index 0000000000..d824ede99d--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/more-numfmt-type/MoreNumfmtType.tsx@@ -0,0 +1,16 @@+import './index.less';++import { MoreDownSingle } from '@univerjs/icons';+import React from 'react';++export const MoreNumfmtType = (props: { value?: string }) => {+ const value = props.value ?? '常规';+ return (+ <span className="more-numfmt-type">+ {value}+ <div className="icon">+ <MoreDownSingle />+ </div>+ </span>+ );+};diff --git a/packages/sheets-plugin-numfmt/src/components/more-numfmt-type/index.less b/packages/sheets-plugin-numfmt/src/components/more-numfmt-type/index.lessnew file mode 100644index 0000000000..a1e7063a5d--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/more-numfmt-type/index.less@@ -0,0 +1,20 @@+.more-numfmt-type {+ display: flex;+ flex-shrink: 0;++ padding: 0 4px;++ font-size: 13px;+ color: var(--black);++ .icon{+ display: flex;+ align-items: center;++ height: auto;+ padding-left: 8px;++ font-size: 10px;+ color: rgb(var(--grey-400));+ }+}diff --git a/packages/sheets-plugin-numfmt/src/components/stories/panel.stories.tsx b/packages/sheets-plugin-numfmt/src/components/stories/panel.stories.tsxnew file mode 100644index 0000000000..90613aba46--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/stories/panel.stories.tsx@@ -0,0 +1,38 @@+import type { Meta, StoryObj } from '@storybook/react';+import { LocaleService, LocaleType, ThemeService } from '@univerjs/core';+import { Injector } from '@wendellhu/redi';+import { connectInjector } from '@wendellhu/redi/react-bindings';+import React, { useMemo } from 'react';++import { zhCn } from '../../locale/zh-CN';+import { SheetNumfmtPanel, SheetNumfmtPanelProps } from '../index';++const Index = (props: any) => {+ const inject = useMemo(() => new Injector([[LocaleService], [ThemeService]]), []);+ const Wrap = useMemo(() => connectInjector(SheetNumfmtPanel, inject), []) as any;++ useMemo(() => {+ const localeService = inject.get(LocaleService);+ localeService.load({ [LocaleType.ZH_CN]: zhCn, [LocaleType.EN_US]: zhCn });+ }, []);++ return <Wrap {...props} />;+};+const meta: Meta = {+ title: 'numfmt',+ component: Index,+ parameters: {+ layout: 'centered',+ },+};++export default meta;++export const Test: StoryObj<SheetNumfmtPanelProps> = {+ args: {+ value: { defaultPattern: '', defaultValue: 123123 },+ 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.tsxnew file mode 100644index 0000000000..ee0bbf00cc--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/components/thousandth-percentile/index.tsx@@ -0,0 +1,57 @@+import { InputNumber, SelectList } from '@univerjs/design';+import React, { FC, useEffect, useMemo, useState } from 'react';++import { BusinessComponentProps } from '../../base/types';+import {+ getDecimalFromPattern,+ isPatternEqualWithoutDecimal,+ isPatternHasDecimal,+ setPatternDecimal,+} from '../../utils/decimal';+import { getNumberFormatOptions } from '../../utils/options';++export const isThousandthPercentilePanel = (pattern: string) =>+ getNumberFormatOptions().some((item) => isPatternEqualWithoutDecimal(item.value, pattern));++export const ThousandthPercentilePanel: FC<BusinessComponentProps> = (props) => {+ const options = useMemo(getNumberFormatOptions, []);+ const [decimal, decimalSet] = useState(() => getDecimalFromPattern(props.defaultPattern || '', 0));++ const [suffix, suffixSet] = useState(() => {+ const item = options.find((item) => isPatternEqualWithoutDecimal(item.value, props.defaultPattern || ''));+ return item?.value || options[0].value;+ });++ const pattern = useMemo(() => setPatternDecimal(suffix, Number(decimal || 0)), [suffix, decimal]);++ const isInputDisable = useMemo(() => !isPatternHasDecimal(suffix), [suffix]);++ const handleClick = (v: string) => {+ decimalSet(getDecimalFromPattern(v, 0));+ suffixSet(v);+ };++ useEffect(() => {+ props.onChange(pattern);+ }, [pattern]);++ return (+ <div>+ <div className="m-t-16 label">小数位数</div>+ <div className="m-t-8">+ <InputNumber+ disabled={isInputDisable}+ value={decimal}+ max={20}+ min={0}+ onChange={(value) => decimalSet(value || 0)}+ />+ </div>+ <div className="m-t-16 label"> 负数类型</div>+ <div className="m-t-8">+ <SelectList onChange={handleClick} options={options} value={suffix}></SelectList>+ </div>+ <div className="describe m-t-14">货币格式用于表示一般货币数值。会计格式可以对一列数值进行小数点对齐。</div>+ </div>+ );+};diff --git a/packages/sheets-plugin-numfmt/src/controllers/index.ts b/packages/sheets-plugin-numfmt/src/controllers/index.tsdeleted file mode 100644index d9ff9e4b75..0000000000--- a/packages/sheets-plugin-numfmt/src/controllers/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './numfmt-controller';-export * from './numfmt-modal-controller';diff --git a/packages/sheets-plugin-numfmt/src/controllers/menu.ts b/packages/sheets-plugin-numfmt/src/controllers/menu.tsdeleted file mode 100644index 7c75490be4..0000000000--- a/packages/sheets-plugin-numfmt/src/controllers/menu.ts+++ /dev/null@@ -1,71 +0,0 @@-import { IMenuSelectorItem, MenuItemType, MenuPosition } from '@univerjs/base-ui';-import { ICommandService } from '@univerjs/core';-import { IAccessor } from '@wendellhu/redi';--import { DEFAULT_DATA, MORE_FORMATS_SELECTIONS } from '../basics/const/default-data';-import { SetNumfmtRangeDataCommand } from '../commands/commands/set-numfmt-range-data.command';-import { ShowModalOperation } from '../commands/operations/show-modal.operation';--export function NumfmtRangeDataMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {- // const permissionService = accessor.get(IPermissionService);- const commandService = accessor.get(ICommandService);- // const selectionManager = accessor.get(ISelectionManager);-- return {- id: SetNumfmtRangeDataCommand.id,- title: 'toolbar.moreFormats',- tooltip: 'toolbar.moreFormats',- type: MenuItemType.SELECTOR,- positions: [MenuPosition.TOOLBAR_START],- selections: DEFAULT_DATA,- // disabled$: new Observable((subscriber) => {- // let editable = false;- // function update() {- // subscriber.next(!editable);- // }-- // update();-- // const permission$ = permissionService.editable$.subscribe((e) => {- // editable = e;- // update();- // });-- // return () => {- // permission$.unsubscribe();- // };- // }),- // value$: new Observable((subscriber) => {- // const defaultValue = FONT_FAMILY_CHILDREN[0].value;-- // const disposable = commandService.onCommandExecuted((c) => {- // const id = c.id;- // if (id !== SetRangeStyleMutation.id && id !== SetSelectionsOperation.id) {- // return;- // }-- // const range = selectionManager.getCurrentCell();- // const ff = range?.getFontFamily();-- // subscriber.next(ff ?? defaultValue);- // });-- // subscriber.next(defaultValue);- // return disposable.dispose;- // }),- };-}--export function OpenMoreFormatsModalMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {- // const permissionService = accessor.get(IPermissionService);- const commandService = accessor.get(ICommandService);- // const selectionManager = accessor.get(ISelectionManager);- return {- // 2. suffix- id: ShowModalOperation.id,- title: 'defaultFmt.CustomFormats.text',- positions: SetNumfmtRangeDataCommand.id,- type: MenuItemType.SELECTOR,- selections: [...MORE_FORMATS_SELECTIONS],- };-}diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt-controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt-controller.tsdeleted file mode 100644index cdc37393a6..0000000000--- a/packages/sheets-plugin-numfmt/src/controllers/numfmt-controller.ts+++ /dev/null@@ -1,166 +0,0 @@-import { ComponentManager, IMenuService } from '@univerjs/base-ui';-import {- Disposable,- ICommandService,- IRange,- IUniverInstanceService,- ObjectMatrix,- ObjectMatrixPrimitiveType,- Range,-} from '@univerjs/core';-import { Inject, Injector } from '@wendellhu/redi';--import { NUMFMT_PLUGIN_NAME } from '../basics/const';-import { SetNumfmtRangeDataCommand } from '../commands/commands/set-numfmt-range-data.command';-import { ShowModalOperation } from '../commands/operations/show-modal.operation';-import { NumfmtModel } from '../model';-import { INumfmtPluginData } from '../symbol';-import { FormatItem } from '../views/ui/FormatItem';-import { NumfmtRangeDataMenuItemFactory, OpenMoreFormatsModalMenuItemFactory } from './menu';-import { NumfmtModalController } from './numfmt-modal-controller';--/**- * const CHILDREN_DATA = DEFAULT_DATA.map((item, index) => ({- onClick: () => {- switch (index) {- case 0: {- //executeFormatter('G');- break;- }- case 1: {- //executeFormatter('@');- break;- }- case 2: {- //executeFormatter('#.##');- break;- }- case 3: {- //executeFormatter('#.##%');- break;- }- case 4: {- //executeFormatter('#.##E+');- break;- }- case 5: {- // TODO- break;- }- case 6: {- //executeFormatter('¥#.##');- break;- }- case 7: {- // TODO- break;- }- case 8: {- //executeFormatter('yyyy-mm-dd');- break;- }- case 9: {- //executeFormatter('h:mm AM/PM');- break;- }- case 10: {- //executeFormatter('h:mm');- break;- }- // eslint-disable-next-line no-magic-numbers- case 11: {- //executeFormatter('yyyy-mm-dd h:mm AM/PM');- break;- }- // eslint-disable-next-line no-magic-numbers- case 12: {- //executeFormatter('yyyy-mm-dd h:mm');- break;- }- // eslint-disable-next-line no-magic-numbers- case 13: {- break;- }- }- },- ...item,- }));- */-export class NumfmtController extends Disposable {- constructor(- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(Injector) private readonly _injector: Injector,- @Inject(INumfmtPluginData) private _numfmtPluginData: NumfmtModel,- @Inject(IUniverInstanceService) private readonly _currentUniverService: IUniverInstanceService,- @Inject(NumfmtModalController) private readonly _numfmtModalController: NumfmtModalController,- @IMenuService private readonly _menuService: IMenuService,- @ICommandService private readonly _commandService: ICommandService- ) {- super();-- this._componentManager.register(NUMFMT_PLUGIN_NAME + FormatItem.name, FormatItem);-- this._initializeContextMenu();-- [ShowModalOperation, SetNumfmtRangeDataCommand].forEach((command) =>- this.disposeWithMe(this._commandService.registerCommand(command))- );- }-- getNumfmtBySheetIdConfig(sheetId: string): ObjectMatrixPrimitiveType<string> {- return this._numfmtPluginData.getNumfmtBySheetIdConfig(sheetId);- }-- setNumfmtByRange(sheetId: string, numfmtRange: IRange, numfmtValue: string): void {- const numfmtMatrix = new ObjectMatrix<string>();- Range.foreach(numfmtRange, (row, column) => {- numfmtMatrix.setValue(row, column, numfmtValue);- });-- // TODO new command-- // const commandManager = this._commandManager;- // const config = {- // actionName: CORE_ACTION_NAME.SET_RANGE_DATA_ACTION,- // sheetId,- // range: numfmtRange,- // cellValue: numfmtMatrix.toJSON(),- // };- // const command = new Command(- // {- // WorkBookUnit: this._currentUniverService.getCurrentUniverSheetInstance(),- // },- // config- // );- // commandManager.invoke(command);- }-- setNumfmtByCoords(sheetId: string, row: number, column: number, numfmt: string): void {- const numfmtMatrix = new ObjectMatrix<string>();- numfmtMatrix.setValue(row, column, numfmt);- const numfmtRange: IRange = { startRow: row, startColumn: column, endRow: row, endColumn: column };-- // TODO new command-- // const commandManager = this._commandManager;- // const config = {- // actionName: CORE_ACTION_NAME.SET_RANGE_DATA_ACTION,- // sheetId,- // range: numfmtRange,- // cellValue: numfmtMatrix.toJSON(),- // };- // const command = new Command(- // {- // WorkBookUnit: this._currentUniverService.getCurrentUniverSheetInstance(),- // },- // config- // );- // commandManager.invoke(command);- }-- private _initializeContextMenu() {- [NumfmtRangeDataMenuItemFactory, OpenMoreFormatsModalMenuItemFactory].forEach((factory) => {- this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));- });- }-}diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt-modal-controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt-modal-controller.tsdeleted file mode 100644index a52faa3933..0000000000--- a/packages/sheets-plugin-numfmt/src/controllers/numfmt-modal-controller.ts+++ /dev/null@@ -1,154 +0,0 @@-import { ComponentManager } from '@univerjs/base-ui';-import { LocaleService } from '@univerjs/core';-import { Inject } from '@wendellhu/redi';-import React from 'react';--import { CURRENCYDETAIL, DATEFMTLISG, NUMBERFORMAT, NUMFMT_PLUGIN_NAME } from '../basics/const';-import { NumfmtModel } from '../model/numfmt-model';-import { INumfmtPluginData } from '../symbol';-import { FormatContent } from '../views/ui/FormatContent';-import { NumfmtModal } from '../views/ui/NumfmtModal';--interface GroupProps {- locale: string;- type?: string;- label?: string;- onClick?: () => void;-}--export interface ModalDataProps {- name?: string;- title?: string;- show: boolean;- locale: string;- children: {- name: string;- props: any;- };- group: GroupProps[];- modal?: React.ReactNode; // 渲染的组件- onCancel?: () => void;-}--export class NumfmtModalController {- protected _modalData: ModalDataProps[];-- constructor(- @Inject(INumfmtPluginData) private _numfmtPluginData: NumfmtModel,- @Inject(LocaleService) private readonly _localeService: LocaleService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager- ) {- this._modalData = [- {- locale: 'toolbar.currencyFormat',- name: 'currency',- group: [- {- locale: 'button.confirm',- type: 'primary',- onClick: () => {},- },- {- locale: 'button.cancel',- onClick: () => {},- },- ],- show: false,- children: {- name: NUMFMT_PLUGIN_NAME + FormatContent.name,- props: {- data: this.resetContentData(CURRENCYDETAIL),- input: this._localeService.t('format.decimalPlaces'),- onClick: (value: string) => console.dir(value),- onChange: (value: string) => console.dir(value),- },- },- onCancel: (): void => {- this.showModal('currency', false);- },- },- {- locale: 'toolbar.currencyFormat',- name: 'date',- group: [- {- locale: 'button.confirm',- type: 'primary',- },- {- locale: 'button.cancel',- },- ],- show: false,- children: {- name: NUMFMT_PLUGIN_NAME + FormatContent.name,- props: {- data: DATEFMTLISG,- onClick: (value: string) => console.dir(value),- },- },- onCancel: (): void => {- this.showModal('currency', false);- },- },- {- locale: 'toolbar.numberFormat',- name: 'number',- group: [- {- locale: 'button.confirm',- type: 'primary',- },- {- locale: 'button.cancel',- },- ],- show: false,- children: {- name: NUMFMT_PLUGIN_NAME + FormatContent.name,- props: {- data: NUMBERFORMAT,- onClick: (value: string) => console.dir(value),- },- },- onCancel: (): void => {- this.showModal('number', false);- },- },- ];- this._componentManager.register(NUMFMT_PLUGIN_NAME + FormatContent.name, FormatContent);- this._componentManager.register(NUMFMT_PLUGIN_NAME + NumfmtModal.name, NumfmtModal);- }-- resetContentData(data: any[]): any[] {- for (let i = 0; i < data.length; i++) {- if (data[i].locale) {- data[i].label = this._localeService.t(data[i].locale);- }- }- return data;- }-- // 渲染所需数据- resetModalData(): void {- this._modalData.forEach((item) => {- item.title = this._localeService.t(item.locale);- if (item.group && item.group.length) {- item.group.forEach((ele) => {- ele.label = this._localeService.t(ele.locale);- });- }- });-- // TODO update modal data- // this._numfmtPluginData.setModal(this._modalData);- }-- showModal(name: string, show: boolean): void {- const index: number = this._modalData.findIndex((item) => item.name === name);- if (index > -1) {- this._modalData[index].show = show;- this.resetModalData();- }- }-}diff --git a/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts b/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.tsnew file mode 100644index 0000000000..9b739e37bc--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/controllers/numfmt.controller.ts@@ -0,0 +1,736 @@+import numfmt from '@univerjs/base-numfmt-engine';+import { IRenderManagerService } from '@univerjs/base-render';+import {+ EffectRefRangeParams,+ EffectRefRangId,+ handleDeleteRangeMoveLeft,+ handleDeleteRangeMoveUp,+ handleInsertCol,+ handleInsertRangeMoveDown,+ handleInsertRangeMoveRight,+ handleInsertRow,+ handleIRemoveCol,+ handleIRemoveRow,+ handleMoveRange,+ RefRangeService,+ runRefRangeMutations,+ SelectionManagerService,+ SetRangeValuesCommand,+} from '@univerjs/base-sheets';+import { ComponentManager, IMenuService, ISidebarService } from '@univerjs/base-ui';+import {+ CellValueType,+ Disposable,+ DisposableCollection,+ ICommandService,+ INTERCEPTOR_POINT,+ IRange,+ IUniverInstanceService,+ LifecycleStages,+ LocaleService,+ LocaleType,+ Nullable,+ OnLifecycle,+ Range,+ SheetInterceptorService,+ ThemeService,+ toDisposable,+} from '@univerjs/core';+import { SheetSkeletonManagerService } from '@univerjs/ui-plugin-sheets';+import { IDisposable, Inject, Injector } from '@wendellhu/redi';+import { combineLatest, Observable } from 'rxjs';+import { bufferTime, distinctUntilChanged, filter, map, switchMap, tap } from 'rxjs/operators';++import { SHEET_NUMFMT_PLUGIN } from '../base/const/PLUGIN_NAME';+import { NumfmtItem } from '../base/types';+import { AddDecimalCommand } from '../commands/commands/add.decimal.command';+import { SetCurrencyCommand } from '../commands/commands/set.currency.command';+import { SetNumfmtCommand, SetNumfmtCommandParams } from '../commands/commands/set.numfmt.command';+import { SubtractDecimalCommand } from '../commands/commands/subtract.decimal.command';+import {+ factorySetNumfmtUndoMutation,+ SetNumfmtMutation,+ SetNumfmtMutationParams,+} 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 { SheetNumfmtPanel, SheetNumfmtPanelProps } from '../components/index';+import { zhCn } from '../locale/zh-CN';+import { AddDecimalMenuItem, CurrencyMenuItem, FactoryOtherMenuItem, SubtractDecimalMenuItem } from '../menu/menu';+import { NumfmtService } from '../service/numfmt.service';+import { getPatternPreview, getPatternType } from '../utils/pattern';++const createCollectEffectMutation = () => {+ type Config = { workbookId: string; worksheetId: string; row: number; col: number; value: Nullable<NumfmtItem> };+ let list: Config[] = [];+ const add = (workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<NumfmtItem>) =>+ list.push({ workbookId, worksheetId, row, col, value });+ const getEffects = () => list;+ const clean = () => {+ list = [];+ };+ return {+ add,+ getEffects,+ clean,+ };+};+@OnLifecycle(LifecycleStages.Ready, NumfmtController)+export class NumfmtController extends Disposable {+ // collect effect mutations when edit end and push this to commands stack in next commands progress+ private _collectEffectMutation = createCollectEffectMutation();+ private _previewPattern = '';++ constructor(+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,+ @Inject(ThemeService) private _themeService: ThemeService,+ @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,+ @Inject(IRenderManagerService) private _renderManagerService: IRenderManagerService,+ @Inject(NumfmtService) private _numfmtService: NumfmtService,+ @Inject(ComponentManager) private _componentManager: ComponentManager,+ @Inject(IMenuService) private _menuService: IMenuService,+ @Inject(ISidebarService) private _sidebarService: ISidebarService,+ @Inject(LocaleService) private _localeService: LocaleService+ ) {+ super();+ this._initInterceptorCellContent();+ this._initInterceptorEditorStart();+ this._initInterceptorEditorEnd();+ this._initInterceptorCommands();+ this._initRealTimeRenderingInterceptor();+ this._registerRefRange();+ this._initMenu();+ this._initLocal();+ this._initPanel();+ this._initCommands();+ }++ openPanel = () => {+ const sidebarService = this._sidebarService;+ const selectionManagerService = this._selectionManagerService;+ const commandService = this._commandService;+ const univerInstanceService = this._univerInstanceService;+ const numfmtService = this._numfmtService;+ const localeService = this._localeService;++ const selections = selectionManagerService.getSelectionRanges() || [];+ const range = selections[0];++ if (!range) {+ return false;+ }+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();+ const sheet = workbook.getActiveSheet();++ const cellValue = sheet.getCellRaw(range.startRow, range.startColumn);+ const numfmtValue = numfmtService.getValue(+ workbook.getUnitId(),+ sheet.getSheetId(),+ range.startRow,+ range.startColumn+ );+ let pattern = '';+ if (numfmtValue) {+ pattern = numfmtValue.pattern;+ }+ // eslint-disable-next-line no-magic-numbers+ const defaultValue = (cellValue?.t === CellValueType.NUMBER ? cellValue.v : 12345678) as number;++ const props: SheetNumfmtPanelProps = {+ onChange: (config) => {+ if (config.type === 'change') {+ this._previewPattern = config.value;+ this._renderManagerService.getRenderById(workbook.getUnitId())?.mainComponent?.makeDirty();+ } else if (config.type === 'confirm') {+ const selections = selectionManagerService.getSelectionRanges() || [];+ const params: SetNumfmtCommandParams = { values: [] };+ const patternType = getPatternType(config.value);+ selections.forEach((rangeInfo) => {+ Range.foreach(rangeInfo, (row, col) => {+ params.values.push({+ row,+ col,+ pattern: config.value,+ type: patternType,+ });+ });+ });+ commandService.executeCommand(SetNumfmtCommand.id, params);+ sidebarService.close();+ } else if (config.type === 'cancel') {+ sidebarService.close();+ }+ },+ value: { defaultPattern: pattern, defaultValue },+ };++ sidebarService.open({+ header: { title: localeService.t('sheet.numfmt.title') },+ children: {+ label: SHEET_NUMFMT_PLUGIN,+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ ...(props as any), // need passthrough to react props.+ },+ onClose: () => {+ commandService.executeCommand(CloseNumfmtPanelOperator.id);+ },+ });+ };++ private _initCommands() {+ [+ AddDecimalCommand,+ SubtractDecimalCommand,+ SetCurrencyCommand,+ OpenNumfmtPanelOperator,+ CloseNumfmtPanelOperator,+ SetNumfmtCommand,+ ].forEach((config) => {+ this.disposeWithMe(this._commandService.registerCommand(config));+ });+ }++ private _initPanel() {+ this._componentManager.register(SHEET_NUMFMT_PLUGIN, SheetNumfmtPanel);+ }+ private _initLocal = () => {+ this._localeService.load({ [LocaleType.ZH_CN]: zhCn, [LocaleType.EN_US]: zhCn });+ };++ private _initMenu() {+ [AddDecimalMenuItem, SubtractDecimalMenuItem, CurrencyMenuItem, FactoryOtherMenuItem]+ .map((factory) => factory(this._componentManager))+ .forEach((configFactory) => {+ this.disposeWithMe(this._menuService.addMenuItem(configFactory(this._injector)));+ });+ }++ private _initInterceptorCommands() {+ const self = this;+ this.disposeWithMe(+ this._sheetInterceptorService.interceptCommand({+ getMutations(command) {+ const workbookId = self._univerInstanceService.getCurrentUniverSheetInstance().getUnitId();+ const worksheetId = self._univerInstanceService+ .getCurrentUniverSheetInstance()+ .getActiveSheet()+ .getSheetId();+ switch (command.id) {+ case SetRangeValuesCommand.id: {+ 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 }],+ };+ }+ }+ return {+ redos: [],+ undos: [],+ };+ },+ })+ );+ }++ private _initInterceptorCellContent() {+ this.disposeWithMe(+ this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ handler: (cell, location, next) => {+ const workbookId = location.workbookId;+ const sheetId = location.worksheetId;+ const numfmtValue = this._numfmtService.getValue(workbookId, sheetId, location.row, location.col);+ if (!numfmtValue) {+ return next(cell);+ }+ const originCellValue = location.worksheet.getCellRaw(location.row, location.col);+ if (!originCellValue) {+ return next(cell);+ }+ // just handle number+ if (originCellValue.t !== CellValueType.NUMBER) {+ return next(cell);+ }++ let numfmtRes: string = '';+ if (numfmtValue._cache && numfmtValue._cache.parameters === originCellValue.v) {+ return numfmtValue._cache.result;+ }++ const info = getPatternPreview(numfmtValue.pattern, Number(originCellValue.v));++ numfmtRes = info.result;++ if (!numfmtRes) {+ return next(cell);+ }++ const res = { ...cell, v: numfmtRes };++ if (info.color) {+ const color = this._themeService.getCurrentTheme()[`${info.color}500`];++ if (color) {+ res.s = { cl: { rgb: color } };+ }+ }++ numfmtValue._cache = {+ result: res,+ parameters: originCellValue.v as number,+ };++ return res;+ },+ })+ );+ }++ private _initRealTimeRenderingInterceptor() {+ const isPanelOpenObserver = new Observable<boolean>((subscribe) => {+ this._commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === OpenNumfmtPanelOperator.id) {+ subscribe.next(true);+ }+ if (commandInfo.id === CloseNumfmtPanelOperator.id) {+ subscribe.next(false);+ }+ });+ });+ const combineOpenAndSelection$ = combineLatest([+ isPanelOpenObserver,+ this._selectionManagerService.selectionInfo$.pipe(+ map((selectionInfos) => {+ if (!selectionInfos) {+ return [];+ }+ return selectionInfos.map((selectionInfo) => selectionInfo.range);+ })+ ),+ ]);+ this.disposeWithMe(+ toDisposable(+ combineOpenAndSelection$+ .pipe(+ switchMap(+ ([isOpen, selectionRanges]) =>+ new Observable<{+ disposableCollection: DisposableCollection;+ selectionRanges: IRange[];+ }>((subscribe) => {+ const disposableCollection = new DisposableCollection();+ isOpen && subscribe.next({ selectionRanges, disposableCollection });+ return () => {+ disposableCollection.dispose();+ };+ })+ ),+ // _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 = '';+ }+ })+ )+ .subscribe(({ disposableCollection, selectionRanges }) => {+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();+ this.openPanel();+ disposableCollection.add(+ this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ priority: 99,+ handler: (cell, location, next) => {+ const { row, col } = location;+ if (+ selectionRanges.find(+ (range) =>+ range.startColumn <= col &&+ range.endColumn >= col &&+ range.startRow <= row &&+ range.endRow >= row+ )+ ) {+ 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();+ }+ const info = getPatternPreview(this._previewPattern, value as number);+ if (info.color) {+ const colorMap = this._themeService.getCurrentTheme();+ const color = colorMap[`${info.color}500`];+ return {+ ...cell,+ v: info.result,+ t: CellValueType.STRING,+ s: { cl: { rgb: color } },+ };+ }+ return {+ ...cell,+ v: info.result,+ t: CellValueType.STRING,+ };+ }+ return next();+ },+ })+ );+ this._renderManagerService.getRenderById(workbook.getUnitId())?.mainComponent?.makeDirty();+ })+ )+ );+ }++ /**+ * 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 _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/hooks/usePatternPreview.ts b/packages/sheets-plugin-numfmt/src/hooks/usePatternPreview.tsnew file mode 100644index 0000000000..6cabf818ef--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/hooks/usePatternPreview.ts@@ -0,0 +1,21 @@+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.tsnew file mode 100644index 0000000000..4d579cb51e--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/index.node.ts@@ -0,0 +1 @@+export * from './numfmt-plugin.node';diff --git a/packages/sheets-plugin-numfmt/src/index.ts b/packages/sheets-plugin-numfmt/src/index.tsindex ce2bc9283c..810e690a4a 100644--- a/packages/sheets-plugin-numfmt/src/index.ts+++ b/packages/sheets-plugin-numfmt/src/index.ts@@ -1,3 +1 @@-import './register-action';-export * from './numfmt-plugin';diff --git a/packages/sheets-plugin-numfmt/src/interfaces/i-numfmt-plugin-config.ts b/packages/sheets-plugin-numfmt/src/interfaces/i-numfmt-plugin-config.tsdeleted file mode 100644index 4e214eb71c..0000000000--- a/packages/sheets-plugin-numfmt/src/interfaces/i-numfmt-plugin-config.ts+++ /dev/null@@ -1 +0,0 @@-export interface INumfmtPluginConfig {}diff --git a/packages/sheets-plugin-numfmt/src/interfaces/index.ts b/packages/sheets-plugin-numfmt/src/interfaces/index.tsdeleted file mode 100644index 3584ec6a35..0000000000--- a/packages/sheets-plugin-numfmt/src/interfaces/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from './i-numfmt-plugin-config';diff --git a/packages/sheets-plugin-numfmt/src/locale/en-US.ts b/packages/sheets-plugin-numfmt/src/locale/en-US.tsindex 55df63ca48..57bbf1b6ca 100644--- a/packages/sheets-plugin-numfmt/src/locale/en-US.ts+++ b/packages/sheets-plugin-numfmt/src/locale/en-US.ts@@ -1,238 +1,25 @@-export default {- currencyDetail: {- RMB: 'RMB',- USdollar: 'US dollar',- EUR: 'EUR',- GBP: 'GBP',- HK: 'HK',- JPY: 'JPY',- AlbanianLek: 'Albanian Lek',- AlgerianDinar: 'Algerian Dinar',- Afghani: 'Afghani',- ArgentinePeso: 'Argentine Peso',- UnitedArabEmiratesDirham: 'United Arab Emirates Dirham',- ArubanFlorin: 'Aruban Florin',- OmaniRial: 'Omani Rial',- Azerbaijanimanat: 'Azerbaijani manat',- EgyptianPound: 'Egyptian Pound',- EthiopianBirr: 'Ethiopian Birr',- AngolaKwanza: 'Angola Kwanza',- AustralianDollar: 'Australian Dollar',- Patacas: 'Patacas',- BarbadosDollar: 'Barbados Dollar',- PapuaNewGuineaKina: 'Papua New Guinea Kina',- BahamianDollar: 'Bahamian Dollar',- PakistanRupee: 'Pakistan Rupee',- ParaguayanGuarani: 'Paraguayan Guarani',- BahrainiDinar: 'Bahraini Dinar',- PanamanianBalboa: 'Panamanian Balboa',- Brazilianreal: 'Brazilian real',- Belarusianruble: 'Belarusian ruble',- BermudianDollar: 'Bermudian Dollar',- BulgarianLev: 'Bulgarian Lev',- IcelandKrona: 'Iceland Krona',- BosniaHerzegovinaConvertibleMark: 'Bosnia-Herzegovina Convertible Mark',- PolishZloty: 'Polish Zloty',- Boliviano: 'Boliviano',- BelizeDollar: 'Belize Dollar',- BotswanaPula: 'Botswana Pula',- NotDannuzhamu: 'Not Dannuzhamu',- BurundiFranc: 'Burundi Franc',- NorthKoreanWon: 'North Korean Won',- DanishKrone: 'Danish Krone',- EastCaribbeanDollar: 'East Caribbean Dollar',- DominicaPeso: 'Dominica Peso',- RussianRuble: 'Russian Ruble',- EritreanNakfa: 'Eritrean Nakfa',- CFAfranc: 'CFA franc',- PhilippinePeso: 'Philippine Peso',- FijiDollar: 'Fiji Dollar',- CapeVerdeEscudo: 'Cape Verde Escudo',- FalklandIslandsPound: 'Falkland Islands Pound',- GambianDalasi: 'Gambian Dalasi',- Congolesefranc: 'Congolese franc',- ColombianPeso: 'Colombian Peso',- CostaRicanColon: 'Costa Rican Colon',- CubanPeso: 'Cuban Peso',- Cubanconvertiblepeso: 'Cuban convertible peso',- GuyanaDollar: 'Guyana Dollar',- KazakhstanTenge: 'Kazakhstan Tenge',- Haitiangourde: 'Haitian gourde',- won: 'won',- NetherlandsAntillesGuilder: 'Netherlands Antilles Guilder',- Honduraslempiras: 'Honduras lempiras',- DjiboutiFranc: 'Djibouti Franc',- KyrgyzstanSom: 'Kyrgyzstan Som',- GuineaFranc: 'Guinea Franc',- CanadianDollar: 'Canadian Dollar',- GhanaianCedi: 'Ghanaian Cedi',- Cambodianriel: 'Cambodian riel',- CzechKoruna: 'Czech Koruna',- ZimbabweDollar: 'Zimbabwe Dollar',- QatariRiyal: 'Qatari Riyal',- CaymanIslandsDollar: 'Cayman Islands Dollar',- Comorianfranc: 'Comorian franc',- KuwaitiDinar: 'Kuwaiti Dinar',- CroatianKuna: 'Croatian Kuna',- KenyanShilling: 'Kenyan Shilling',- LesothoLoti: 'Lesotho Loti',- LaoKip: 'Lao Kip',- LebanesePound: 'Lebanese Pound',- Lithuanianlitas: 'Lithuanian litas',- LibyanDinar: 'Libyan Dinar',- LiberianDollar: 'Liberian Dollar',- RwandaFranc: 'Rwanda Franc',- RomanianLeu: 'Romanian Leu',- MalagasyAriary: 'Malagasy Ariary',- MaldivianRufiyaa: 'Maldivian Rufiyaa',- MalawiKwacha: 'Malawi Kwacha',- MalaysianRinggit: 'Malaysian Ringgit',- MacedoniawearingDinar: 'Macedonia wearing Dinar',- MauritiusRupee: 'Mauritius Rupee',- MauritanianOuguiya: 'Mauritanian Ouguiya',- MongolianTugrik: 'Mongolian Tugrik',- BangladeshiTaka: 'Bangladeshi Taka',- PeruvianNuevoSol: 'Peruvian Nuevo Sol',- MyanmarKyat: 'Myanmar Kyat',- MoldovanLeu: 'Moldovan Leu',- MoroccanDirham: 'Moroccan Dirham',- MozambiqueMetical: 'Mozambique Metical',- MexicanPeso: 'Mexican Peso',- NamibianDollar: 'Namibian Dollar',- SouthAfricanRand: 'South African Rand',- SouthSudanesePound: 'South Sudanese Pound',- NicaraguaCordoba: 'Nicaragua Cordoba',- NepaleseRupee: 'Nepalese Rupee',- NigerianNaira: 'Nigerian Naira',- NorwegianKrone: 'Norwegian Krone',- GeorgianLari: 'Georgian Lari',- RMBOffshore: 'RMB (Offshore)',- SwedishKrona: 'Swedish Krona',- SwissFranc: 'Swiss Franc',- SerbianDinar: 'Serbian Dinar',- SierraLeone: 'Sierra Leone',- SeychellesRupee: 'Seychelles Rupee',- SaudiRiyal: 'Saudi Riyal',- SaoTomeDobra: 'Sao Tome Dobra',- SaintHelenapound: 'Saint Helena pound',- SriLankaRupee: 'Sri Lanka Rupee',- SwazilandLilangeni: 'Swaziland Lilangeni',- SudanesePound: 'Sudanese Pound',- Surinamesedollar: 'Surinamese dollar',- SolomonIslandsDollar: 'Solomon Islands Dollar',- SomaliShilling: 'Somali Shilling',- TajikistanSomoni: 'Tajikistan Somoni',- PacificFranc: 'Pacific Franc',- ThaiBaht: 'Thai Baht',- TanzanianShilling: 'Tanzanian Shilling',- TonganPaanga: "Tongan Pa'anga",- TrinidadandTobagoDollar: 'Trinidad and Tobago Dollar',- TunisianDinar: 'Tunisian Dinar',- TurkishLira: 'Turkish Lira',- VanuatuVatu: 'Vanuatu Vatu',- GuatemalanQuetzal: 'Guatemalan Quetzal',- CommissionBolivar: 'Commission Bolivar',- BruneiDollar: 'Brunei Dollar',- UgandanShilling: 'Ugandan Shilling',- UkrainianHryvnia: 'Ukrainian Hryvnia',- UruguayanPeso: 'Uruguayan Peso',- Uzbekistansom: 'Uzbekistan som',- WesternSamoaTala: 'Western Samoa Tala',- SingaporeDollar: 'Singapore Dollar',- NT: 'NT',- NewZealandDollar: 'New Zealand Dollar',- HungarianForint: 'Hungarian Forint',- SyrianPound: 'Syrian Pound',- JamaicanDollar: 'Jamaican Dollar',- ArmenianDram: 'Armenian Dram',- YemeniRial: 'Yemeni Rial',- IraqiDinar: 'Iraqi Dinar',- IranianRial: 'Iranian Rial',- NewIsraeliShekel: 'New Israeli Shekel',- IndianRupee: 'Indian Rupee',- IndonesianRupiah: 'Indonesian Rupiah',- JordanianDinar: 'Jordanian Dinar',- VND: 'VND',- ZambianKwacha: 'Zambian Kwacha',- GibraltarPound: 'Gibraltar Pound',- ChileanPeso: 'Chilean Peso',- CFAFrancBEAC: 'CFA Franc BEAC',- },- defaultFmt: {- Automatic: {- text: 'Automatic',- value: 'General',- example: '',- },- Number: {- text: 'Number',- value: '##0.00',- example: '1000.12',- },- Percent: {- text: 'Percent',- value: '#0.00%',- example: '12.21%',- },- PlainText: {- text: 'Plain text',- value: '@',- example: '',- },- Scientific: {- text: 'Scientific',- value: '0.00E+00',- example: '1.01E+5',- },- Accounting: {- text: 'Accounting',- value: '¥(0.00)',- example: '¥(1200.09)',- },- Thousand: {- text: 'Ten Thousand',- value: 'w',- example: '1亿2000万2500',- },- Currency: {- text: 'Currency',- value: '¥0.00',- example: '¥1200.09',- },- Digit: {- text: '万元2位小数',- value: 'w0.00',- example: '2万2500.55',- },- Date: {- text: 'Date',- value: 'yyyy-MM-dd',- example: '2017-11-29',- },- Time: {- text: 'Time',- value: 'hh:mm AM/PM',- example: '3:00 PM',- },- Time24H: {- text: 'Time 24H',- value: 'hh:mm',- example: '15:00',- },- DateTime: {- text: 'Date time',- value: 'yyyy-MM-dd hh:mm AM/PM',- example: '2017-11-29 3:00 PM',- },- DateTime24H: {- text: 'Date time 24H',- value: 'yyyy-MM-dd hh:mm',- example: '2017-11-29 15:00',- },- CustomFormats: {- text: 'Custom Formats',- value: 'fmtOtherSelf',- example: '',+export const zhCn = {+ sheet: {+ numfmt: {+ title: '数据格式',+ numfmtType: '格式类型',+ cancel: '取消',+ confirm: '确认',+ general: '常规',+ accounting: '会计',+ currency: '货币',+ date: '日期',+ thousandthPercentile: '千分为符',+ preview: '示例',+ decimalLength: '小数位数',+ currencyType: '货币类型',+ currencyDes: '货币格式用于表示一般货币数值。会计格式可以对一列数值进行小数点对齐',+ accountingDes: '会计数字格式可对一列数值进行货币符号和小数点对齐',+ dateType: '日期类型',+ dateDes: '日期格式将日期和时间系列数值品示为日期值。',+ negType: '负数类型',+ generalDes: '常规格式不包含任何特定的数字格式。',+ thousandthPercentileDes: '千分位符格式用于一般数字的表示。货币和会计格式则提供货币值计算的专用格式。',},},};diff --git a/packages/sheets-plugin-numfmt/src/locale/index.ts b/packages/sheets-plugin-numfmt/src/locale/index.tsindex b0b1d48d5d..e69de29bb2 100644--- a/packages/sheets-plugin-numfmt/src/locale/index.ts+++ b/packages/sheets-plugin-numfmt/src/locale/index.ts@@ -1,2 +0,0 @@-export { default as enUS } from './en-US';-export { default as zhCN } from './zh-CN';diff --git a/packages/sheets-plugin-numfmt/src/locale/zh-CN.ts b/packages/sheets-plugin-numfmt/src/locale/zh-CN.tsindex 4ebf3fa5ab..57bbf1b6ca 100644--- a/packages/sheets-plugin-numfmt/src/locale/zh-CN.ts+++ b/packages/sheets-plugin-numfmt/src/locale/zh-CN.ts@@ -1,238 +1,25 @@-export default {- currencyDetail: {- RMB: '人民币',- USdollar: '美元',- EUR: '欧元',- GBP: '英镑',- HK: '港元',- JPY: '日元',- AlbanianLek: '阿尔巴尼亚列克',- AlgerianDinar: '阿尔及利亚第纳尔',- Afghani: '阿富汗尼',- ArgentinePeso: '阿根廷比索',- UnitedArabEmiratesDirham: '阿拉伯联合酋长国迪拉姆',- ArubanFlorin: '阿鲁巴弗罗林',- OmaniRial: '阿曼里亚尔',- Azerbaijanimanat: '阿塞拜疆马纳特',- EgyptianPound: '埃及镑',- EthiopianBirr: '埃塞俄比亚比尔',- AngolaKwanza: '安哥拉宽扎',- AustralianDollar: '澳大利亚元',- Patacas: '澳门元',- BarbadosDollar: '巴巴多斯元',- PapuaNewGuineaKina: '巴布亚新几内亚基那',- BahamianDollar: '巴哈马元',- PakistanRupee: '巴基斯坦卢比',- ParaguayanGuarani: '巴拉圭瓜拉尼',- BahrainiDinar: '巴林第纳尔',- PanamanianBalboa: '巴拿马巴波亚',- Brazilianreal: '巴西里亚伊',- Belarusianruble: '白俄罗斯卢布',- BermudianDollar: '百慕大元',- BulgarianLev: '保加利亚列弗',- IcelandKrona: '冰岛克朗',- BosniaHerzegovinaConvertibleMark: '波黑可兑换马克',- PolishZloty: '波兰兹罗提',- Boliviano: '玻利维亚诺',- BelizeDollar: '伯利兹元',- BotswanaPula: '博茨瓦纳普拉',- NotDannuzhamu: '不丹努扎姆',- BurundiFranc: '布隆迪法郎',- NorthKoreanWon: '朝鲜圆',- DanishKrone: '丹麦克朗',- EastCaribbeanDollar: '东加勒比元',- DominicaPeso: '多米尼加比索',- RussianRuble: '俄国卢布',- EritreanNakfa: '厄立特里亚纳克法',- CFAfranc: '非洲金融共同体法郎',- PhilippinePeso: '菲律宾比索',- FijiDollar: '斐济元',- CapeVerdeEscudo: '佛得角埃斯库多',- FalklandIslandsPound: '福克兰群岛镑',- GambianDalasi: '冈比亚达拉西',- Congolesefranc: '刚果法郎',- ColombianPeso: '哥伦比亚比索',- CostaRicanColon: '哥斯达黎加科朗',- CubanPeso: '古巴比索',- Cubanconvertiblepeso: '古巴可兑换比索',- GuyanaDollar: '圭亚那元',- KazakhstanTenge: '哈萨克斯坦坚戈',- Haitiangourde: '海地古德',- won: '韩元',- NetherlandsAntillesGuilder: '荷属安的列斯盾',- Honduraslempiras: '洪都拉斯拉伦皮拉',- DjiboutiFranc: '吉布提法郎',- KyrgyzstanSom: '吉尔吉斯斯坦索姆',- GuineaFranc: '几内亚法郎',- CanadianDollar: '加拿大元',- GhanaianCedi: '加纳塞地',- Cambodianriel: '柬埔寨瑞尔',- CzechKoruna: '捷克克朗',- ZimbabweDollar: '津巴布韦元',- QatariRiyal: '卡塔尔里亚尔',- CaymanIslandsDollar: '开曼群岛元',- Comorianfranc: '科摩罗法郎',- KuwaitiDinar: '科威特第纳尔',- CroatianKuna: '克罗地亚库纳',- KenyanShilling: '肯尼亚先令',- LesothoLoti: '莱索托洛蒂',- LaoKip: '老挝基普',- LebanesePound: '黎巴嫩镑',- Lithuanianlitas: '立陶宛立特',- LibyanDinar: '利比亚第纳尔',- LiberianDollar: '利比亚元',- RwandaFranc: '卢旺达法郎',- RomanianLeu: '罗马尼亚列伊',- MalagasyAriary: '马达加斯加阿里亚里',- MaldivianRufiyaa: '马尔代夫拉菲亚',- MalawiKwacha: '马拉维克瓦查',- MalaysianRinggit: '马来西亚林吉特',- MacedoniawearingDinar: '马其顿戴第纳尔',- MauritiusRupee: '毛里求斯卢比',- MauritanianOuguiya: '毛里塔尼亚乌吉亚',- MongolianTugrik: '蒙古图格里克',- BangladeshiTaka: '孟加拉塔卡',- PeruvianNuevoSol: '秘鲁新索尔',- MyanmarKyat: '缅甸开亚特',- MoldovanLeu: '摩尔多瓦列伊',- MoroccanDirham: '摩洛哥迪拉姆',- MozambiqueMetical: '莫桑比克梅蒂卡尔',- MexicanPeso: '墨西哥比索',- NamibianDollar: '纳米比亚元',- SouthAfricanRand: '南非兰特',- SouthSudanesePound: '南苏丹镑',- NicaraguaCordoba: '尼加拉瓜科多巴',- NepaleseRupee: '尼泊尔卢比',- NigerianNaira: '尼日利亚奈拉',- NorwegianKrone: '挪威克朗',- GeorgianLari: '乔治亚拉瑞',- RMBOffshore: '人民币(离岸)',- SwedishKrona: '瑞典克朗',- SwissFranc: '瑞士法郎',- SerbianDinar: '塞尔维亚第纳尔',- SierraLeone: '塞拉利昂利昂',- SeychellesRupee: '塞舌尔卢比',- SaudiRiyal: '沙特里亚尔',- SaoTomeDobra: '圣多美多布拉',- SaintHelenapound: '圣赫勒拿群岛磅',- SriLankaRupee: '斯里兰卡卢比',- SwazilandLilangeni: '斯威士兰里兰吉尼',- SudanesePound: '苏丹镑',- Surinamesedollar: '苏里南元',- SolomonIslandsDollar: '所罗门群岛元',- SomaliShilling: '索马里先令',- TajikistanSomoni: '塔吉克斯坦索莫尼',- PacificFranc: '太平洋法郎',- ThaiBaht: '泰国铢',- TanzanianShilling: '坦桑尼亚先令',- TonganPaanga: '汤加潘加',- TrinidadandTobagoDollar: '特立尼达和多巴哥元',- TunisianDinar: '突尼斯第纳尔',- TurkishLira: '土耳其里拉',- VanuatuVatu: '瓦努阿图瓦图',- GuatemalanQuetzal: '危地马拉格查尔',- CommissionBolivar: '委内瑞拉博利瓦',- BruneiDollar: '文莱元',- UgandanShilling: '乌干达先令',- UkrainianHryvnia: '乌克兰格里夫尼亚',- UruguayanPeso: '乌拉圭比索',- Uzbekistansom: '乌兹别克斯坦苏姆',- WesternSamoaTala: '西萨摩亚塔拉',- SingaporeDollar: '新加坡元',- NT: '新台币',- NewZealandDollar: '新西兰元',- HungarianForint: '匈牙利福林',- SyrianPound: '叙利亚镑',- JamaicanDollar: '牙买加元',- ArmenianDram: '亚美尼亚德拉姆',- YemeniRial: '也门里亚尔',- IraqiDinar: '伊拉克第纳尔',- IranianRial: '伊朗里亚尔',- NewIsraeliShekel: '以色列新谢克尔',- IndianRupee: '印度卢比',- IndonesianRupiah: '印度尼西亚卢比',- JordanianDinar: '约旦第纳尔',- VND: '越南盾',- ZambianKwacha: '赞比亚克瓦查',- GibraltarPound: '直布罗陀镑',- ChileanPeso: '智利比索',- CFAFrancBEAC: '中非金融合作法郎',- },- defaultFmt: {- Automatic: {- text: '自动',- value: 'General',- example: '',- },- Number: {- text: '数字',- value: '##0.00',- example: '1000.12',- },- Percent: {- text: '百分比',- value: '#0.00%',- example: '12.21%',- },- PlainText: {- text: '纯文本',- value: '@',- example: '',- },- Scientific: {- text: '科学计数',- value: '0.00E+00',- example: '1.01E+5',- },- Accounting: {- text: '会计',- value: '¥(0.00)',- example: '¥(1200.09)',- },- Thousand: {- text: '万元',- value: 'w',- example: '1亿2000万2500',- },- Currency: {- text: '货币',- value: '¥0.00',- example: '¥1200.09',- },- Digit: {- text: '万元2位小数',- value: 'w0.00',- example: '2万2500.55',- },- Date: {- text: '日期',- value: 'yyyy-MM-dd',- example: '2017-11-29',- },- Time: {- text: '时间',- value: 'hh:mm AM/PM',- example: '3:00 PM',- },- Time24H: {- text: '时间24H',- value: 'hh:mm',- example: '15:00',- },- DateTime: {- text: '日期时间',- value: 'yyyy-MM-dd hh:mm AM/PM',- example: '2017-11-29 3:00 PM',- },- DateTime24H: {- text: '日期时间24H',- value: 'yyyy-MM-dd hh:mm',- example: '2017-11-29 15:00',- },- CustomFormats: {- text: '自定义格式',- value: 'fmtOtherSelf',- example: '',+export const zhCn = {+ sheet: {+ numfmt: {+ title: '数据格式',+ numfmtType: '格式类型',+ cancel: '取消',+ confirm: '确认',+ general: '常规',+ accounting: '会计',+ currency: '货币',+ date: '日期',+ thousandthPercentile: '千分为符',+ preview: '示例',+ decimalLength: '小数位数',+ currencyType: '货币类型',+ currencyDes: '货币格式用于表示一般货币数值。会计格式可以对一列数值进行小数点对齐',+ accountingDes: '会计数字格式可对一列数值进行货币符号和小数点对齐',+ dateType: '日期类型',+ dateDes: '日期格式将日期和时间系列数值品示为日期值。',+ negType: '负数类型',+ generalDes: '常规格式不包含任何特定的数字格式。',+ thousandthPercentileDes: '千分位符格式用于一般数字的表示。货币和会计格式则提供货币值计算的专用格式。',},},};diff --git a/packages/sheets-plugin-numfmt/src/menu/menu.ts b/packages/sheets-plugin-numfmt/src/menu/menu.tsnew file mode 100644index 0000000000..31ce1b72a9--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/menu/menu.ts@@ -0,0 +1,111 @@+import { SelectionManagerService } from '@univerjs/base-sheets';+import { ComponentManager, IMenuButtonItem, 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 { Observable } from 'rxjs';++import { AddDecimalCommand } from '../commands/commands/add.decimal.command';+import { SetCurrencyCommand } from '../commands/commands/set.currency.command';+import { SubtractDecimalCommand } from '../commands/commands/subtract.decimal.command';+import { OpenNumfmtPanelOperator } from '../commands/operators/open.numfmt.panel.operator';+import { isAccountingPanel } from '../components/accounting';+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 { NumfmtService } from '../service/numfmt.service';++export const CurrencyMenuItem = (componentManager: ComponentManager) => {+ const iconKey = 'icon-rmbSingle';+ componentManager.register(iconKey, RmbSingle);+ componentManager.register('MoreDownSingle', MoreDownSingle);+ return () => ({+ icon: iconKey,+ id: SetCurrencyCommand.id,+ title: 'numfmt.menu.currency',+ tooltip: 'numfmt.menu.currency',+ type: MenuItemType.BUTTON,+ group: MenuGroup.TOOLBAR_FORMULAS_INSERT,+ positions: [MenuPosition.TOOLBAR_START],+ });+};++export const AddDecimalMenuItem = (componentManager: ComponentManager) => {+ const iconKey = 'icon-addDigitsSingle';+ componentManager.register(iconKey, AddDigitsSingle);+ return () => ({+ icon: iconKey,+ id: AddDecimalCommand.id,+ title: 'numfmt.menu.add.decimal',+ tooltip: 'numfmt.menu.add.decimal',+ type: MenuItemType.BUTTON,+ positions: [MenuPosition.TOOLBAR_START],+ group: MenuGroup.TOOLBAR_FORMULAS_INSERT,+ });+};+export const SubtractDecimalMenuItem = (componentManager: ComponentManager) => {+ const iconKey = 'icon-reduceDigitsSingle';+ componentManager.register(iconKey, ReduceDigitsSingle);+ return () => ({+ icon: iconKey,+ id: SubtractDecimalCommand.id,+ title: 'numfmt.menu.subtract.decimal',+ tooltip: 'numfmt.menu.subtract.decimal',+ type: MenuItemType.BUTTON,+ group: MenuGroup.TOOLBAR_FORMULAS_INSERT,+ positions: [MenuPosition.TOOLBAR_START],+ });+};++export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {+ componentManager.register('sheet.numfmt.moreNumfmtType', MoreNumfmtType);+ return (_accessor: IAccessor) => {+ const numfmtService = _accessor.get(NumfmtService);+ const univerInstanceService = _accessor.get(IUniverInstanceService);+ const selectionManagerService = _accessor.get(SelectionManagerService);+ const value$ = new Observable((subscribe) =>+ selectionManagerService.selectionInfo$.subscribe((selections) => {+ if (selections && selections[0]) {+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();+ const range = selections[0].range;+ const row = range.startRow;+ const col = range.startColumn;+ const numfmtValue = numfmtService.getValue(workbook.getUnitId(), worksheet.getSheetId(), row, col);+ let value: string = '常规';++ if (numfmtValue) {+ const pattern = numfmtValue.pattern;+ if (isAccountingPanel(pattern)) {+ value = '会计';+ }++ if (isCurrencyPanel(pattern)) {+ value = '货币';+ }++ if (isDatePanel(pattern)) {+ value = '日期';+ }+ if (isThousandthPercentilePanel(pattern)) {+ value = '千分位';+ }+ }+ subscribe.next(value);+ }+ })+ );+ return {+ // icon: 'MoreDownSingle',+ label: 'sheet.numfmt.moreNumfmtType',+ id: OpenNumfmtPanelOperator.id,+ // title: 'numfmt.menu.preview',+ tooltip: 'numfmt.menu.preview',+ type: MenuItemType.BUTTON,+ group: MenuGroup.TOOLBAR_FORMULAS_INSERT,+ positions: [MenuPosition.TOOLBAR_START],+ value$,+ } as IMenuButtonItem;+ };+};diff --git a/packages/sheets-plugin-numfmt/src/model/action/index.ts b/packages/sheets-plugin-numfmt/src/model/action/index.tsdeleted file mode 100644index 4193ef116d..0000000000--- a/packages/sheets-plugin-numfmt/src/model/action/index.ts+++ /dev/null@@ -1 +0,0 @@-// export * from './set-numfmt-range-data-action';diff --git a/packages/sheets-plugin-numfmt/src/model/action/set-numfmt-range-data-action.ts b/packages/sheets-plugin-numfmt/src/model/action/set-numfmt-range-data-action.tsdeleted file mode 100644index 3e89d44d97..0000000000--- a/packages/sheets-plugin-numfmt/src/model/action/set-numfmt-range-data-action.ts+++ /dev/null@@ -1,38 +0,0 @@-// import { SheetActionBase, ActionObservers, ISheetActionData, ObjectMatrixPrimitiveType, CommandUnit } from '@univerjs/core';-// import { SetNumfmtRangeData } from '../apply';-// import { NumfmtController } from '../../controller';--// export interface ISetNumfmtRangeActionData extends ISheetActionData {-// numfmtMatrix: ObjectMatrixPrimitiveType<string>;-// }--// export class SetNumfmtRangeDataAction extends SheetActionBase<ISetNumfmtRangeActionData, ISetNumfmtRangeActionData> {-// constructor(actionData: ISetNumfmtRangeActionData, commandUnit: CommandUnit, observers: ActionObservers) {-// super(actionData, commandUnit, observers);-// this._doActionData = {-// ...actionData,-// };-// this._oldActionData = {-// ...actionData,-// numfmtMatrix: this.do(),-// };-// }--// do(): ObjectMatrixPrimitiveType<string> {-// return this.redo();-// }--// redo(): ObjectMatrixPrimitiveType<string> {-// const { injector } = this._doActionData;-// return SetNumfmtRangeData(this, this._doActionData.sheetId, this._doActionData.numfmtMatrix, injector!.get(NumfmtController));-// }--// undo(): void {-// const { injector } = this._oldActionData;-// SetNumfmtRangeData(this, this._oldActionData.sheetId, this._oldActionData.numfmtMatrix, injector!.get(NumfmtController));-// }--// validate(): boolean {-// return false;-// }-// }diff --git a/packages/sheets-plugin-numfmt/src/model/apply/index.ts b/packages/sheets-plugin-numfmt/src/model/apply/index.tsdeleted file mode 100644index 9717230cd4..0000000000--- a/packages/sheets-plugin-numfmt/src/model/apply/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from './set-numfmt-range-data';diff --git a/packages/sheets-plugin-numfmt/src/model/apply/set-numfmt-range-data.ts b/packages/sheets-plugin-numfmt/src/model/apply/set-numfmt-range-data.tsdeleted file mode 100644index 02b05dc1db..0000000000--- a/packages/sheets-plugin-numfmt/src/model/apply/set-numfmt-range-data.ts+++ /dev/null@@ -1,20 +0,0 @@-import { ObjectMatrix, ObjectMatrixPrimitiveType, Workbook } from '@univerjs/core';--import { NumfmtController } from '../../controllers';--export function SetNumfmtRangeData(- workbook: Workbook,- sheetId: string,- numfmtPrimitiveMatrix: ObjectMatrixPrimitiveType<string>,- _numfmtController: NumfmtController-): ObjectMatrixPrimitiveType<string> {- const numfmtConfig = _numfmtController.getNumfmtBySheetIdConfig(sheetId);- const currSheetNumfmtMatrix = new ObjectMatrix(numfmtConfig);- const olderSheetNumfmtMatrix = new ObjectMatrix<string>();- new ObjectMatrix(numfmtPrimitiveMatrix).forValue((r, c, value) => {- const olderValue = currSheetNumfmtMatrix.getValue(r, c);- currSheetNumfmtMatrix.setValue(r, c, value);- olderSheetNumfmtMatrix.setValue(r, c, olderValue);- });- return olderSheetNumfmtMatrix.toJSON();-}diff --git a/packages/sheets-plugin-numfmt/src/model/index.ts b/packages/sheets-plugin-numfmt/src/model/index.tsdeleted file mode 100644index b2b65fd696..0000000000--- a/packages/sheets-plugin-numfmt/src/model/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './apply';-export * from './numfmt-model';diff --git a/packages/sheets-plugin-numfmt/src/model/numfmt-model.ts b/packages/sheets-plugin-numfmt/src/model/numfmt-model.tsdeleted file mode 100644index a0d5738f43..0000000000--- a/packages/sheets-plugin-numfmt/src/model/numfmt-model.ts+++ /dev/null@@ -1,19 +0,0 @@-import { ObjectMatrixPrimitiveType } from '@univerjs/core';--export class NumfmtModel {- protected _sheetsNumfmtConfig: Map<string, ObjectMatrixPrimitiveType<string>>;-- constructor() {- this._sheetsNumfmtConfig = new Map();- }-- getNumfmtBySheetIdConfig(sheetId: string): ObjectMatrixPrimitiveType<string> {- let sheetNumfmtMatrix = this._sheetsNumfmtConfig.get(sheetId);- if (sheetNumfmtMatrix) {- return sheetNumfmtMatrix;- }- sheetNumfmtMatrix = {};- this._sheetsNumfmtConfig.set(sheetId, sheetNumfmtMatrix);- return sheetNumfmtMatrix;- }-}diff --git a/packages/sheets-plugin-numfmt/src/numfmt-plugin.node.ts b/packages/sheets-plugin-numfmt/src/numfmt-plugin.node.tsnew file mode 100644index 0000000000..9a9b162732--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/numfmt-plugin.node.ts@@ -0,0 +1,16 @@+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';++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([NumfmtService]);+ }+}diff --git a/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts b/packages/sheets-plugin-numfmt/src/numfmt-plugin.tsindex 4452e3f3f9..643b6f5ac1 100644--- a/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts+++ b/packages/sheets-plugin-numfmt/src/numfmt-plugin.ts@@ -1,80 +1,18 @@-import { IRange, LocaleService, ObjectMatrixPrimitiveType, Plugin, PluginType } from '@univerjs/core';-import { Dependency, Inject, Injector } from '@wendellhu/redi';+import { Plugin, PluginType } from '@univerjs/core';+import { Inject, Injector } from '@wendellhu/redi';-import { NUMFMT_PLUGIN_NAME } from './basics';-import { NumfmtController, NumfmtModalController } from './controllers';-import { INumfmtPluginConfig } from './interfaces';-import { enUS } from './locale';-import { NumfmtModel } from './model';-import { NumfmtService } from './services/numfmt.service';-import { INumfmtPluginData } from './symbol';+import { SHEET_NUMFMT_PLUGIN } from './base/const/PLUGIN_NAME';+import { NumfmtController } from './controllers/numfmt.controller';+import { NumfmtService } from './service/numfmt.service';export class NumfmtPlugin extends Plugin {static override type = PluginType.Sheet;-- private _numfmtModalController!: NumfmtModalController;-- private _numfmtController!: NumfmtController;-- private _numfmtPluginData: NumfmtModel;-- constructor(- config: Partial<INumfmtPluginConfig>,- @Inject(LocaleService) private readonly _localeService: LocaleService,- @Inject(Injector) override readonly _injector: Injector- ) {- super(NUMFMT_PLUGIN_NAME);-- this._numfmtPluginData = new NumfmtModel();- this._injector.add([INumfmtPluginData, { useFactory: () => this._numfmtPluginData }]);- }-- override onRendered(): void {- this.initializeDependencies(this._injector);- this.registerExtension();- this._numfmtController = this._injector.get(NumfmtController);- this._numfmtModalController = this._injector.get(NumfmtModalController);- this._localeService.load({ enUS });- // actionRegister.add(this._numfmtActionExtensionFactory);- }-- override onDestroy(): void {- super.onDestroy();- // const actionRegister = this._commandManager.getActionExtensionManager().getRegister();- // actionRegister.delete(this._numfmtActionExtensionFactory);- }-- registerExtension(): void {- // const actionRegister = this._commandManager.getActionExtensionManager().getRegister();- // this._numfmtActionExtensionFactory = new NumfmtActionExtensionFactory(this, this._injector);- // actionRegister.add(this._numfmtActionExtensionFactory);- }-- getNumfmtBySheetIdConfig(sheetId: string): ObjectMatrixPrimitiveType<string> {- return this._numfmtController.getNumfmtBySheetIdConfig(sheetId);- }-- setNumfmtByRange(sheetId: string, range: IRange, format: string): void {- this._numfmtController.setNumfmtByRange(sheetId, range, format);- }-- setNumfmtByCoords(sheetId: string, row: number, column: number, format: string): void {- this._numfmtController.setNumfmtByCoords(sheetId, row, column, format);- }-- getNumfmtModalController(): NumfmtModalController {- return this._numfmtModalController;+ constructor(@Inject(Injector) override readonly _injector: Injector) {+ super(SHEET_NUMFMT_PLUGIN);}- private initializeDependencies(sheetInjector: Injector): void {- // this._injector = new Injector([- // [IRenderingEngine, { useFactory: () => this.getGlobalContext().getPluginManager().getRequirePluginByName<RenderEngine>(PLUGIN_NAMES.BASE_RENDER).getEngine() }],- // [NumfmtController],- // [NumfmtModalController],- // ]);- const dependencies: Dependency[] = [[NumfmtController], [NumfmtModalController], [NumfmtService]];- dependencies.forEach((d) => {- sheetInjector.add(d);- });+ override onStarting(): void {+ this._injector.add([NumfmtService]);+ this._injector.add([NumfmtController]);}}diff --git a/packages/sheets-plugin-numfmt/src/register-action.ts b/packages/sheets-plugin-numfmt/src/register-action.tsdeleted file mode 100644index 32eaeb3649..0000000000--- a/packages/sheets-plugin-numfmt/src/register-action.ts+++ /dev/null@@ -1,7 +0,0 @@-// TODO new command--// import { CommandManager } from '@univerjs/core';-// import { ACTION_NAMES } from './basics/enum';-// import { SetNumfmtRangeDataAction } from './model/action/set-numfmt-range-data-action';--// CommandManager.register(ACTION_NAMES.SET_NUMFMT_RANGE_DATA_ACTION, SetNumfmtRangeDataAction);diff --git a/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts b/packages/sheets-plugin-numfmt/src/service/numfmt.service.tsnew file mode 100644index 0000000000..b4010c7636--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/service/numfmt.service.ts@@ -0,0 +1,65 @@+import {+ Disposable,+ ICellData,+ ICommandService,+ LifecycleStages,+ Nullable,+ ObjectMatrix,+ OnLifecycle,+} from '@univerjs/core';+import { Inject } from '@wendellhu/redi';++import { NumfmtItem } from '../base/types';+import { SetNumfmtMutation } from '../commands/mutations/set.numfmt.mutation';++type NumfmtItemWithCache = NumfmtItem & {+ // when change parameters or pattern, the cache is cleared follow mutation execute+ _cache?: {+ result: ICellData;+ parameters: number; // The parameter that was last calculated+ };+};++@OnLifecycle(LifecycleStages.Ready, NumfmtService)+export class NumfmtService extends Disposable {+ numfmtModel: Map<string, ObjectMatrix<NumfmtItemWithCache>> = new Map();+ // collect effect mutations when edit end and push this to commands stack in next commands progress++ constructor(@Inject(ICommandService) private _commandService: ICommandService) {+ super();+ this._initCommands();+ }++ private _initCommands() {+ [SetNumfmtMutation].forEach((config) => this.disposeWithMe(this._commandService.registerCommand(config)));+ }++ getValue(workbookId: string, worksheetId: string, row: number, col: number) {+ const model = this.getModel(workbookId, worksheetId);+ if (!model) {+ return null;+ }+ return model.getValue(row, col);+ }++ setValue(workbookId: string, worksheetId: string, row: number, col: number, value: Nullable<NumfmtItem>) {+ let model = this.getModel(workbookId, worksheetId);+ if (!model) {+ const key = getModelKey(workbookId, worksheetId);+ model = new ObjectMatrix();+ this.numfmtModel.set(key, model);+ }+ if (value) {+ model.setValue(row, col, value);+ } else {+ model.realDeleteValue(row, col);+ }+ }++ getModel(workbookId: string, worksheetId: string) {+ const key = getModelKey(workbookId, worksheetId);+ return this.numfmtModel.get(key);+ }+}++const getModelKey = (workbookId: string, worksheetId: string) => `${workbookId}_${worksheetId}`;diff --git a/packages/sheets-plugin-numfmt/src/services/numfmt.service.ts b/packages/sheets-plugin-numfmt/src/services/numfmt.service.tsdeleted file mode 100644index ff1f8b625f..0000000000--- a/packages/sheets-plugin-numfmt/src/services/numfmt.service.ts+++ /dev/null@@ -1,11 +0,0 @@-import { Inject } from '@wendellhu/redi';--import { NumfmtModalController } from '../controllers/numfmt-modal-controller';--export class NumfmtService {- constructor(@Inject(NumfmtModalController) private _numfmtModalController: NumfmtModalController) {}-- showModal(type: string) {- this._numfmtModalController.showModal(type, true);- }-}diff --git a/packages/sheets-plugin-numfmt/src/symbol/index.ts b/packages/sheets-plugin-numfmt/src/symbol/index.tsdeleted file mode 100644index 08db317723..0000000000--- a/packages/sheets-plugin-numfmt/src/symbol/index.ts+++ /dev/null@@ -1,5 +0,0 @@-import { createIdentifier } from '@wendellhu/redi';--import { NumfmtModel } from '../model/numfmt-model';--export const INumfmtPluginData = createIdentifier<NumfmtModel>('numfmt-plugin-data');diff --git a/packages/sheets-plugin-numfmt/src/types/index.d.ts b/packages/sheets-plugin-numfmt/src/types/index.d.tsdeleted file mode 100644index 8c2412e6fc..0000000000--- a/packages/sheets-plugin-numfmt/src/types/index.d.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from '../index';-declare module '@univerjs/sheets-plugin-numfmt' {}diff --git a/packages/sheets-plugin-numfmt/src/utils/currency.ts b/packages/sheets-plugin-numfmt/src/utils/currency.tsnew file mode 100644index 0000000000..ff1cc94b3f--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/utils/currency.ts@@ -0,0 +1,6 @@+import { currencySymbols } from '../base/const/CURRENCY-SYMBOLS';++export const getCurrencyType = (pattern: string) => {+ const item = currencySymbols.find((code) => pattern.includes(code));+ return item;+};diff --git a/packages/sheets-plugin-numfmt/src/utils/decimal.ts b/packages/sheets-plugin-numfmt/src/utils/decimal.tsnew file mode 100644index 0000000000..1d2c821607--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/utils/decimal.ts@@ -0,0 +1,69 @@+import numfmt from '@univerjs/base-numfmt-engine';++/**+ * the function decimal just use positive,negative configuration ignored+ */+export const getDecimalFromPattern = (pattern: string, defaultValue: number = 0) => {+ if (!pattern) {+ return defaultValue;+ }++ const info = numfmt.getInfo(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('');++export const setPatternDecimal = (patterns: string, decimalLength: number) => {+ const tokens = patterns.split(';').map((pattern) => {+ if (/\.0?/.test(pattern)) {+ return pattern.replace(+ /\.0*/g,+ `${decimalLength > 0 ? '.' : ''}${getDecimalString(Number(decimalLength || 0))}`+ );+ }+ if (/0([^0]?)|0$/.test(pattern)) {+ return pattern.replace(+ /0([^0]+)|0$/,+ `0${decimalLength > 0 ? '.' : ''}${getDecimalString(Number(decimalLength || 0))}$1`+ );+ }++ return pattern;+ });+ return tokens.join(';');+};++export const isPatternHasDecimal = (pattern: string) => /\.0?/.test(pattern) || /0([^0]?)|0$/.test(pattern);diff --git a/packages/sheets-plugin-numfmt/src/utils/options.ts b/packages/sheets-plugin-numfmt/src/utils/options.tsnew file mode 100644index 0000000000..b8ed222881--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/utils/options.ts@@ -0,0 +1,16 @@+import { currencySymbols } from '../base/const/CURRENCY-SYMBOLS';+import { CURRENCYFORMAT, DATEFMTLISG, NUMBERFORMAT } from '../base/const/FORMATDETAIL';++export const getCurrencyOptions = () => currencySymbols.map((item) => ({ label: item, value: item }));++export const getCurrencyFormatOptions = (suffix: string) =>+ CURRENCYFORMAT.map((item) => ({+ label: item.label(suffix),+ value: item.suffix(suffix),+ color: item.color,+ }));++export const getDateFormatOptions = () => DATEFMTLISG.map((item) => ({ label: item.label, value: item.suffix }));++export const getNumberFormatOptions = () =>+ NUMBERFORMAT.map((item) => ({ label: item.label, value: item.suffix, color: item.color }));diff --git a/packages/sheets-plugin-numfmt/src/utils/pattern.ts b/packages/sheets-plugin-numfmt/src/utils/pattern.tsnew file mode 100644index 0000000000..45f536aafe--- /dev/null+++ b/packages/sheets-plugin-numfmt/src/utils/pattern.ts@@ -0,0 +1,20 @@+import numfmt from '@univerjs/base-numfmt-engine';++import { FormatType } from '../base/types';++export const getPatternType = (pattern: string): FormatType => numfmt.getInfo(pattern).type || 'unknown';+export const getPatternPreview = (pattern: string, value: number) => {+ const info = numfmt.getInfo(pattern);++ const negInfo = info._partitions[1];+ const result = numfmt.format(pattern, value, { locale: 'zh-CN' });+ if (value < 0) {+ return {+ result,+ color: negInfo.color,+ };+ }+ return {+ result,+ };+};diff --git a/packages/sheets-plugin-numfmt/src/views/ui/FormatContent.tsx b/packages/sheets-plugin-numfmt/src/views/ui/FormatContent.tsxdeleted file mode 100644index fea818596f..0000000000--- a/packages/sheets-plugin-numfmt/src/views/ui/FormatContent.tsx+++ /dev/null@@ -1,68 +0,0 @@-import { InputNumber } from '@univerjs/design';-import React, { Component, createRef } from 'react';--import styles from './index.module.less';--interface IProps {- data: any[];- input?: string;- onClick: (value: string) => void;- onChange?: (value: string) => void;-}--interface IState {}--export class FormatContent extends Component<IProps, IState> {- private _ref = createRef<HTMLDivElement>();-- constructor(props: IProps) {- super(props);- this.initialize(props);- }-- initialize(props: IProps) {}-- handleClick(value: string, index: number) {- const lis = this._ref.current?.querySelectorAll('li');- if (!lis) return;- for (let i = 0; i < lis.length; i++) {- lis[i].classList.remove(styles.formatSelected);- }-- lis[index].classList.add(styles.formatSelected);-- this.props.onClick(value);- }-- handleChange(value: number | null) {- this.props.onChange?.(value?.toString() ?? '');- }-- /**- * Render the component's HTML- *- * @returns {void}- */- override render() {- const { data, input } = this.props;-- return (- <div className={styles.formatContent} ref={this._ref}>- input && (- <div className={styles.formatInput}>- <span>{input}:</span>- <InputNumber value={2} onChange={this.handleChange.bind(this)} />- </div>- )- <ul>- {data.map((item, index) => (- <li onClick={() => this.handleClick(item.value, index)}>- <span>{item.label}</span>- <span>{item.suffix}</span>- </li>- ))}- </ul>- </div>- );- }-}diff --git a/packages/sheets-plugin-numfmt/src/views/ui/FormatItem.module.less b/packages/sheets-plugin-numfmt/src/views/ui/FormatItem.module.lessdeleted file mode 100644index f4c46eb6c6..0000000000--- a/packages/sheets-plugin-numfmt/src/views/ui/FormatItem.module.less+++ /dev/null@@ -1,36 +0,0 @@-.format-item {- position: relative;-- display: flex;- align-items: center;- justify-content: space-between;-- padding: 0 14px 0 25px;-- .format-item-selected {- position: absolute;- top: 50%;- left: 5px;- transform: translateY(-50%) scale(1.5);-- display: flex;- align-items: center;- }-- .format-item-content {- display: block;- }-- .format-item-suffix {- margin-left: 10px;-- span[role='img'] {- font-size: 24px;- }- }-}--.format-disabled-item {- pointer-events: none;- color: var(--gray-15);-}diff --git a/packages/sheets-plugin-numfmt/src/views/ui/FormatItem.tsx b/packages/sheets-plugin-numfmt/src/views/ui/FormatItem.tsxdeleted file mode 100644index 5d5a400ae6..0000000000--- a/packages/sheets-plugin-numfmt/src/views/ui/FormatItem.tsx+++ /dev/null@@ -1,30 +0,0 @@-// import { joinClassNames } from '@univerjs/base-ui';-import { LocaleService } from '@univerjs/core';-import { useDependency } from '@wendellhu/redi/react-bindings';-import React from 'react';--export interface BaseFormatItemProps {- selected?: boolean;- labelText?: string;- suffix?: string;- border?: boolean;- disabled?: boolean;- value?: string;-}--/**- * FormatItem- */-export function FormatItem(props: BaseFormatItemProps): JSX.Element {- const { selected, labelText, suffix, disabled, value } = props;- const localeService = useDependency(LocaleService);-- return (- // <div className={joinClassNames(styles.formatItem, disabled ? styles.selectDisabledItem : '')}>- // {selected && <span className={styles.formatItemSelected}>{/* <Icon.CorrectIcon /> */}</span>}- // <span className={styles.formatItemContent}>{localeService.t(labelText as string) || labelText}</span>- // {suffix && <span className={styles.formatItemSuffix}>{localeService.t(suffix as string) || suffix}</span>}- // </div>- <></>- );-}diff --git a/packages/sheets-plugin-numfmt/src/views/ui/NumfmtModal.tsx b/packages/sheets-plugin-numfmt/src/views/ui/NumfmtModal.tsxdeleted file mode 100644index eef89689ec..0000000000--- a/packages/sheets-plugin-numfmt/src/views/ui/NumfmtModal.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { BaseComponentProps, ComponentManager } from '@univerjs/base-ui';-import React, { Component } from 'react';--import { ModalDataProps } from '../../controllers/numfmt-modal-controller';--interface IProps extends BaseComponentProps {}--interface IState {- modalData: ModalDataProps[];-}--export class NumfmtModal extends Component<IProps, IState> {- // static override contextType = AppContext;-- constructor(props: IProps) {- super(props);- this.initialize(props);- }-- initialize(props: IProps): void {- this.state = {- modalData: [],- };- }-- override componentDidMount(): void {}-- setModal(modalData: ModalDataProps[]): void {- const componentManager: ComponentManager = (this.context as any).injector.get(ComponentManager);- modalData.forEach((item): void => {- const Label = componentManager.get(item.children.name) as JSX.ElementType;- if (Label) {- const props = item.children.props ?? {};- item.modal = <Label {...props} />;- }- });- this.setState({ modalData });- }-- /**- * Render the component's HTML- *- * @returns {void}- */- override render() {- // const Modal = this._render.renderFunction('Modal');- // const { modalData } = this.state;- // // Set Provider for entire Container- // return (- // <>- // {modalData.map((item) => {- // if (!item.show) return;- // return (- // <Modal title={item.title} visible={item.show} group={item.group} onCancel={item.onCancel}>- // {item.modal}- // </Modal>- // );- // })}- // </>- // );- return <></>;- }-}diff --git a/packages/sheets-plugin-numfmt/src/views/ui/index.module.less b/packages/sheets-plugin-numfmt/src/views/ui/index.module.lessdeleted file mode 100644index 5e0cef2e37..0000000000--- a/packages/sheets-plugin-numfmt/src/views/ui/index.module.less+++ /dev/null@@ -1,70 +0,0 @@-.format-content {- .format-input {- display: flex;-- input {- width: 80px;- height: 24px;- margin-left: 5px;- padding: 0 5px;- }- }-- ul {- overflow-y: auto;-- height: 240px;- padding: 0;-- list-style: none;-- border: 1px solid var(--gray-5);-- li {- display: flex;- justify-content: space-between;-- height: 30px;- padding: 0 20px;-- line-height: 30px;-- border-bottom: 1px solid #dfdfdf;- }-- .format-selected {- color: #fff;- background: var(--primary-color);- }- }-}--.custom-format {- .drop-content {- width: 60px;-- >div {- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }- }-- .select-item-content {- margin-right: 15px;- }-- .custom-format-more {- .select-item-suffix {- span[role='img'] {- font-size: 16px;- }- }-- ul {- .select-item {- padding: 0 14px;- }- }- }-}\ No newline at end of filediff --git a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.tsindex 726aeecdda..8ab6c0de53 100644--- a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts+++ b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts@@ -10,10 +10,12 @@ import {DOCS_NORMAL_EDITOR_UNIT_ID_KEY,ICommandInfo,ICommandService,+ INTERCEPTOR_POINT,IUniverInstanceService,LifecycleStages,makeCellToSelection,OnLifecycle,+ SheetInterceptorService,} from '@univerjs/core';import { Inject } from '@wendellhu/redi';@@ -33,7 +35,8 @@ export class EditorBridgeController extends Disposable {@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,- @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService+ @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService) {super();@@ -111,11 +114,25 @@ export class EditorBridgeController extends Disposable {endX = skeleton.convertTransformToOffsetX(endX, scaleX, scrollXY);endY = skeleton.convertTransformToOffsetY(endY, scaleY, scrollXY);+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();+ const worksheet = workbook.getActiveSheet();+ const location = {+ workbook,+ worksheet,+ workbookId: workbook.getUnitId(),+ worksheetId: worksheet.getSheetId(),+ row: startRow,+ col: startColumn,+ };+ const cell = this._sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.BEFORE_CELL_EDIT)(+ worksheet.getCell(startRow, startColumn),+ location+ );- let documentLayoutObject = skeleton.getCellDocumentModelWithFormula(startRow, startColumn);+ let documentLayoutObject = cell && skeleton.getCellDocumentModelWithFormula(cell);- if (documentLayoutObject == null || documentLayoutObject.documentModel == null) {- documentLayoutObject = skeleton.getBlankCellDocumentModel(startRow, startColumn);+ if (!documentLayoutObject || documentLayoutObject.documentModel == null) {+ documentLayoutObject = skeleton.getBlankCellDocumentModel(cell);}documentLayoutObject.documentModel?.setZoomRatio(Math.max(scaleX, scaleY));diff --git a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.tsindex cbd64451ce..fdd6d868ee 100644--- a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts+++ b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts@@ -15,6 +15,7 @@ import {ICommandInfo,ICommandService,IContextService,+ INTERCEPTOR_POINT,isFormulaString,IUndoRedoService,IUniverInstanceService,@@ -22,6 +23,7 @@ import {Nullable,Observer,OnLifecycle,+ SheetInterceptorService,Tools,} from '@univerjs/core';import { Inject } from '@wendellhu/redi';@@ -61,7 +63,8 @@ export class EndEditController extends Disposable {@IContextService private readonly _contextService: IContextService,@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,- @IUndoRedoService private _undoRedoService: IUndoRedoService+ @IUndoRedoService private _undoRedoService: IUndoRedoService,+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService) {super();@@ -172,6 +175,18 @@ export class EndEditController extends Disposable {cellData.p = null;}+ const context = {+ worksheetId: sheetId,+ workbookId: unitId,+ workbook: workbook!,+ worksheet,+ row,+ col: column,+ };+ const cell = this._sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.AFTER_CELL_EDIT)(+ cellData,+ context+ );this._commandService.executeCommand(SetRangeValuesCommand.id, {worksheetId: sheetId,workbookId: unitId,@@ -181,7 +196,7 @@ export class EndEditController extends Disposable {endRow: row,endColumn: column,},- value: cellData,+ value: cell,});});}diff --git a/packages/ui-plugin-sheets/src/views/count-bar/zoom-slider.tsx b/packages/ui-plugin-sheets/src/views/count-bar/zoom-slider.tsxindex 29f95de707..776c12ee36 100644--- a/packages/ui-plugin-sheets/src/views/count-bar/zoom-slider.tsx+++ b/packages/ui-plugin-sheets/src/views/count-bar/zoom-slider.tsx@@ -28,7 +28,7 @@ export function ZoomSlider() {function getCurrentZoom() {const currentZoom =- univerInstanceService.getCurrentUniverSheetInstance()?.getActiveSheet().getZoomRatio() * 100 ?? 100;+ univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getZoomRatio() * 100 || 100;return Math.round(currentZoom);}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex db6772e740..f12c62102b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -406,6 +406,9 @@ importers:'@univerjs/core':specifier: workspace:*version: link:../core+ numfmt:+ specifier: ^2.5.2+ version: 2.5.2devDependencies:'@vitest/coverage-istanbul':specifier: ^0.34.6@@ -1036,12 +1039,21 @@ importers:'@univerjs/design':specifier: workspace:*version: link:../design+ '@univerjs/icons':+ specifier: ^0.1.12+ version: 0.1.12([email protected])([email protected])'@univerjs/ui-plugin-sheets':specifier: workspace:*version: link:../ui-plugin-sheets'@wendellhu/redi':specifier: ^0.12.11version: 0.12.11+ react:+ specifier: ^18.2.0+ version: 18.2.0+ rxjs:+ specifier: ^7.8.1+ version: 7.8.1devDependencies:'@types/react':specifier: ^18.2.38@@ -1055,9 +1067,6 @@ importers:less:specifier: ^4.2.0version: 4.2.0- react:- specifier: ^18.2.0- version: 18.2.0ts-node:specifier: ^10.9.1@@ -10587,6 +10596,10 @@ packages:resolution: {integrity: sha512-qaKRmtYPZ5qdw4jWJD6bxEf1FJEqllJrwxCLIm0sQU/A7v2/czigzOb+C2uSiFsa9lBUzeH7M1oK+Q+OLxL3kA==}dev: false+ resolution: {integrity: sha512-VXrB2bpU9Xa0oCHq8IsqE2CcUx5OLupLC3oryFT4DB9e/xe+OnUzBndhXfNHUzxFE4DYI3Sx4OtzS1Sdaf7tEw==}+ dev: false+resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}engines: {node: '>=0.10.0'}