Skip to content

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

fix(sheets-ui): simplify status bar statistics (#7493)

wpxp123456291e60a2b833
diff --git a/packages/sheets-ui/src/views/status-bar/CopyableStatisticItem.tsx b/packages/sheets-ui/src/views/status-bar/CopyableStatisticItem.tsx
index 32e2417e46..c5f54fbcac 100644
--- a/packages/sheets-ui/src/views/status-bar/CopyableStatisticItem.tsx
+++ b/packages/sheets-ui/src/views/status-bar/CopyableStatisticItem.tsx
@@ -15,12 +15,8 @@
*/
import type { IFunctionNames } from '@univerjs/engine-formula';
-import type { FC } from 'react';
-import type { LocaleKey } from '../../locale/types';
-import { LocaleService, numfmt } from '@univerjs/core';
-import { MessageType, Tooltip } from '@univerjs/design';
+import { numfmt } from '@univerjs/core';
import { FUNCTION_NAMES_MATH, FUNCTION_NAMES_STATISTICAL, FUNCTION_NAMES_TEXT } from '@univerjs/engine-formula';
-import { IClipboardInterfaceService, IMessageService, useDependency } from '@univerjs/ui';
export interface IStatisticItem {
name: IFunctionNames;
@@ -51,50 +47,12 @@ interface IFunctionNameMap {
[key: string]: string;
}
-export const CopyableStatisticItem: FC<IStatisticItem> = (item: IStatisticItem) => {
- const localeService = useDependency(LocaleService);
- const messageService = useDependency(IMessageService);
- const clipboardService = useDependency(IClipboardInterfaceService);
-
- const formateValue = formatNumber(item);
-
- const copyToClipboard = async () => {
- await clipboardService.writeText(item.value.toString());
- messageService.show({
- type: MessageType.Success,
- content: localeService.t<LocaleKey>('sheets-ui.statusbar.copied'),
- });
- };
- return (
- <Tooltip title={localeService.t<LocaleKey>('sheets-ui.statusbar.clickToCopy')} placement="top">
- <div
- key={item.name}
- className={`
- univer-flex univer-cursor-pointer univer-truncate univer-text-center univer-text-xs
- univer-text-gray-400
- `}
- onClick={copyToClipboard}
- >
- <span>
- {`${localeService.t(
- functionDisplayNames?.[item.name as string] || (item.name as string)
- )}: ${formateValue}`}
- </span>
- </div>
- </Tooltip>
- );
-};
-
export function formatNumber(item: IStatisticItem) {
const { pattern, value: num } = item;
if (typeof num !== 'number') {
return 0;
}
- if (num >= 1e8) {
- return num.toExponential(2);
- }
-
if (pattern && allowPatternFunctions.includes(item.name)) {
return numfmt.format(pattern, num, { throws: false });
}
diff --git a/packages/sheets-ui/src/views/status-bar/StatusBar.tsx b/packages/sheets-ui/src/views/status-bar/StatusBar.tsx
index 6c02bcffa4..84a03eb711 100644
--- a/packages/sheets-ui/src/views/status-bar/StatusBar.tsx
+++ b/packages/sheets-ui/src/views/status-bar/StatusBar.tsx
@@ -15,145 +15,141 @@
*/
import type { Nullable } from '@univerjs/core';
-import type { ComponentType } from 'react';
+import type { IFunctionNames } from '@univerjs/engine-formula';
import type { IStatusBarServiceStatus } from '../../services/status-bar.service';
import type { IStatisticItem } from './CopyableStatisticItem';
-import { debounce } from '@univerjs/core';
-import { clsx } from '@univerjs/design';
+import { LocaleService } from '@univerjs/core';
+import { clsx, Dropdown, Tooltip } from '@univerjs/design';
+import { FUNCTION_NAMES_MATH } from '@univerjs/engine-formula';
+import { CheckMarkIcon, MoreDownIcon } from '@univerjs/icons';
import { useDependency } from '@univerjs/ui';
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { IStatusBarService } from '../../services/status-bar.service';
-import { CopyableStatisticItem } from './CopyableStatisticItem';
+import { useEffect, useState } from 'react';
-const SINGLE_MODE_WIDTH = 800;
-const ROW_COUNT_THRESHOLD = 3;
+import { IStatusBarService } from '../../services/status-bar.service';
+import { formatNumber, functionDisplayNames } from './CopyableStatisticItem';
export const StatusBar = () => {
- const [isSingle, setIsSingle] = useState(window.innerWidth < SINGLE_MODE_WIDTH);
-
+ const localeService = useDependency(LocaleService);
const statusBarService = useDependency(IStatusBarService);
- // items is six functions: MAX MIN ALL ...
- const items = statusBarService.getFunctions().map((item, index) => ({
- name: item.func,
- value: 0,
- show: true,
- disable: false,
- pattern: null,
- }));
-
- const useStatistics = (
- initialItems: IStatisticItem[],
- statusBarService: IStatusBarService,
- isSingle: boolean
- ) => {
- const [statistics, setStatistics] = useState<IStatisticItem[]>(initialItems);
- const [show, setShow] = useState(true);
-
- const filteredStatistics = useMemo(() =>
- statistics.filter((item) => item.show && !item.disable), [statistics]);
-
- const firstItem = useMemo(() =>
- filteredStatistics.find((item) => item.show && !item.disable), [filteredStatistics]);
-
- const showList = useMemo(() =>
- isSingle && firstItem ? [firstItem] : filteredStatistics, [isSingle, firstItem, filteredStatistics]);
-
- const updateStatistics = useCallback((state: Nullable<IStatusBarServiceStatus>) => {
- const items = state?.values;
- if (!items?.length) {
- setShow(false);
- return;
- }
-
- setShow(true);
- setStatistics((prevStats) =>
- prevStats.map((stat) => ({
- ...stat,
- value: items.find((i) => i.func === stat.name)?.value ?? stat.value,
- disable: !items.some((i) => i.func === stat.name),
- pattern: state?.pattern ?? null,
- }))
- );
- }, []);
-
- useEffect(() => {
- const subscription = statusBarService.state$.subscribe(updateStatistics);
-
- return () => subscription.unsubscribe();
- }, [statusBarService, updateStatistics]);
-
- return {
- statistics,
- showList,
- show,
- };
- };
-
- const { showList, show } = useStatistics(
- items,
- statusBarService,
- isSingle
+ const [selectedFunction, setSelectedFunction] = useState<IFunctionNames>(FUNCTION_NAMES_MATH.SUM);
+ const [open, setOpen] = useState(false);
+ const [statistics, setStatistics] = useState<IStatisticItem[]>(() =>
+ statusBarService.getFunctions().map((item) => ({
+ name: item.func,
+ value: 0,
+ show: true,
+ disable: true,
+ pattern: null,
+ }))
);
- const handleResize = debounce(() => {
- const newSingleState = window.innerWidth < SINGLE_MODE_WIDTH;
- if (isSingle !== newSingleState) {
- setIsSingle(newSingleState);
- }
- }, 100);
useEffect(() => {
- window.addEventListener('resize', handleResize);
-
- return () => {
- window.removeEventListener('resize', handleResize);
- };
- }, [isSingle]);
-
- const getStatisticLayout = (
- showList: IStatisticItem[],
- rowCountThreshold: number,
- CopyableStatisticItem: ComponentType<IStatisticItem>
- ) => {
- if (showList.length > rowCountThreshold) {
- const doubleLineList = showList.reduce<IStatisticItem[][]>((acc, _, index) => {
- if (index % 2 === 0) {
- acc.push(showList.slice(index, index + 2));
- }
- return acc;
- }, []);
-
- return doubleLineList.map((item, index) => (
- <div key={`stat-col-${index}`} className="univer-grid univer-h-full univer-items-center">
- {item[0] && <CopyableStatisticItem key={item[0].name} {...item[0]} />}
- {item[1] && <CopyableStatisticItem key={item[1].name} {...item[1]} />}
- </div>
- ));
- }
-
- return showList.map((item) => (
- <div key={item.name} className="univer-grid univer-h-full univer-items-center">
- <CopyableStatisticItem {...item} />
- </div>
- ));
+ const subscription = statusBarService.state$.subscribe((state: Nullable<IStatusBarServiceStatus>) => {
+ const values = state?.values ?? [];
+ setStatistics((previousStatistics) =>
+ previousStatistics.map((statistic) => {
+ const value = values.find((item) => item.func === statistic.name);
+ return {
+ ...statistic,
+ value: value?.value ?? statistic.value,
+ disable: !value,
+ pattern: state?.pattern ?? null,
+ };
+ })
+ );
+ });
+
+ return () => subscription.unsubscribe();
+ }, [statusBarService]);
+
+ const availableStatistics = statistics.filter((item) => item.show && !item.disable);
+ const selectedStatistic = availableStatistics.find((item) => item.name === selectedFunction) ??
+ availableStatistics.find((item) => item.name === FUNCTION_NAMES_MATH.SUM) ??
+ availableStatistics[0];
+ if (!selectedStatistic) {
+ return null;
+ }
+
+ const formatStatistic = (item: IStatisticItem) => {
+ const localeKey = functionDisplayNames[item.name as string] || (item.name as string);
+ return `${localeService.t(localeKey)}: ${formatNumber(item)}`;
};
- const renderContent = getStatisticLayout(showList, ROW_COUNT_THRESHOLD, CopyableStatisticItem);
+ const handleSelect = (name: IFunctionNames) => {
+ setSelectedFunction(name);
+ setOpen(false);
+ };
return (
- show && (
- <div
- className={clsx(`
- univer-relative univer-box-border univer-flex univer-h-full univer-items-center univer-overflow-hidden
- univer-px-2
- after:univer-absolute after:univer-right-0 after:univer-top-1/2 after:univer-block after:univer-h-4
- after:univer-w-px after:-univer-translate-y-1/2 after:univer-bg-gray-200 after:univer-content-[""]
- `, {
- 'univer-max-w-32': isSingle,
- 'univer-max-w-fit': !isSingle,
- })}
+ <div
+ className={`
+ univer-relative univer-box-border univer-flex univer-h-full univer-min-w-0 univer-max-w-64
+ univer-items-center univer-overflow-hidden univer-px-2
+ after:univer-absolute after:univer-right-0 after:univer-top-1/2 after:univer-block after:univer-h-4
+ after:univer-w-px after:-univer-translate-y-1/2 after:univer-bg-gray-200 after:univer-content-[""]
+ `}
+ >
+ <Dropdown
+ align="end"
+ side="top"
+ open={open}
+ onOpenChange={setOpen}
+ overlay={(
+ <div
+ data-u-comp="status-bar-statistic-menu"
+ className={`
+ univer-grid univer-w-max univer-max-w-[calc(100vw-16px)] univer-gap-0.5 univer-p-1.5
+ `}
+ >
+ {availableStatistics.map((item) => {
+ const text = formatStatistic(item);
+ const selected = item.name === selectedStatistic.name;
+ return (
+ <button
+ key={item.name}
+ type="button"
+ className={clsx(`
+ univer-flex univer-cursor-pointer univer-items-center univer-gap-2 univer-rounded
+ univer-border-none univer-bg-transparent univer-px-2 univer-py-1.5
+ univer-text-left univer-text-xs univer-text-gray-900
+ hover:univer-bg-gray-100
+ dark:!univer-text-gray-200
+ dark:hover:!univer-bg-gray-800
+ `, {
+ 'univer-bg-gray-100 dark:!univer-bg-gray-800': selected,
+ })}
+ aria-pressed={selected}
+ onClick={() => handleSelect(item.name)}
+ >
+ <span className="univer-w-3 univer-shrink-0">
+ {selected && <CheckMarkIcon />}
+ </span>
+ <Tooltip title={text} placement="top">
+ <span className="univer-min-w-0 univer-flex-1 univer-truncate">{text}</span>
+ </Tooltip>
+ </button>
+ );
+ })}
+ </div>
+ )}
>
- <div className="univer-flex univer-h-full univer-gap-x-2">{renderContent}</div>
- </div>
- )
+ <button
+ type="button"
+ data-u-comp="status-bar-statistic-picker"
+ className={`
+ univer-flex univer-min-w-0 univer-max-w-full univer-cursor-pointer univer-items-center
+ univer-gap-1 univer-border-none univer-bg-transparent univer-p-0 univer-text-xs
+ univer-text-gray-400
+ `}
+ >
+ <Tooltip title={formatStatistic(selectedStatistic)} placement="top">
+ <span className="univer-min-w-0 univer-flex-1 univer-truncate">
+ {formatStatistic(selectedStatistic)}
+ </span>
+ </Tooltip>
+ <MoreDownIcon className="univer-shrink-0" />
+ </button>
+ </Dropdown>
+ </div>
);
};
diff --git a/packages/sheets-ui/src/views/status-bar/__tests__/StatusBar.spec.tsx b/packages/sheets-ui/src/views/status-bar/__tests__/StatusBar.spec.tsx
index a074965181..0ff45c7881 100644
--- a/packages/sheets-ui/src/views/status-bar/__tests__/StatusBar.spec.tsx
+++ b/packages/sheets-ui/src/views/status-bar/__tests__/StatusBar.spec.tsx
@@ -14,17 +14,15 @@
* limitations under the License.
*/
-import type { IDisposable } from '@univerjs/core';
-import type { IMessageProps } from '@univerjs/design';
import type { ReactElement } from 'react';
import { Injector, LocaleService } from '@univerjs/core';
import { FUNCTION_NAMES_MATH, FUNCTION_NAMES_STATISTICAL } from '@univerjs/engine-formula';
-import { IClipboardInterfaceService, IMessageService, RediContext } from '@univerjs/ui';
+import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, describe, expect, it } from 'vitest';
import { IStatusBarService, StatusBarService } from '../../../services/status-bar.service';
-import { CopyableStatisticItem } from '../CopyableStatisticItem';
+import { formatNumber } from '../CopyableStatisticItem';
import { StatusBar } from '../StatusBar';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -35,47 +33,6 @@ class TestLocaleService {
}
}
-class TestClipboardService {
- readonly supportClipboard = true;
-
- async writeText(text: string): Promise<void> {
- TestState.copiedText = text;
- }
-
- async write(text: string): Promise<void> {
- TestState.copiedText = text;
- }
-
- async readText(): Promise<string> {
- return TestState.copiedText;
- }
-
- async read(): Promise<ClipboardItem[]> {
- return [];
- }
-}
-
-class TestMessageService {
- show(options: IMessageProps): IDisposable {
- TestState.messages.push(String(options.content));
- return { dispose(): void {} };
- }
-
- remove(): void {}
-
- removeAll(): void {}
-}
-
-class TestState {
- static copiedText = '';
- static messages: string[] = [];
-
- static reset(): void {
- this.copiedText = '';
- this.messages = [];
- }
-}
-
function setViewportWidth(width: number) {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
@@ -88,8 +45,6 @@ function createStatusBarInjector() {
const injector = new Injector();
injector.add([LocaleService, { useClass: TestLocaleService as never }]);
injector.add([IStatusBarService, { useClass: StatusBarService }]);
- injector.add([IClipboardInterfaceService, { useClass: TestClipboardService as never }]);
- injector.add([IMessageService, { useClass: TestMessageService as never }]);
return injector;
}
@@ -161,64 +116,73 @@ describe('StatusBar', () => {
afterEach(() => {
disposals.splice(0).forEach((dispose) => dispose());
- TestState.reset();
setViewportWidth(1024);
});
- it('renders filtered statistics from service state with number formatting', () => {
+ it('shows only sum by default with number formatting', () => {
setViewportWidth(1024);
const { container, injector, unmount } = renderWithDependencies(<StatusBar />);
disposals.push(unmount);
publishStatistics(injector);
- expect(getByText(container, 'sheets-ui.statusbar.max: 12.50')).toBeTruthy();
- expect(getByText(container, 'sheets-ui.statusbar.min: 3.00')).toBeTruthy();
expect(getByText(container, 'sheets-ui.statusbar.sum: 15.50')).toBeTruthy();
- expect(getByText(container, 'sheets-ui.statusbar.countA: 3')).toBeTruthy();
- expect(getByText(container, 'sheets-ui.statusbar.count: 2')).toBeTruthy();
- expect(getByText(container, 'sheets-ui.statusbar.average: 7.75')).toBeTruthy();
+ expect(queryByText(container, 'sheets-ui.statusbar.max: 12.50')).toBeNull();
+ expect(queryByText(container, 'sheets-ui.statusbar.average: 7.75')).toBeNull();
});
- it('keeps only the first available statistic in narrow viewports', () => {
- setViewportWidth(640);
+ it('opens all available statistics and changes the displayed statistic', () => {
const { container, injector, unmount } = renderWithDependencies(<StatusBar />);
disposals.push(unmount);
publishStatistics(injector);
- expect(getByText(container, 'sheets-ui.statusbar.max: 12.50')).toBeTruthy();
- expect(queryByText(container, 'sheets-ui.statusbar.min: 3.00')).toBeNull();
- expect(queryByText(container, 'sheets-ui.statusbar.sum: 15.50')).toBeNull();
- });
-});
+ const statisticText = getByText(container, 'sheets-ui.statusbar.sum: 15.50');
+ act(() => statisticText.click());
-describe('CopyableStatisticItem', () => {
- const disposals: Array<() => void> = [];
+ expect(getByText(document.body, 'sheets-ui.statusbar.max: 12.50')).toBeTruthy();
+ expect(getByText(document.body, 'sheets-ui.statusbar.average: 7.75')).toBeTruthy();
+ expect(document.body.querySelector('[data-u-comp="status-bar-statistic-menu"]')?.className)
+ .toContain('univer-w-max');
- afterEach(() => {
- disposals.splice(0).forEach((dispose) => dispose());
- TestState.reset();
+ act(() => {
+ getByText(document.body, 'sheets-ui.statusbar.average: 7.75').click();
+ });
+
+ expect(getByText(container, 'sheets-ui.statusbar.average: 7.75')).toBeTruthy();
+ expect(queryByText(container, 'sheets-ui.statusbar.sum: 15.50')).toBeNull();
});
- it('copies the raw statistic value and reports a success message', async () => {
- const { container, unmount } = renderWithDependencies(
- <CopyableStatisticItem
- name={FUNCTION_NAMES_MATH.SUM}
- value={1234.5}
- show
- disable={false}
- pattern="0.00"
- />
- );
+ it('falls back to count when the selection has no numeric values', () => {
+ const { container, injector, unmount } = renderWithDependencies(<StatusBar />);
disposals.push(unmount);
- await act(async () => {
- getByText(container, 'sheets-ui.statusbar.sum: 1234.50').dispatchEvent(new MouseEvent('click', { bubbles: true }));
- await Promise.resolve();
+ act(() => {
+ injector.get(IStatusBarService).setState({
+ pattern: null,
+ values: [
+ { func: FUNCTION_NAMES_STATISTICAL.COUNTA, value: 3 },
+ { func: FUNCTION_NAMES_STATISTICAL.COUNT, value: 0 },
+ ],
+ });
});
- expect(TestState.copiedText).toBe('1234.5');
- expect(TestState.messages).toEqual(['sheets-ui.statusbar.copied']);
+ expect(getByText(container, 'sheets-ui.statusbar.countA: 3')).toBeTruthy();
+ });
+});
+
+describe('formatNumber', () => {
+ it('does not force positive or negative large values into scientific notation', () => {
+ const value = 1_273_000_000;
+
+ for (const largeValue of [value, -value]) {
+ expect(formatNumber({
+ name: FUNCTION_NAMES_MATH.SUM,
+ value: largeValue,
+ show: true,
+ disable: false,
+ pattern: null,
+ })).toBe(largeValue.toLocaleString());
+ }
});
});