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(sheet): fix summary performance (#3517)

VicKun0ab07d946f04
diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.ts
index a08f115f61..c765dcc2f1 100644
--- a/packages/core/src/shared/index.ts
+++ b/packages/core/src/shared/index.ts
@@ -34,7 +34,7 @@ export { LRUHelper, LRUMap } from './lru/lru-map';
export { numfmt } from './numfmt';
export * from './object-matrix';
export { queryObjectMatrix } from './object-matrix-query';
-export { moveRangeByOffset } from './range';
+export { moveRangeByOffset, splitIntoGrid } from './range';
export * from './rectangle';
export { RefAlias } from './ref-alias';
export * from './row-col-iter';
diff --git a/packages/core/src/shared/rectangle.ts b/packages/core/src/shared/rectangle.ts
index 5928c1dabf..3ba26097c6 100644
--- a/packages/core/src/shared/rectangle.ts
+++ b/packages/core/src/shared/rectangle.ts
@@ -270,6 +270,12 @@ export class Rectangle {
endColumn: range.endColumn + offsetX,
});
+ /**
+ * Subtract range2 from range1, the result is is horizontal first then vertical
+ * @param {IRange} range1 The source range
+ * @param {IRange} range2 The range to be subtracted
+ * @returns {IRange[]} Returns the array of ranges, which are the result not intersected with range1
+ */
static subtract(range1: IRange, range2: IRange): IRange[] {
// 如果没有交集,则返回 range1
if (
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index 8492e88ec9..5e3170ea76 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -15,6 +15,7 @@
*/
import {
+ CellValueType,
createInterceptorKey,
debounce,
Disposable,
@@ -25,31 +26,95 @@ import {
LifecycleStages,
ObjectMatrix,
OnLifecycle,
+ RANGE_TYPE,
+ splitIntoGrid,
toDisposable,
UniverInstanceType,
} from '@univerjs/core';
import {
- convertUnitDataToRuntime,
FormulaDataModel,
+ FUNCTION_NAMES_MATH,
+ FUNCTION_NAMES_STATISTICAL,
IFunctionService,
- RangeReferenceObject,
} from '@univerjs/engine-formula';
import {
INumfmtService,
SetRangeValuesMutation,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import type { ICommandInfo, IRange, ISelectionCell, Nullable, Workbook } from '@univerjs/core';
-import type { ArrayValueObject, BaseValueObject, ISheetData } from '@univerjs/engine-formula';
+import type { ICellData, ICommandInfo, IRange, ISelectionCell, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import type { ArrayValueObject, ISheetData } from '@univerjs/engine-formula';
+
import type {
ISelectionWithStyle,
} from '@univerjs/sheets';
-
import { IStatusBarService } from '../services/status-bar.service';
import type { IStatusBarServiceStatus } from '../services/status-bar.service';
export const STATUS_BAR_PERMISSION_CORRECT = createInterceptorKey<ArrayValueObject[], ArrayValueObject[]>('statusBarPermissionCorrect');
+class CalculateValueSet {
+ private _sum: number = 0;
+ private _count: number = 0;
+ private _countNumber: number = 0;
+ private _min: number = Number.POSITIVE_INFINITY;
+ private _max: number = Number.NEGATIVE_INFINITY;
+
+ add(value: Nullable<ICellData>) {
+ const v = value?.v;
+ const t = value?.t;
+ if (v !== undefined && v !== null) {
+ if (typeof v === 'number' && t !== CellValueType.STRING) {
+ this._sum += v;
+ this._countNumber++;
+ this._min = Math.min(this._min, v);
+ this._max = Math.max(this._max, v);
+ }
+ this._count++;
+ }
+ }
+
+ getResults() {
+ return {
+ sum: this._sum,
+ count: this._countNumber,
+ // the countA in formula is the count of all values
+ countA: this._count,
+ min: this._min,
+ max: this._max,
+ };
+ }
+}
+function calculateValues(valueSet: CalculateValueSet) {
+ const { sum, count, countA, min, max } = valueSet.getResults();
+ return [
+ {
+ func: FUNCTION_NAMES_STATISTICAL.MAX,
+ value: max,
+ },
+ {
+ func: FUNCTION_NAMES_STATISTICAL.MIN,
+ value: min,
+ },
+ {
+ func: FUNCTION_NAMES_MATH.SUM,
+ value: sum,
+ },
+ {
+ func: FUNCTION_NAMES_STATISTICAL.COUNTA,
+ value: countA,
+ },
+ {
+ func: FUNCTION_NAMES_STATISTICAL.COUNT,
+ value: count,
+ },
+ {
+ func: FUNCTION_NAMES_STATISTICAL.AVERAGE,
+ value: sum / count,
+ },
+ ];
+}
+
@OnLifecycle(LifecycleStages.Ready, StatusBarController)
export class StatusBarController extends Disposable {
private _calculateTimeout: number | NodeJS.Timeout = -1;
@@ -119,6 +184,41 @@ export class StatusBarController extends Disposable {
this._statusBarService.setState(null);
}
+ getRangeStartEndInfo(range: IRange, sheet: Worksheet): IRange {
+ if (range.rangeType === RANGE_TYPE.ALL) {
+ return {
+ startRow: 0,
+ startColumn: 0,
+ endRow: sheet.getRowCount() - 1,
+ endColumn: sheet.getColumnCount() - 1,
+ };
+ }
+ if (range.rangeType === RANGE_TYPE.COLUMN) {
+ return {
+ startRow: 0,
+ startColumn: range.startColumn,
+ endRow: sheet.getRowCount() - 1,
+ endColumn: range.endColumn,
+
+ };
+ }
+ if (range.rangeType === RANGE_TYPE.ROW) {
+ return {
+ startRow: range.startRow,
+ startColumn: 0,
+ endRow: range.endRow,
+ endColumn: sheet.getColumnCount() - 1,
+ };
+ }
+ return {
+ startRow: range.startRow,
+ startColumn: range.startColumn,
+ endRow: range.endRow,
+ endColumn: range.endColumn,
+ };
+ }
+
+ // eslint-disable-next-line max-lines-per-function
private _calculateSelection(selections: IRange[], primary: Nullable<ISelectionCell>) {
const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
if (!workbook) {
@@ -132,7 +232,6 @@ export class StatusBarController extends Disposable {
}
const sheetData: ISheetData = {};
- const arrayFormulaMatrixCell = this._formulaDataModel.getArrayFormulaCellData();
this._univerInstanceService
.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!
@@ -149,15 +248,6 @@ export class StatusBarController extends Disposable {
});
if (selections?.length) {
- if (selections.length === 1) {
- const selection = selections[0];
- const { startRow: start, endRow: end, startColumn: startCol, endColumn: endCol } = selection;
- const rowCount = end - start + 1;
- const columnCount = endCol - startCol + 1;
- if (rowCount * columnCount > 1000000) {
- return this._clearResult();
- }
- }
const realSelections: IRange[] = [];
selections.forEach((selection) => {
const { startRow: start, endRow: end } = selection;
@@ -178,41 +268,21 @@ export class StatusBarController extends Disposable {
realSelections.push({ ...selection, startRow: prev, endRow: end });
}
});
- const refs = realSelections.map((s) => new RangeReferenceObject(s, sheetId, unitId));
- refs.forEach((ref) => {
- ref.setUnitData({
- [unitId]: sheetData,
- });
- arrayFormulaMatrixCell && ref.setArrayFormulaCellData(convertUnitDataToRuntime(arrayFormulaMatrixCell));
- });
-
- const functions = this._statusBarService.getFunctions();
-
- let arrayValue = refs.map((ref) => {
- return ref.toArrayValueObject(false);
- });
- const correctArrayValue = this.interceptor.fetchThroughInterceptors(STATUS_BAR_PERMISSION_CORRECT)(arrayValue, arrayValue);
- if (correctArrayValue) {
- arrayValue = correctArrayValue;
- }
-
- const calcResult = functions.map((f) => {
- const executor = this._functionService.getExecutor(f.func);
- if (!executor) {
- return undefined;
+ const noDuplicate = splitIntoGrid(realSelections);
+ // const matrix = sheet.getCellMatrix();
+ const calculateValueSet = new CalculateValueSet();
+ for (const range of noDuplicate) {
+ const { startRow, startColumn, endColumn, endRow } = this.getRangeStartEndInfo(range, sheet);
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ const value = sheet.getCell(r, c);
+ calculateValueSet.add(value);
+ }
}
+ }
- const res = executor?.calculate(...arrayValue) as BaseValueObject;
- const value = res?.getValue();
- if (!value) {
- return undefined;
- }
- return {
- func: f.func,
- value,
- };
- });
+ const calcResult = calculateValues(calculateValueSet);
if (calcResult.every((r) => r === undefined)) {
return;
}
@@ -232,3 +302,4 @@ export class StatusBarController extends Disposable {
}
}
}
+
diff --git a/packages/sheets-ui/src/controllers/utils/range-tools.ts b/packages/sheets-ui/src/controllers/utils/range-tools.ts
index 83a5749d45..dce6a4bcae 100644
--- a/packages/sheets-ui/src/controllers/utils/range-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/range-tools.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IAccessor, ICellData, IObjectMatrixPrimitiveType, IRange, Workbook } from '@univerjs/core';
import { IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';
+import type { IAccessor, ICellData, IObjectMatrixPrimitiveType, IRange, Workbook } from '@univerjs/core';
export interface IDiscreteRange {
rows: number[];
diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
index 8f9150a616..615bc8e417 100644
--- a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
@@ -14,6 +14,10 @@
* limitations under the License.
*/
+import { createIdentifier, Disposable, InterceptorManager, makeCellToSelection, RANGE_TYPE } from '@univerjs/core';
+import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
+import { getNormalSelectionStyle as getDefaultNormalSelectionStyle, transformCellDataToSelectionData } from '@univerjs/sheets';
+import { BehaviorSubject, Subject } from 'rxjs';
import type {
IDisposable,
IFreeze,
@@ -27,22 +31,18 @@ import type {
Nullable,
ThemeService,
} from '@univerjs/core';
-import { createIdentifier, Disposable, InterceptorManager, makeCellToSelection, RANGE_TYPE } from '@univerjs/core';
import type { IMouseEvent, IPointerEvent, IRenderModule, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
-import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import type { ISelectionStyle, ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
-import { getNormalSelectionStyle as getDefaultNormalSelectionStyle, transformCellDataToSelectionData } from '@univerjs/sheets';
import type { IShortcutService } from '@univerjs/ui';
import type { Observable, Subscription } from 'rxjs';
-import { BehaviorSubject, Subject } from 'rxjs';
-import type { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
import { SHEET_COMPONENT_SELECTION_LAYER_INDEX } from '../../common/keys';
import { RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './const';
+import { SelectionLayer } from './selection-layer';
import { SelectionControl } from './selection-shape';
import { SelectionShapeExtension } from './selection-shape-extension';
import { attachPrimaryWithCoord, attachSelectionWithCoord } from './util';
-import { SelectionLayer } from './selection-layer';
+import type { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
export interface IControlFillConfig {
oldRange: IRange;
@@ -283,6 +283,10 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
}
+ refreshSelectionMoveEnd(): void {
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ }
+
protected _changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene, viewport?: Viewport): void {
this._skeleton = skeleton;
this._scene = scene;
diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.ts
index d2acbda909..e6a5458060 100644
--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts
@@ -14,21 +14,21 @@
* limitations under the License.
*/
-import type { IDisposable, Nullable, Workbook } from '@univerjs/core';
import { ICommandService, IContextService, ILogService, Inject, Injector, RANGE_TYPE, ThemeService, toDisposable } from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import type { ISelectionWithCoordAndStyle, ISetSelectionsOperationParams, WorkbookSelections } from '@univerjs/sheets';
import { convertSelectionDataToRange, DISABLE_NORMAL_SELECTIONS, SelectionMoveType, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IShortcutService } from '@univerjs/ui';
import { distinctUntilChanged, startWith } from 'rxjs';
-import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import type { ISheetObjectParam } from '../../controllers/utils/component-tools';
+import type { IDisposable, Nullable, Workbook } from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { ISelectionWithCoordAndStyle, ISetSelectionsOperationParams, WorkbookSelections } from '@univerjs/sheets';
import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';
import { isThisColSelected, isThisRowSelected } from '../../controllers/utils/selections-tools';
+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+import { BaseSelectionRenderService, getAllSelection, getTopLeftSelection } from './base-selection-render.service';
import { attachSelectionWithCoord } from './util';
-import { BaseSelectionRenderService, getAllSelection, getTopLeftSelection } from './base-selection-render.service';
+import type { ISheetObjectParam } from '../../controllers/utils/component-tools';
/**
* This services controls rendering of normal selections in a render unit.
@@ -123,7 +123,7 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
const selectionWithStyle = getAllSelection(skeleton);
const selectionData = attachSelectionWithCoord(selectionWithStyle, skeleton);
this._addSelectionControlBySelectionData(selectionData);
- this.refreshSelectionMoveStart();
+ this.refreshSelectionMoveEnd();
if (evt.button !== 2) {
state.stopPropagation();