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-ui): reset panel state on selection change (#7823)
白熱99ebece5d204
diff --git a/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx b/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsxindex 55477887f3..883bd19214 100644--- a/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx+++ b/packages/sheets-numfmt-ui/src/views/SheetNumfmtPanel.tsx@@ -22,7 +22,7 @@ import { LocaleService } from '@univerjs/core';import { Button, clsx, scrollbarClassName, Select } from '@univerjs/design';import { getCurrencyType } from '@univerjs/sheets-numfmt';import { useDependency, useObservable } from '@univerjs/ui';-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useRef, useState } from 'react';import { UserHabitCurrencyContext } from '../controllers/user-habit.controller';import { AccountingPanel, isAccountingPanel } from './components/Accounting';import { CurrencyPanel, isCurrencyPanel } from './components/Currency';@@ -48,6 +48,11 @@ const TYPE_OPTIONS: Array<{ label: LocaleKey; component: ComponentType<IBusiness];export function SheetNumfmtPanel(props: ISheetNumfmtPanelProps) {+ const { row, col, defaultPattern } = props.value;+ return <SheetNumfmtPanelContent {...props} key={`${row}_${col}_${defaultPattern}`} />;+}++function SheetNumfmtPanelContent(props: ISheetNumfmtPanelProps) {const { onChange } = props;const { defaultValue, defaultPattern, row, col } = props.value;const localeService = useDependency(LocaleService);@@ -55,19 +60,20 @@ export function SheetNumfmtPanel(props: ISheetNumfmtPanelProps) {const currentPatternRef = useRef<() => string | null>(() => '');const nextTick = useNextTick();- 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 = 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) ? TYPE_OPTIONS[index].label : ''), '') ||+ 'sheets-numfmt-ui.customFormat'+ );+ }+const selectOptions: ISelectProps['options'] = TYPE_OPTIONS.map((option) => ({label: localeService.t<LocaleKey>(option.label),value: option.label,@@ -107,11 +113,6 @@ export function SheetNumfmtPanel(props: ISheetNumfmtPanelProps) {defaultPattern,};- useEffect(() => {- setType(findDefaultType());- setKey(`${row}_${col}_${defaultPattern}`);- }, [row, col, defaultPattern, findDefaultType]);-return (<divclassName={clsx(diff --git a/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtPanel.spec.tsx b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtPanel.spec.tsxindex 08e7f10c28..5ab60bdaf8 100644--- a/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtPanel.spec.tsx+++ b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtPanel.spec.tsx@@ -15,13 +15,14 @@*/import type { Root } from 'react-dom/client';+import type { ISheetNumfmtPanelProps } from '../SheetNumfmtPanel';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 { afterEach, beforeEach, 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';@@ -31,6 +32,10 @@ const roots: Root[] = [];const containers: HTMLElement[] = [];const injectors: Injector[] = [];+beforeEach(() => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);+});+afterEach(async () => {roots.splice(0).forEach((root) => act(() => root.unmount()));containers.splice(0).forEach((container) => container.remove());@@ -38,37 +43,58 @@ afterEach(async () => {await injector.get(ILocalStorageService).clear();injector.dispose();}+ vi.unstubAllGlobals();});-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();+async function renderPanel(value: ISheetNumfmtPanelProps['value']) {+ 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();+ const rerender = async (value: ISheetNumfmtPanelProps['value']) => {await act(async () => root.render(- <ConfigProvider locale={designEnUS.design} mountContainer={document.body}>+ <ConfigProvider locale={designEnUS.design} direction="ltr" mountContainer={document.body}><RediContext.Provider value={{ injector }}>- <SheetNumfmtPanel- value={{ defaultValue: 0.5625, defaultPattern: 'h:mm', row: 0, col: 0 }}- onChange={onChange}- />+ <SheetNumfmtPanel value={value} onChange={onChange} /></RediContext.Provider></ConfigProvider>));+ };+ await rerender(value);+ return { container, localeService, onChange, rerender };+}++async function confirmPanel(container: HTMLElement, label = 'Confirm') {+ const button = Array.from(container.querySelectorAll('button')).find((element) =>+ element.textContent?.trim() === label);+ if (!button) {+ throw new Error(`Button "${label}" was not rendered.`);+ }++ await act(async () => button.dispatchEvent(new MouseEvent('click', { bubbles: true })));+}++describe('SheetNumfmtPanel', () => {+ it('keeps the active category and selected date format when its labels are translated', async () => {+ const { container, localeService, onChange } = await renderPanel({+ defaultValue: 0.5625,+ defaultPattern: 'h:mm',+ row: 0,+ col: 0,+ });const option = Array.from(container.querySelectorAll('li a')).find((element) =>element.textContent?.trim() === '1:30 PM');@@ -82,10 +108,56 @@ describe('SheetNumfmtPanel', () => {.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 })));+ await confirmPanel(container, localeService.t('sheets-numfmt-ui.confirm'));expect(onChange).toHaveBeenLastCalledWith({ type: 'confirm', value: selectedPattern });});++ it('preserves a custom format when reopening and confirming without edits', async () => {+ const pattern = '#,##0 "km/h"';+ const { container, onChange } = await renderPanel({+ defaultValue: 5800,+ defaultPattern: pattern,+ row: 3,+ col: 3,+ });++ await confirmPanel(container);++ expect(onChange).toHaveBeenCalledExactlyOnceWith({ type: 'confirm', value: pattern });+ expect(container.querySelector('[data-u-comp="select"]')?.textContent).toBe('Custom Format');+ expect(container.querySelector<HTMLInputElement>('input[placeholder="Custom Format"]')?.value).toBe(pattern);+ });++ it.each(['', '0.00 "kg"'])('follows a new custom-formatted selection after opening with %j', async (initialPattern) => {+ const { container, onChange, rerender } = await renderPanel({+ defaultValue: 12,+ defaultPattern: initialPattern,+ row: 0,+ col: 0,+ });+ const pattern = '#,##0 "km/h"';++ await rerender({ defaultValue: 5800, defaultPattern: pattern, row: 3, col: 3 });+ await confirmPanel(container);++ expect(onChange).toHaveBeenCalledExactlyOnceWith({ type: 'confirm', value: pattern });+ expect(container.querySelector<HTMLInputElement>('input[placeholder="Custom Format"]')?.value).toBe(pattern);+ });++ it.each([+ ['', 'General'],+ ['#,##0_);(#,##0)', 'Thousands separator'],+ ])('preserves the built-in format %j when confirming without edits', async (pattern, category) => {+ const { container, onChange } = await renderPanel({+ defaultValue: 5800,+ defaultPattern: pattern,+ row: 3,+ col: 3,+ });++ await confirmPanel(container);++ expect(onChange).toHaveBeenCalledExactlyOnceWith({ type: 'confirm', value: pattern });+ expect(container.querySelector('[data-u-comp="select"]')?.textContent).toBe(category);+ });});