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): statusbar (#442)
YuHonga494f98bcb55
diff --git a/packages/base-formula-engine/src/functions/average.ts b/packages/base-formula-engine/src/functions/average.tsindex 628e7983f9..82b69e487c 100644--- a/packages/base-formula-engine/src/functions/average.ts+++ b/packages/base-formula-engine/src/functions/average.ts@@ -12,6 +12,7 @@ export class Average extends BaseFunction {const accumulatorSum = functionService.getExecutor(FUNCTION_NAMES.SUM)?.calculate(...variants);const accumulatorCount = functionService.getExecutor(FUNCTION_NAMES.COUNT)?.calculate(...variants);+ //TODO@DR-Univer: accumulatorCount should be calculated by numeric type count instead of all countsif (accumulatorSum == null ||diff --git a/packages/base-formula-engine/src/index.ts b/packages/base-formula-engine/src/index.tsindex 021e015d03..c6fc0e75d7 100644--- a/packages/base-formula-engine/src/index.ts+++ b/packages/base-formula-engine/src/index.ts@@ -8,4 +8,7 @@ export type {IUnitSheetNameMap,} from './basics/common';export { FUNCTION_NAMES, FunctionType, type IFunctionInfo, type IFunctionParam } from './basics/function';+export { RangeReferenceObject } from './reference-object/range-reference-object';export { FormulaEngineService } from './services/formula-engine.service';+export { IFunctionService } from './services/function.service';+export type { BaseValueObject } from './value-object/base-value-object';diff --git a/packages/base-formula-engine/src/value-object/primitive-object.ts b/packages/base-formula-engine/src/value-object/primitive-object.tsindex f1e993eed4..e46306c07f 100644--- a/packages/base-formula-engine/src/value-object/primitive-object.ts+++ b/packages/base-formula-engine/src/value-object/primitive-object.ts@@ -204,7 +204,12 @@ export class NumberValueObject extends BaseValueObject {if (valueObject.isArray()) {return valueObject.plus(this);}- return this.plusBy(valueObject.getValue());+ const object = this.plusBy(valueObject.getValue());+ if (object.isErrorObject()) {+ return this;+ }++ return object;}equalZero() {@@ -219,7 +224,12 @@ export class NumberValueObject extends BaseValueObject {}return (o as BaseValueObject).plus(this);}- return this.minusBy(valueObject.getValue());+ const object = this.minusBy(valueObject.getValue());+ if (object.isErrorObject()) {+ return this;+ }++ return object;}override multiply(valueObject: BaseValueObject): CalculateValueType {diff --git a/packages/ui-plugin-sheets/package.json b/packages/ui-plugin-sheets/package.jsonindex 87c8ce5d04..09b8636963 100644--- a/packages/ui-plugin-sheets/package.json+++ b/packages/ui-plugin-sheets/package.json@@ -57,7 +57,8 @@"@wendellhu/redi": "^0.12.11","react": "^18.2.0","react-dom": "^18.2.0",- "rxjs": "^7.8.1"+ "rxjs": "^7.8.1",+ "clsx": "^2.0.0"},"devDependencies": {"@types/node": "^20.9.0",diff --git a/packages/ui-plugin-sheets/src/controllers/status-bar.controller.ts b/packages/ui-plugin-sheets/src/controllers/status-bar.controller.tsnew file mode 100644index 0000000000..0ae4ef1684--- /dev/null+++ b/packages/ui-plugin-sheets/src/controllers/status-bar.controller.ts@@ -0,0 +1,85 @@+import { BaseValueObject, FormulaEngineService, ISheetData, RangeReferenceObject } from '@univerjs/base-formula-engine';+import { ISelectionWithStyle, SelectionManagerService } from '@univerjs/base-sheets';+import { Disposable, IRange, IUniverInstanceService, LifecycleStages, ObjectMatrix, OnLifecycle } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';++import { IStatusBarService, IStatusBarServiceStatus } from '../services/status-bar.service';++@OnLifecycle(LifecycleStages.Ready, StatusBarController)+export class StatusBarController extends Disposable {+ constructor(+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,+ @IStatusBarService private readonly _statusBarService: IStatusBarService+ ) {+ super();++ this._init();+ }++ private _init(): void {+ this._registerSelectionListener();+ }++ private _registerSelectionListener(): void {+ this._selectionManagerService.selectionInfo$.subscribe((selectionRangeWithStyle) => {+ if (selectionRangeWithStyle) {+ this._calculateSelection(selectionRangeWithStyle);+ }+ });+ }++ private _calculateSelection(selections: ISelectionWithStyle[]) {+ const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();+ const unitId = workbook.getUnitId();+ const sheetId = workbook.getActiveSheet().getSheetId();+ const sheetData: ISheetData = {};+ this._univerInstanceService+ .getCurrentUniverSheetInstance()+ .getSheets()+ .forEach((sheet) => {+ const sheetConfig = sheet.getConfig();+ sheetData[sheet.getSheetId()] = {+ cellData: new ObjectMatrix(sheetConfig.cellData),+ rowCount: sheetConfig.rowCount,+ columnCount: sheetConfig.columnCount,+ };+ });+ if (selections?.length && (selections?.length > 1 || !this._isSingleCell(selections[0].range))) {+ const refs = selections.map((s) => new RangeReferenceObject(s.range, sheetId, unitId));+ refs.forEach((ref) =>+ ref.setUnitData({+ [unitId]: sheetData,+ })+ );++ const functions = this._statusBarService.getFunctions();+ const calcResult = functions.map((f) => {+ const executor = this._formulaEngineService.getExecutor(f);+ if (!executor) {+ return undefined;+ }+ const res = executor?.calculate(...refs) as BaseValueObject;+ if (!res.getValue) {+ return undefined;+ }+ return {+ func: f,+ value: (executor?.calculate(...refs) as BaseValueObject).getValue(),+ };+ });+ if (calcResult.every((r) => r === undefined)) {+ return;+ }+ const availableResult = calcResult.filter((r) => r !== undefined);+ this._statusBarService.setState(availableResult as IStatusBarServiceStatus);+ } else {+ this._statusBarService.setState(null);+ }+ }++ private _isSingleCell(range: IRange) {+ return range.startRow === range.endRow && range.startColumn === range.endColumn;+ }+}diff --git a/packages/ui-plugin-sheets/src/locale/en-US.ts b/packages/ui-plugin-sheets/src/locale/en-US.tsindex 1b84820900..01b7093d66 100644--- a/packages/ui-plugin-sheets/src/locale/en-US.ts+++ b/packages/ui-plugin-sheets/src/locale/en-US.ts@@ -537,4 +537,13 @@ export default {exceedMaxCells: 'The number of cells pasted exceeds the maximum number of cells',},},+ statusbar: {+ sum: 'sum',+ average: 'average',+ min: 'min',+ max: 'max',+ count: 'count',+ clickToCopy: 'click to copy',+ copied: 'copied!',+ },};diff --git a/packages/ui-plugin-sheets/src/locale/zh-CN.ts b/packages/ui-plugin-sheets/src/locale/zh-CN.tsindex 2f6d7ced9f..5bcf7fce9c 100644--- a/packages/ui-plugin-sheets/src/locale/zh-CN.ts+++ b/packages/ui-plugin-sheets/src/locale/zh-CN.ts@@ -401,4 +401,13 @@ export default {exceedMaxCells: '粘贴区域超出最大单元格数',},},+ statusbar: {+ sum: '求和',+ average: '平均值',+ min: '最小值',+ max: '最大值',+ count: '计数',+ clickToCopy: '点击复制数值',+ copied: '数据复制成功,快去粘贴数据吧!',+ },};diff --git a/packages/ui-plugin-sheets/src/services/status-bar.service.ts b/packages/ui-plugin-sheets/src/services/status-bar.service.tsnew file mode 100644index 0000000000..efebf8400d--- /dev/null+++ b/packages/ui-plugin-sheets/src/services/status-bar.service.ts@@ -0,0 +1,47 @@+import { FUNCTION_NAMES } from '@univerjs/base-formula-engine';+import { Nullable } from '@univerjs/core';+import { createIdentifier, IDisposable } from '@wendellhu/redi';+import { BehaviorSubject, Observable } from 'rxjs';++export interface IStatusBarService {+ state$: Observable<Nullable<IStatusBarServiceStatus>>;+ dispose(): void;+ setState(param: IStatusBarServiceStatus | null): void;+ getState(): Readonly<Nullable<IStatusBarServiceStatus>>;+ getFunctions(): Readonly<FUNCTION_NAMES[]>;+}++export type IStatusBarServiceStatus = Array<{+ func: FUNCTION_NAMES;+ value: number;+}>;++export class StatusBarService implements IStatusBarService, IDisposable {+ private readonly _functions = [+ FUNCTION_NAMES.SUM,+ FUNCTION_NAMES.MAX,+ FUNCTION_NAMES.MIN,+ FUNCTION_NAMES.AVERAGE,+ FUNCTION_NAMES.COUNT,+ ];+ private readonly _state$ = new BehaviorSubject<Nullable<IStatusBarServiceStatus>>(null);+ readonly state$ = this._state$.asObservable();++ dispose(): void {+ this._state$.complete();+ }++ setState(param: IStatusBarServiceStatus | null) {+ this._state$.next(param);+ }++ getState(): Readonly<Nullable<IStatusBarServiceStatus>> {+ return this._state$.getValue();+ }++ getFunctions(): Readonly<FUNCTION_NAMES[]> {+ return this._functions;+ }+}++export const IStatusBarService = createIdentifier<StatusBarService>('univer.sheet-status-bar.service');diff --git a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts b/packages/ui-plugin-sheets/src/sheet-ui-plugin.tsindex 96a726fd0c..6c7b88fceb 100644--- a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts+++ b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts@@ -25,6 +25,7 @@ import { ScrollController } from './controllers/scroll.controller';import { SelectionController } from './controllers/selection.controller';import { SheetRenderController } from './controllers/sheet-render.controller';import { SheetUIController } from './controllers/sheet-ui.controller';+import { StatusBarController } from './controllers/status-bar.controller';import { ZoomController } from './controllers/zoom.controller';import { enUS } from './locale';import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';@@ -36,6 +37,7 @@ import { ScrollManagerService } from './services/scroll-manager.service';import { ISelectionRenderService, SelectionRenderService } from './services/selection/selection-render.service';import { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';import { ISheetBarService, SheetBarService } from './services/sheetbar/sheetbar.service';+import { IStatusBarService, StatusBarService } from './services/status-bar.service';import { SheetCanvasView } from './views/sheet-canvas-view';export class SheetUIPlugin extends Plugin {@@ -76,6 +78,7 @@ export class SheetUIPlugin extends Plugin {},],[FormulaEngineService],+ [IStatusBarService, { useClass: StatusBarService }],// controllers[AutoHeightController],@@ -100,6 +103,7 @@ export class SheetUIPlugin extends Plugin {[StartEditController],[ZoomController],[AutoFillController],+ [StatusBarController],] as Dependency[]).forEach((d) => injector.add(d));}diff --git a/packages/ui-plugin-sheets/src/views/count-bar/index.module.less b/packages/ui-plugin-sheets/src/views/count-bar/index.module.lessindex 512d14f29a..8f35045f9d 100644--- a/packages/ui-plugin-sheets/src/views/count-bar/index.module.less+++ b/packages/ui-plugin-sheets/src/views/count-bar/index.module.less@@ -1,5 +1,5 @@.count-bar {display: flex;- flex: 0 0 auto;+ flex: 0 0 260px;justify-content: flex-end;}diff --git a/packages/ui-plugin-sheets/src/views/sheet-bar/index.module.less b/packages/ui-plugin-sheets/src/views/sheet-bar/index.module.lessindex 068056af66..791feea533 100644--- a/packages/ui-plugin-sheets/src/views/sheet-bar/index.module.less+++ b/packages/ui-plugin-sheets/src/views/sheet-bar/index.module.less@@ -1,16 +1,17 @@@sheet-bar-max-width: 1515px;-@right-width: 300px;+@status-bar-max-width: 332px;+@zoom-slider-width: 260px;.sheet-bar {position: relative;display: flex;- flex: 1;+ flex: 1 1 0px;flex-direction: row;- width: calc(100% - @right-width);- max-width: @sheet-bar-max-width;+ max-width: calc(100% - @zoom-slider-width);+ min-width: calc(100% - @zoom-slider-width - @status-bar-max-width);height: 100%;background-color: rgb(var(--bg-color));diff --git a/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/index.module.less b/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/index.module.lessindex 8f6d2b5828..64ff55bdeb 100644--- a/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/index.module.less+++ b/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/index.module.less@@ -3,6 +3,7 @@.slide-tab-bar-container {overflow: hidden;+ max-width: calc(100% - 112px);.slide-tab-bar {user-select: none;diff --git a/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx b/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsxindex e65da8d1b6..40186865e6 100644--- a/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx+++ b/packages/ui-plugin-sheets/src/views/sheet-container/SheetContainer.tsx@@ -4,6 +4,7 @@ import { EditorContainer } from '../editor-container/EditorContainer';import { FormulaBar } from '../formula-bar/FormulaBar';import { OperateContainer } from '../operate-container/OperateContainer';import { SheetBar } from '../sheet-bar/SheetBar';+import { StatusBar } from '../status-bar/StatusBar';import styles from './index.module.less';export interface BaseSheetContainerProps {@@ -16,6 +17,7 @@ export function RenderSheetFooter() {return (<section className={styles.sheetContainer}><SheetBar />+ <StatusBar /><CountBar /></section>);diff --git a/packages/ui-plugin-sheets/src/views/status-bar/CopyableStatisticItem.tsx b/packages/ui-plugin-sheets/src/views/status-bar/CopyableStatisticItem.tsxnew file mode 100644index 0000000000..1f0200aa1c--- /dev/null+++ b/packages/ui-plugin-sheets/src/views/status-bar/CopyableStatisticItem.tsx@@ -0,0 +1,58 @@+import { FUNCTION_NAMES } from '@univerjs/base-formula-engine';+import { IClipboardInterfaceService, IMessageService } from '@univerjs/base-ui';+import { LocaleService } from '@univerjs/core';+import { MessageType, Tooltip } from '@univerjs/design';+import { useDependency } from '@wendellhu/redi/react-bindings';++import styles from './index.module.less';++export interface IStatisticItem {+ name: FUNCTION_NAMES;+ value: number;+ show: boolean;+}++export const functionDisplayNames: FunctionNameMap = {+ [FUNCTION_NAMES.SUM]: 'statusbar.sum',+ [FUNCTION_NAMES.AVERAGE]: 'statusbar.average',+ [FUNCTION_NAMES.MIN]: 'statusbar.min',+ [FUNCTION_NAMES.MAX]: 'statusbar.max',+ [FUNCTION_NAMES.COUNT]: 'statusbar.count',+ [FUNCTION_NAMES.CONCATENATE]: 'concatenate',+};+type FunctionNameMap = {+ [key: string]: string;+};++export const CopyableStatisticItem: React.FC<IStatisticItem> = (item: IStatisticItem) => {+ const localeService = useDependency(LocaleService);+ const messageService = useDependency(IMessageService);+ const clipboardService = useDependency(IClipboardInterfaceService);++ const formateValue = formatNumber(item.value);+ const copyToClipboard = async () => {+ await clipboardService.writeText(item.value.toString());+ messageService.show({+ type: MessageType.Success,+ content: localeService.t('statusbar.copied'),+ });+ };+ return (+ <Tooltip title={localeService.t('statusbar.clickToCopy')} placement="top">+ <div key={item.name} className={styles.statisticItem} onClick={copyToClipboard}>+ <span>{`${localeService.t(functionDisplayNames?.[item.name] || item.name)}: ${formateValue}`}</span>+ </div>+ </Tooltip>+ );+};++export function formatNumber(num: number) {+ if (typeof num !== 'number') {+ return 'Invalid input';+ }++ if (num >= 1e8) {+ return num.toExponential(2);+ }+ return num.toLocaleString();+}diff --git a/packages/ui-plugin-sheets/src/views/status-bar/StatusBar.tsx b/packages/ui-plugin-sheets/src/views/status-bar/StatusBar.tsxnew file mode 100644index 0000000000..11ec47e034--- /dev/null+++ b/packages/ui-plugin-sheets/src/views/status-bar/StatusBar.tsx@@ -0,0 +1,142 @@+import { LocaleService } from '@univerjs/core';+import { Checkbox, Dropdown } from '@univerjs/design';+import { MoreSingle } from '@univerjs/icons';+import { useDependency } from '@wendellhu/redi/react-bindings';+import clsx from 'clsx';+import { useEffect, useState } from 'react';++import { IStatusBarService } from '../../services/status-bar.service';+import { CopyableStatisticItem, formatNumber, functionDisplayNames, IStatisticItem } from './CopyableStatisticItem';+import styles from './index.module.less';++const SINGLE_MODE_WIDTH = 800;++export const StatusBar = () => {+ const [isSingle, setIsSingle] = useState(window.innerWidth < SINGLE_MODE_WIDTH);+ const [show, setShow] = useState(true);++ const localeService = useDependency(LocaleService);+ const statusBarService = useDependency(IStatusBarService);+ const items = statusBarService.getFunctions().map((item, index) => ({+ name: item,+ value: 0,+ show: isSingle ? index < 1 : index < 3,+ }));+ const [statistics, setStatistics] = useState<IStatisticItem[]>(items);+ const showList = statistics.filter((item) => item.show);++ const onChange = (item: IStatisticItem) => {+ const newStatistics = statistics.map((stat) => {+ if (stat.name === item.name) {+ stat.show = !stat.show;+ } else if (isSingle) {+ stat.show = false;+ }+ return stat;+ });+ setStatistics(newStatistics);+ };++ useEffect(() => {+ const subscription = statusBarService.state$.subscribe((item) => {+ if (!item) {+ setShow(false);+ } else {+ setShow(true);+ const newStatistics = statistics.map((stat) => {+ const target = item.find((i) => i.func === stat.name);+ stat.value = target?.value ?? stat.value;+ return stat;+ });+ setStatistics(newStatistics);+ }+ });+ return () => {+ subscription.unsubscribe();+ };+ }, [statusBarService]);++ const handleResize = () => {+ const newSingleState = window.innerWidth < SINGLE_MODE_WIDTH;+ if (isSingle !== newSingleState) {+ if (newSingleState) {+ // keep the items hide except the first show item+ const firstIndex = statistics.findIndex((item) => item.show);+ const newStatistics = statistics.map((stat, index) => {+ if (index === firstIndex) {+ stat.show = true;+ } else {+ stat.show = false;+ }+ return stat;+ });+ setStatistics(newStatistics);+ }+ setIsSingle(newSingleState);+ }+ };++ useEffect(() => {+ window.addEventListener('resize', handleResize);++ return () => {+ window.removeEventListener('resize', handleResize);+ };+ }, []);++ return (+ show && (+ <div+ className={clsx(styles.statusBar, {+ [styles.singleMode]: isSingle,+ })}+ >+ <div+ className={clsx(styles.statisticList, {+ [styles.statisticListTwoRow]: showList.length > 3,+ })}+ >+ {showList.length > 3 ? (+ <>+ <div className={styles.statisticListRow}>+ {showList.slice(0, 3).map((item) => (+ <CopyableStatisticItem key={item.name} {...item} />+ ))}+ </div>+ <div className={styles.statisticListRow}>+ {showList.slice(3).map((item) => (+ <CopyableStatisticItem key={item.name} {...item} />+ ))}+ </div>+ </>+ ) : (+ showList.map((item) => <CopyableStatisticItem key={item.name} {...item} />)+ )}+ </div>+ <Dropdown+ placement="topRight"+ overlay={+ <div className={styles.statisticPicker}>+ {statistics?.map((item) => (+ <a key={item.name} className={styles.statisticPickerItem}>+ <Checkbox+ value={item.name}+ checked={item.show}+ onChange={() => onChange && onChange(item)}+ ></Checkbox>+ <span>{`${localeService.t(+ functionDisplayNames?.[item.name] || item.name+ )}: ${formatNumber(item.value)}`}</span>+ </a>+ ))}+ </div>+ }+ >+ <div className={styles.statisticMore}>+ <MoreSingle />+ </div>+ </Dropdown>+ </div>+ )+ );+};diff --git a/packages/ui-plugin-sheets/src/views/status-bar/index.module.less b/packages/ui-plugin-sheets/src/views/status-bar/index.module.lessnew file mode 100644index 0000000000..240e6c1f2c--- /dev/null+++ b/packages/ui-plugin-sheets/src/views/status-bar/index.module.less@@ -0,0 +1,80 @@+@statistic-menu-value-width: 55px;++.status-bar {+ display: flex;+ align-items: center;+ max-width: 332px;++ &.single-mode {+ max-width: 136px;+ }+}++.statistic {+ &-list {+ display: flex;+ }++ &-list-two-row {+ flex-direction: column;+ }++ &-list-two-row &-list-row {+ display: flex;+ flex-direction: row;+ }++ &-list-two-row &-item{+ font-size: 11px;+ line-height: 140%;+ }++ &-item {+ color: rgb(var(--grey-600));+ text-align: center;+ font-size: 12px;+ font-style: normal;+ font-weight: 400;+ line-height: 20px; /* 181.818% */+ margin-right: 8px;+ max-width: 96px;+ display: flex;+ justify-content: start;+ cursor: default;+ }++ &-picker {+ width: 196px;+ padding: var(--padding-base);+ font-size: var(--font-size-xs);+ background-color: rgb(var(--color-white));+ border: 1px solid rgb(var(--border-color));+ border-radius: var(--border-radius-lg);+ box-shadow: var(--box-shadow-lg);+ box-sizing: border-box;+ display: grid;+ align-items: center;+ gap: var(--margin-sm);+ }++ &-picker-item {+ display: flex;+ align-items: center;+ justify-content: start;+ }++ &-more {+ width: 24px;+ height: 24px;+ font-size: 12px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 4px;+ transform: rotate(90deg);++ &:hover {+ background: rgb(var(--grey-300, #E8E8E8));+ }+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex eb61586dce..1640d9d534 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1231,6 +1231,9 @@ importers:'@wendellhu/redi':specifier: ^0.12.11version: 0.12.11+ clsx:+ specifier: ^2.0.0+ version: 2.0.0react:specifier: ^18.2.0version: 18.2.0