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
fix(sheets-numfmt): localize date format presets (#7819)
wpxp123456dc9339800713
diff --git a/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts b/packages/sheets-numfmt-ui/src/menu/mobile-menu.tsindex 50af24323e..b5a77bfa74 100644--- a/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts+++ b/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts@@ -40,7 +40,6 @@ import {import {AddDecimalCommand,CURRENCYFORMAT,- DATEFMTLISG,getCurrencySymbolByLocale,NUMBERFORMAT,SetCurrencyCommand,@@ -113,7 +112,6 @@ export function createMobileNumberFormatMenuConfig(currencySymbol: string): IMobdetailOptions,customPatterns: [...new Set([...CURRENCYFORMAT.map((item) => item.suffix(currencySymbol)),- ...DATEFMTLISG.map((item) => item.suffix),...NUMBERFORMAT.map((item) => item.suffix),])],};diff --git a/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx b/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsxindex f1cc0b9c12..55477887f3 100644--- a/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx+++ b/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx@@ -21,8 +21,8 @@ import type { IBusinessComponentProps } from './components/interface';import { LocaleService } from '@univerjs/core';import { Button, clsx, scrollbarClassName, Select } from '@univerjs/design';import { getCurrencyType } from '@univerjs/sheets-numfmt';-import { useDependency } from '@univerjs/ui';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useDependency, useObservable } from '@univerjs/ui';+import { useCallback, useEffect, useRef, useState } from 'react';import { UserHabitCurrencyContext } from '../controllers/user-habit.controller';import { AccountingPanel, isAccountingPanel } from './components/Accounting';import { CurrencyPanel, isCurrencyPanel } from './components/Currency';@@ -38,55 +38,50 @@ export interface ISheetNumfmtPanelProps {onChange: (config: { type: 'change' | 'cancel' | 'confirm'; value: string }) => void;}+const TYPE_OPTIONS: Array<{ label: LocaleKey; component: ComponentType<IBusinessComponentProps> }> = [+ { label: 'sheets-numfmt-ui.general', component: GeneralPanel },+ { label: 'sheets-numfmt-ui.accounting', component: AccountingPanel },+ { label: 'sheets-numfmt-ui.currency', component: CurrencyPanel },+ { label: 'sheets-numfmt-ui.date', component: DatePanel },+ { label: 'sheets-numfmt-ui.thousandthPercentile', component: ThousandthPercentilePanel },+ { label: 'sheets-numfmt-ui.customFormat', component: CustomFormat },+];+export function SheetNumfmtPanel(props: ISheetNumfmtPanelProps) {+ const { onChange } = props;const { defaultValue, defaultPattern, row, col } = props.value;const localeService = useDependency(LocaleService);+ useObservable(localeService.currentLocale$, localeService.getCurrentLocale());const currentPatternRef = useRef<() => string | null>(() => '');const nextTick = useNextTick();- const typeOptions = useMemo(- () => {- const typeOptions: Array<{ label: LocaleKey; component: ComponentType<IBusinessComponentProps> }> = [- { label: 'sheets-numfmt-ui.general', component: GeneralPanel },- { label: 'sheets-numfmt-ui.accounting', component: AccountingPanel },- { label: 'sheets-numfmt-ui.currency', component: CurrencyPanel },- { label: 'sheets-numfmt-ui.date', component: DatePanel },- { label: 'sheets-numfmt-ui.thousandthPercentile', component: ThousandthPercentilePanel },- { label: 'sheets-numfmt-ui.customFormat', component: CustomFormat },- ];-- return typeOptions.map((item) => ({ ...item, label: localeService.t<LocaleKey>(item.label) }));- },- [localeService]- );+ const findDefaultType = useCallback(() => {+ const list = [isGeneralPanel, isAccountingPanel, isCurrencyPanel, isDatePanel, isThousandthPercentilePanel];+ return (+ list.reduce((pre, curFn, index) => pre || (curFn(defaultPattern) ? TYPE_OPTIONS[index].label : ''), '') ||+ TYPE_OPTIONS[0].label+ );+ }, [defaultPattern]);const [type, setType] = useState(findDefaultType);const [key, setKey] = useState(() => `${row}_${col}_${defaultPattern}`);const { mark, userHabitCurrency } = useCurrencyOptions(() => setKey(`${row}_${col}_${defaultPattern}_userCurrency`));- const BusinessComponent = typeOptions.find((item) => item.label === type)?.component;+ const BusinessComponent = TYPE_OPTIONS.find((item) => item.label === type)?.component;- function findDefaultType() {- const list = [isGeneralPanel, isAccountingPanel, isCurrencyPanel, isDatePanel, isThousandthPercentilePanel];- return (- list.reduce((pre, curFn, index) => pre || (curFn(defaultPattern) ? typeOptions[index].label : ''), '') ||- typeOptions[0].label- );- }-- const selectOptions: ISelectProps['options'] = typeOptions.map((option) => ({- label: option.label,+ const selectOptions: ISelectProps['options'] = TYPE_OPTIONS.map((option) => ({+ label: localeService.t<LocaleKey>(option.label),value: option.label,}));const handleSelect: ISelectProps['onChange'] = (value) => {setType(value);// after the BusinessComponent render.- nextTick(() => props.onChange({ type: 'change', value: currentPatternRef.current() || '' }));+ nextTick(() => onChange({ type: 'change', value: currentPatternRef.current() || '' }));};const handleChange = useCallback((v: string) => {- props.onChange({ type: 'change', value: v });- }, []);+ onChange({ type: 'change', value: v });+ }, [onChange]);const handleActionChange = useCallback((action: () => string | null) => {currentPatternRef.current = action;@@ -98,11 +93,11 @@ export function SheetNumfmtPanel(props: ISheetNumfmtPanelProps) {if (currency) {mark(currency);}- props.onChange({ type: 'confirm', value: pattern });+ onChange({ type: 'confirm', value: pattern });};const handleCancel = () => {- props.onChange({ type: 'cancel', value: '' });+ onChange({ type: 'cancel', value: '' });};const subProps: IBusinessComponentProps = {@@ -115,7 +110,7 @@ export function SheetNumfmtPanel(props: ISheetNumfmtPanelProps) {useEffect(() => {setType(findDefaultType());setKey(`${row}_${col}_${defaultPattern}`);- }, [row, col, defaultPattern]);+ }, [row, col, defaultPattern, findDefaultType]);return (<divdiff --git a/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtPanel.spec.tsx b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtPanel.spec.tsxnew file mode 100644index 0000000000..08e7f10c28--- /dev/null+++ b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtPanel.spec.tsx@@ -0,0 +1,91 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Root } from 'react-dom/client';+import { ILocalStorageService, Injector, LocaleService, LocaleType } from '@univerjs/core';+import { ConfigProvider } from '@univerjs/design';+import designEnUS from '@univerjs/design/locale/en-US';+import { DesktopLocalStorageService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { UserHabitController } from '../../controllers/user-habit.controller';+import enUS from '../../locale/en-US';+import zhCN from '../../locale/zh-CN';+import { SheetNumfmtPanel } from '../SheetNumfmtPanel';++const roots: Root[] = [];+const containers: HTMLElement[] = [];+const injectors: Injector[] = [];++afterEach(async () => {+ roots.splice(0).forEach((root) => act(() => root.unmount()));+ containers.splice(0).forEach((container) => container.remove());+ for (const injector of injectors.splice(0)) {+ await injector.get(ILocalStorageService).clear();+ injector.dispose();+ }+});++describe('SheetNumfmtPanel', () => {+ it('keeps the active category and selected date format when its labels are translated', async () => {+ const injector = new Injector([+ [LocaleService],+ [ILocalStorageService, { useClass: DesktopLocalStorageService }],+ [UserHabitController],+ ]);+ injectors.push(injector);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS, [LocaleType.ZH_CN]: zhCN });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');+ const container = document.createElement('div');+ document.body.appendChild(container);+ containers.push(container);+ const root = createRoot(container);+ roots.push(root);+ const onChange = vi.fn();++ await act(async () => root.render(+ <ConfigProvider locale={designEnUS.design} mountContainer={document.body}>+ <RediContext.Provider value={{ injector }}>+ <SheetNumfmtPanel+ value={{ defaultValue: 0.5625, defaultPattern: 'h:mm', row: 0, col: 0 }}+ onChange={onChange}+ />+ </RediContext.Provider>+ </ConfigProvider>+ ));++ const option = Array.from(container.querySelectorAll('li a')).find((element) =>+ element.textContent?.trim() === '1:30 PM');+ expect(option).toBeDefined();+ act(() => option!.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ const selectedPattern = onChange.mock.lastCall![0].value;++ act(() => localeService.setLocale(LocaleType.ZH_CN));++ expect(container.querySelector('[data-u-comp="select"]')?.textContent)+ .toContain(localeService.t('sheets-numfmt-ui.date'));+ expect(container.textContent).toContain('1930年08月05日');+ expect(onChange).toHaveBeenCalledTimes(1);+ const confirm = Array.from(container.querySelectorAll('button')).find((button) =>+ button.textContent === localeService.t('sheets-numfmt-ui.confirm'));+ expect(confirm).toBeDefined();+ act(() => confirm!.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ expect(onChange).toHaveBeenLastCalledWith({ type: 'confirm', value: selectedPattern });+ });+});diff --git a/packages/sheets-numfmt-ui/src/views/components/CustomFormat.tsx b/packages/sheets-numfmt-ui/src/views/components/CustomFormat.tsxindex 3344138db2..74e3d47daf 100644--- a/packages/sheets-numfmt-ui/src/views/components/CustomFormat.tsx+++ b/packages/sheets-numfmt-ui/src/views/components/CustomFormat.tsx@@ -19,8 +19,8 @@ import type { IBusinessComponentProps } from './interface';import { ILocalStorageService, LocaleService } from '@univerjs/core';import { borderClassName, clsx, Input } from '@univerjs/design';import { CheckMarkIcon } from '@univerjs/icons';-import { CURRENCYFORMAT, DATEFMTLISG, NUMBERFORMAT } from '@univerjs/sheets-numfmt';-import { useDependency } from '@univerjs/ui';+import { CURRENCYFORMAT, getDateFormatOptions, NUMBERFORMAT } from '@univerjs/sheets-numfmt';+import { useDependency, useObservable } from '@univerjs/ui';import { useEffect, useLayoutEffect, useState } from 'react';import { UserHabitController } from '../../controllers/user-habit.controller';@@ -32,6 +32,7 @@ export function CustomFormat(props: IBusinessComponentProps) {const userHabitController = useDependency(UserHabitController);const localStorageService = useDependency(ILocalStorageService);const localeService = useDependency(LocaleService);+ const locale = useObservable(localeService.currentLocale$, localeService.getCurrentLocale());const [pattern, setPattern] = useState(defaultPattern);useLayoutEffect(() => {@@ -39,8 +40,8 @@ export function CustomFormat(props: IBusinessComponentProps) {userHabitController.markHabit(key, pattern);localStorageService.getItem<string[]>(historyPatternKey).then((list = []) => {const _list = [...new Set([pattern, ...(list || [])])].splice(0, 10).filter((e) => !!e);- localStorageService.setItem(historyPatternKey, _list);- });+ return localStorageService.setItem(historyPatternKey, _list);+ }).catch(console.error);return pattern;});}, [localStorageService, onActionChange, pattern, userHabitController]);@@ -49,10 +50,10 @@ export function CustomFormat(props: IBusinessComponentProps) {useEffect(() => {let cancelled = false;- void localStorageService.getItem<string[]>(historyPatternKey).then((historyList) => {+ localStorageService.getItem<string[]>(historyPatternKey).then((historyList) => {const list = [...CURRENCYFORMAT.map((item) => item.suffix('$')),- ...DATEFMTLISG.map((item) => item.suffix),+ ...getDateFormatOptions(locale).map((item) => item.value),...NUMBERFORMAT.map((item) => item.suffix),...(historyList ?? []),];@@ -61,12 +62,12 @@ export function CustomFormat(props: IBusinessComponentProps) {if (!cancelled) {setOptions([...new Set(list)]);}- });+ }).catch(console.error);return () => {cancelled = true;};- }, [localStorageService, userHabitController]);+ }, [locale, localStorageService, userHabitController]);const handleClick = (p: string) => {setPattern(p);diff --git a/packages/sheets-numfmt-ui/src/views/components/Date.tsx b/packages/sheets-numfmt-ui/src/views/components/Date.tsxindex 3c1e9e7ae2..3b9cc73515 100644--- a/packages/sheets-numfmt-ui/src/views/components/Date.tsx+++ b/packages/sheets-numfmt-ui/src/views/components/Date.tsx@@ -19,40 +19,27 @@ import type { IBusinessComponentProps } from './interface';import { LocaleService, numfmt } from '@univerjs/core';import { SelectList } from '@univerjs/design';import { getDateFormatOptions } from '@univerjs/sheets-numfmt';-import { useDependency } from '@univerjs/ui';+import { useDependency, useObservable } from '@univerjs/ui';import { useLayoutEffect, useMemo, useState } from 'react';export const isDatePanel = (pattern: string) => {const info = numfmt.getFormatInfo(pattern);- return (- getDateFormatOptions()- .map((item) => item.value)- .includes(pattern) || ['date', 'datetime', 'time'].includes(info.type)- );+ return ['date', 'datetime', 'time'].includes(info.type);};export function DatePanel(props: IBusinessComponentProps) {const { onActionChange, onChange, defaultPattern } = props;-- const options = useMemo(getDateFormatOptions, []);const localeService = useDependency(LocaleService);-- const [suffix, setSuffix] = useState(() => {- if (defaultPattern) {- const item = options.find((item) => item.value === defaultPattern);- if (item) {- return item.value;- }- }- return options[0].value;- });+ const locale = useObservable(localeService.currentLocale$, localeService.getCurrentLocale());+ const [suffix, setSuffix] = useState(() => defaultPattern || getDateFormatOptions(locale)[0].value);+ const options = useMemo(() => getDateFormatOptions(locale, suffix), [locale, suffix]);useLayoutEffect(() => {onActionChange(() => suffix);}, [onActionChange, suffix]);- const handleChange = (v: any) => {- if (v === undefined) {+ const handleChange = (v: string | string[] | undefined) => {+ if (typeof v !== 'string') {return;}setSuffix(v);diff --git a/packages/sheets-numfmt-ui/src/views/components/__tests__/CustomFormat.spec.tsx b/packages/sheets-numfmt-ui/src/views/components/__tests__/CustomFormat.spec.tsxnew file mode 100644index 0000000000..fef0958605--- /dev/null+++ b/packages/sheets-numfmt-ui/src/views/components/__tests__/CustomFormat.spec.tsx@@ -0,0 +1,88 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Root } from 'react-dom/client';+import { ILocalStorageService, Injector, LocaleService, LocaleType } from '@univerjs/core';+import { DesktopLocalStorageService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { UserHabitController } from '../../../controllers/user-habit.controller';+import enUS from '../../../locale/en-US';+import zhCN from '../../../locale/zh-CN';+import { CustomFormat } from '../CustomFormat';++const roots: Root[] = [];+const containers: HTMLElement[] = [];+const injectors: Injector[] = [];++afterEach(async () => {+ roots.splice(0).forEach((root) => act(() => root.unmount()));+ containers.splice(0).forEach((container) => container.remove());+ for (const injector of injectors.splice(0)) {+ await injector.get(ILocalStorageService).clear();+ injector.dispose();+ }+});++describe('CustomFormat', () => {+ it('refreshes date presets without dropping user history or editing the active pattern', async () => {+ const injector = new Injector([+ [LocaleService],+ [ILocalStorageService, { useClass: DesktopLocalStorageService }],+ [UserHabitController],+ ]);+ injectors.push(injector);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS, [LocaleType.ZH_CN]: zhCN });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');+ const storage = injector.get(ILocalStorageService);+ const historicPattern = 'yyyy"年"m"月"d"日"';+ await storage.setItem('numfmt_custom_pattern', [historicPattern]);+ const container = document.createElement('div');+ document.body.appendChild(container);+ containers.push(container);+ const root = createRoot(container);+ roots.push(root);+ const onActionChange = vi.fn();+ const onChange = vi.fn();++ await act(async () => root.render(+ <RediContext.Provider value={{ injector }}>+ <CustomFormat+ defaultPattern={historicPattern}+ defaultValue={0}+ onActionChange={onActionChange}+ onChange={onChange}+ />+ </RediContext.Provider>+ ));++ expect(container.textContent).toContain('m/d/yyyy');+ expect(container.textContent).toContain(historicPattern);+ expect(container.textContent).not.toContain('yyyy"年"MM"月"dd"日"');++ await act(async () => localeService.setLocale(LocaleType.ZH_CN));++ expect(container.textContent).toContain('yyyy"年"MM"月"dd"日"');+ expect(container.textContent).toContain(historicPattern);+ expect(container.textContent).not.toContain('m/d/yyyy');+ expect((container.querySelector('input') as HTMLInputElement).value).toBe(historicPattern);+ expect(onChange).not.toHaveBeenCalled();+ expect(await storage.getItem('numfmt_custom_pattern')).toEqual([historicPattern]);+ });+});diff --git a/packages/sheets-numfmt-ui/src/views/components/__tests__/Date.spec.tsx b/packages/sheets-numfmt-ui/src/views/components/__tests__/Date.spec.tsxnew file mode 100644index 0000000000..6ab2056b67--- /dev/null+++ b/packages/sheets-numfmt-ui/src/views/components/__tests__/Date.spec.tsx@@ -0,0 +1,112 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Root } from 'react-dom/client';+import { excelDateTimeSerial, Injector, LocaleService, LocaleType } from '@univerjs/core';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import enUS from '../../../locale/en-US';+import zhCN from '../../../locale/zh-CN';+import { DatePanel, isDatePanel } from '../Date';++const roots: Root[] = [];+const containers: HTMLElement[] = [];+const injectors: Injector[] = [];++afterEach(() => {+ roots.splice(0).forEach((root) => act(() => root.unmount()));+ containers.splice(0).forEach((container) => container.remove());+ injectors.splice(0).forEach((injector) => injector.dispose());+});++describe('DatePanel', () => {+ it('preserves an existing non-preset date pattern when opened in English', () => {+ const injector = new Injector([[LocaleService]]);+ injectors.push(injector);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');+ const container = document.createElement('div');+ containers.push(container);+ document.body.appendChild(container);+ const root = createRoot(container);+ roots.push(root);+ const pattern = 'yyyy"年"m"月"d"日"';+ const onActionChange = vi.fn();+ const onChange = vi.fn();++ act(() => root.render(+ <RediContext.Provider value={{ injector }}>+ <DatePanel+ defaultPattern={pattern}+ defaultValue={excelDateTimeSerial(new Date(Date.UTC(2024, 0, 2)))}+ onActionChange={onActionChange}+ onChange={onChange}+ />+ </RediContext.Provider>+ ));++ expect(container.textContent).toContain('1930年8月5日');+ expect(onActionChange.mock.lastCall![0]()).toBe(pattern);+ expect(onChange).not.toHaveBeenCalled();+ expect(isDatePanel(pattern)).toBe(true);+ });++ it('updates presets on locale changes without replacing a user-selected format', () => {+ const injector = new Injector([[LocaleService]]);+ injectors.push(injector);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS, [LocaleType.ZH_CN]: zhCN });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');+ const container = document.createElement('div');+ containers.push(container);+ document.body.appendChild(container);+ const root = createRoot(container);+ roots.push(root);+ const onActionChange = vi.fn();+ const onChange = vi.fn();++ act(() => root.render(+ <RediContext.Provider value={{ injector }}>+ <DatePanel+ defaultPattern=""+ defaultValue={0.5625}+ onActionChange={onActionChange}+ onChange={onChange}+ />+ </RediContext.Provider>+ ));++ expect(container.textContent).not.toContain('下午');+ const option = Array.from(container.querySelectorAll('li a')).find((element) =>+ element.textContent?.trim() === '1:30 PM');+ expect(option).toBeDefined();+ act(() => option!.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ const selectedPattern = onChange.mock.lastCall![0];++ act(() => localeService.setLocale(LocaleType.ZH_CN));++ expect(container.textContent).toContain('1930年08月05日');+ expect(container.textContent).toContain('下午 1:30');+ expect(onActionChange.mock.lastCall![0]()).toBe(selectedPattern);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(container.querySelector('li a.univer-bg-gray-200')?.textContent).toContain('1:30 下午');+ });+});diff --git a/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx b/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsxindex e45c9228ac..1d1a7395ee 100644--- a/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx+++ b/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx@@ -17,8 +17,9 @@import type { LocaleKey } from '../../locale/types';import { LocaleService } from '@univerjs/core';import { Button, Input, MobileActionRowGroup, MobileSelect } from '@univerjs/design';-import { useDependency } from '@univerjs/ui';-import { useState } from 'react';+import { getDateFormatOptions } from '@univerjs/sheets-numfmt';+import { useDependency, useObservable } from '@univerjs/ui';+import { useMemo, useState } from 'react';export interface IMobileCustomFormatProps {patterns: string[];@@ -28,8 +29,15 @@ export interface IMobileCustomFormatProps {export function MobileCustomFormat(props: IMobileCustomFormatProps) {const { patterns, onConfirm } = props;const localeService = useDependency(LocaleService);+ const locale = useObservable(localeService.currentLocale$, localeService.getCurrentLocale());const [pattern, setPattern] = useState('');const title = localeService.t<LocaleKey>('sheets-numfmt-ui.customFormat');+ // Menu configuration outlives locale changes; resolve date presets when the editor renders.+ const options = useMemo(() => [...new Set([+ ...patterns,+ ...getDateFormatOptions(locale).map((item) => item.value),+ ...(pattern ? [pattern] : []),+ ])].map((value) => ({ label: value, value })), [locale, pattern, patterns]);return (<div@@ -50,7 +58,7 @@ export function MobileCustomFormat(props: IMobileCustomFormatProps) {[&>div]:univer-font-mono"value={pattern || title}- options={patterns.map((item) => ({ label: item, value: item }))}+ options={options}onChange={setPattern}/><divdiff --git a/packages/sheets-numfmt-ui/src/views/mobile/__tests__/MobileCustomFormat.spec.tsx b/packages/sheets-numfmt-ui/src/views/mobile/__tests__/MobileCustomFormat.spec.tsxindex d636baf2f8..e3adc2b0f9 100644--- a/packages/sheets-numfmt-ui/src/views/mobile/__tests__/MobileCustomFormat.spec.tsx+++ b/packages/sheets-numfmt-ui/src/views/mobile/__tests__/MobileCustomFormat.spec.tsx@@ -23,22 +23,27 @@ import { act } from 'react';import { createRoot } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';import enUS from '../../../locale/en-US';+import zhCN from '../../../locale/zh-CN';import { MobileCustomFormat } from '../MobileCustomFormat';const roots: Root[] = [];const containers: HTMLElement[] = [];+const injectors: Injector[] = [];afterEach(() => {roots.splice(0).forEach((root) => act(() => root.unmount()));containers.splice(0).forEach((container) => container.remove());+ injectors.splice(0).forEach((injector) => injector.dispose());});describe('MobileCustomFormat', () => {it('selects an existing pattern from a mobile dropdown and confirms it', () => {const injector = new Injector([[LocaleService]]);+ injectors.push(injector);const localeService = injector.get(LocaleService);localeService.load({ [LocaleType.EN_US]: enUS });localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');const onConfirm = vi.fn();const container = document.createElement('div');document.body.appendChild(container);@@ -72,6 +77,43 @@ describe('MobileCustomFormat', () => {act(() => confirm.dispatchEvent(new MouseEvent('click', { bubbles: true })));expect(onConfirm).toHaveBeenCalledExactlyOnceWith('#,##0');});++ it('resolves live date presets while preserving a selection across locale changes', () => {+ const injector = new Injector([[LocaleService]]);+ injectors.push(injector);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS, [LocaleType.ZH_CN]: zhCN });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');+ const onConfirm = vi.fn();+ const container = document.createElement('div');+ document.body.appendChild(container);+ containers.push(container);+ const root = createRoot(container);+ roots.push(root);++ act(() => root.render(+ <ConfigProvider locale={designEnUS.design} mountContainer={document.body}>+ <RediContext.Provider value={{ injector }}>+ <MobileCustomFormat patterns={['0.00']} onConfirm={onConfirm} />+ </RediContext.Provider>+ </ConfigProvider>+ ));++ const select = container.querySelector('[data-u-comp="mobile-select"]');+ act(() => select!.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ expect(document.body.querySelector('[role="dialog"]')?.textContent).not.toMatch(/[年月日]|上午|下午/);+ act(() => getButton('m/d/yyyy').dispatchEvent(new MouseEvent('click', { bubbles: true })));++ act(() => localeService.setLocale(LocaleType.ZH_CN));++ expect((container.querySelector('input') as HTMLInputElement).value).toBe('m/d/yyyy');+ act(() => select!.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ expect(document.body.querySelector('[role="dialog"]')?.textContent).toContain('yyyy"年"MM"月"dd"日"');+ act(() => getButton('m/d/yyyy').dispatchEvent(new MouseEvent('click', { bubbles: true })));+ act(() => getButton(localeService.t('sheets-numfmt-ui.confirm')).dispatchEvent(new MouseEvent('click', { bubbles: true })));+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith('m/d/yyyy');+ });});function getButton(name: string): HTMLButtonElement {diff --git a/packages/sheets-numfmt/src/base/const/date-format.ts b/packages/sheets-numfmt/src/base/const/date-format.tsnew file mode 100644index 0000000000..731bfd8322--- /dev/null+++ b/packages/sheets-numfmt/src/base/const/date-format.ts@@ -0,0 +1,98 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { LocaleType } from '@univerjs/core';++interface IDateFormatProfile {+ dates: readonly string[];+ shortDate: string;+ periodBeforeTime?: boolean;+}++const ISO_DATE_PROFILE: IDateFormatProfile = {+ dates: ['yyyy/MM/dd', 'MM-dd'],+ shortDate: 'MM-dd',+};+const MDY_DATE_PROFILE: IDateFormatProfile = {+ dates: ['m/d/yyyy', 'mm/dd/yyyy', 'mmm d, yyyy', 'm/d', 'mmmm d'],+ shortDate: 'm/d',+};+const DMY_DATE_PROFILE: IDateFormatProfile = {+ dates: ['dd/mm/yyyy', 'd/m/yyyy', 'd mmm yyyy', 'dd/mm', 'd mmmm'],+ shortDate: 'dd/mm',+};+const DMY_DOT_DATE_PROFILE: IDateFormatProfile = {+ dates: ['dd.mm.yyyy', 'd.m.yyyy', 'd mmm yyyy', 'dd.mm', 'd mmmm'],+ shortDate: 'dd.mm',+};+const CJK_DATE_PROFILE: IDateFormatProfile = {+ dates: ['yyyy/MM/dd', 'yyyy"年"MM"月"dd"日"', 'MM-dd', 'M"月"d"日"'],+ shortDate: 'MM-dd',+ periodBeforeTime: true,+};+const DATE_FORMAT_PROFILES: Record<LocaleType, IDateFormatProfile> = {+ [LocaleType.EN_US]: MDY_DATE_PROFILE,+ [LocaleType.FR_FR]: DMY_DATE_PROFILE,+ [LocaleType.ZH_CN]: CJK_DATE_PROFILE,+ [LocaleType.RU_RU]: DMY_DOT_DATE_PROFILE,+ [LocaleType.ZH_TW]: CJK_DATE_PROFILE,+ [LocaleType.ZH_HK]: {+ ...CJK_DATE_PROFILE,+ dates: ['dd/MM/yyyy', ...CJK_DATE_PROFILE.dates],+ shortDate: 'dd/MM',+ },+ [LocaleType.VI_VN]: DMY_DATE_PROFILE,+ // The formatter currently falls back to English for Persian and Spanish for Catalan.+ [LocaleType.FA_IR]: ISO_DATE_PROFILE,+ [LocaleType.CA_ES]: {+ dates: ['dd/mm/yyyy', 'd/m/yyyy', 'dd/mm'],+ shortDate: 'dd/mm',+ },+ [LocaleType.JA_JP]: CJK_DATE_PROFILE,+ [LocaleType.KO_KR]: {+ dates: ['yyyy. mm. dd.', 'yyyy"년" m"월" d"일"', 'mm-dd', 'm"월" d"일"'],+ shortDate: 'mm-dd',+ periodBeforeTime: true,+ },+ [LocaleType.ES_ES]: DMY_DATE_PROFILE,+ [LocaleType.SK_SK]: DMY_DOT_DATE_PROFILE,+ [LocaleType.PT_BR]: DMY_DATE_PROFILE,+ [LocaleType.DE_DE]: DMY_DOT_DATE_PROFILE,+ [LocaleType.IT_IT]: DMY_DATE_PROFILE,+ [LocaleType.ID_ID]: DMY_DATE_PROFILE,+ [LocaleType.PL_PL]: DMY_DOT_DATE_PROFILE,+ [LocaleType.AR_SA]: {+ dates: ['dd/mm/yyyy', 'd/m/yyyy', 'dd/mm'],+ shortDate: 'dd/mm',+ },+};++export function getDateFormatPatterns(locale: LocaleType): string[] {+ const profile = DATE_FORMAT_PROFILES[locale] ?? ISO_DATE_PROFILE;+ const clockPatterns = ['hh:mm', 'h:mm', 'h:mm:ss'];+ const timePatterns = clockPatterns.map((pattern) => profile.periodBeforeTime+ ? `AM/PM ${pattern}`+ : `${pattern} AM/PM`);++ return [...new Set([+ 'yyyy-MM-dd',+ ...profile.dates,+ 'h:mm:ss',+ 'h:mm',+ ...timePatterns,+ `${profile.shortDate} ${timePatterns[0]}`,+ ])];+}diff --git a/packages/sheets-numfmt/src/utils/__tests__/options.spec.ts b/packages/sheets-numfmt/src/utils/__tests__/options.spec.tsnew file mode 100644index 0000000000..5db7c02851--- /dev/null+++ b/packages/sheets-numfmt/src/utils/__tests__/options.spec.ts@@ -0,0 +1,68 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { LocaleType, numfmt } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DATEFMTLISG } from '../../base/const/formatdetail';+import { getDateFormatOptions } from '../options';++describe('getDateFormatOptions', () => {+ it('keeps the legacy public options when no locale is supplied', () => {+ expect(getDateFormatOptions()).toEqual(DATEFMTLISG.map(({ label, suffix }) => ({ label, value: suffix })));+ });++ it.each<[LocaleType, string, string]>([+ [LocaleType.EN_US, '08/05/1930', '1:30 PM'],+ [LocaleType.FR_FR, '05/08/1930', '1:30 PM'],+ [LocaleType.DE_DE, '05.08.1930', '1:30 PM'],+ [LocaleType.ZH_CN, '1930年08月05日', '下午 1:30'],+ [LocaleType.JA_JP, '1930年08月05日', '午後 1:30'],+ [LocaleType.KO_KR, '1930년 8월 5일', '오후 1:30'],+ ])('previews the date order and day period for %s', (locale, dateLabel, timeLabel) => {+ const labels = getDateFormatOptions(locale).map((option) => option.label);+ expect(labels).toContain(dateLabel);+ expect(labels).toContain(timeLabel);+ });++ it.each(Object.values(LocaleType))('provides valid, unique temporal patterns for %s', (locale) => {+ const options = getDateFormatOptions(locale);+ expect(options.length).toBeGreaterThan(0);+ expect(new Set(options.map((option) => option.value)).size).toBe(options.length);+ for (const option of options) {+ expect(['date', 'time', 'datetime']).toContain(numfmt.getFormatInfo(option.value).type);+ expect(option.label).not.toMatch(/#|NaN/);+ }+ });++ it('does not offer Chinese literals in English presets', () => {+ for (const option of getDateFormatOptions(LocaleType.EN_US)) {+ expect(option.label).not.toMatch(/[年月日]|上午|下午/);+ expect(option.value).not.toMatch(/[年月日]|上午|下午/);+ }+ });++ it('does not select the US date order for locales whose formatter falls back to English', () => {+ const persian = getDateFormatOptions(LocaleType.FA_IR);+ expect(persian.some((option) => option.label === '1930/08/05')).toBe(true);+ expect(persian.some((option) => option.label === '8/5/1930')).toBe(false);+ });++ it('falls back to language-neutral date patterns for an unsupported locale', () => {+ const options = getDateFormatOptions('unsupported' as LocaleType);+ expect(options.some((option) => option.label === '1930-08-05')).toBe(true);+ expect(options.some((option) => /[年月日]|上午|下午/.test(option.label))).toBe(false);+ });+});diff --git a/packages/sheets-numfmt/src/utils/options.ts b/packages/sheets-numfmt/src/utils/options.tsindex 5d5fe333da..bb83e5dfe3 100644--- a/packages/sheets-numfmt/src/utils/options.ts+++ b/packages/sheets-numfmt/src/utils/options.ts@@ -14,7 +14,9 @@* limitations under the License.*/-import { currencySymbols } from '@univerjs/core';+import type { LocaleType } from '@univerjs/core';+import { currencySymbols, excelDateTimeSerial, getNumfmtLocaleTag, numfmt } from '@univerjs/core';+import { getDateFormatPatterns } from '../base/const/date-format';import { CURRENCYFORMAT, DATEFMTLISG, NUMBERFORMAT } from '../base/const/formatdetail';export const getCurrencyOptions = () => currencySymbols.map((item) => ({ label: item, value: item }));@@ -26,7 +28,24 @@ export const getCurrencyFormatOptions = (suffix: string) =>color: item.color,}));-export const getDateFormatOptions = () => DATEFMTLISG.map((item) => ({ label: item.label, value: item.suffix }));+const DATE_FORMAT_PREVIEW_VALUE = excelDateTimeSerial(new Date(Date.UTC(1930, 7, 5, 13, 30, 30)));++export const getDateFormatOptions = (locale?: LocaleType, currentPattern?: string) => {+ if (locale === undefined) {+ return DATEFMTLISG.map((item) => ({ label: item.label, value: item.suffix }));+ }++ const numfmtLocale = getNumfmtLocaleTag(locale);+ const patterns = getDateFormatPatterns(locale);+ if (currentPattern && !patterns.includes(currentPattern)) {+ patterns.unshift(currentPattern);+ }++ return patterns.map((pattern) => ({+ label: numfmt.format(pattern, DATE_FORMAT_PREVIEW_VALUE, { locale: numfmtLocale }),+ value: pattern,+ }));+};export const getNumberFormatOptions = () =>NUMBERFORMAT.map((item) => ({ label: item.label, value: item.suffix, color: item.color }));