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.

feat(sheets-formula): support quick sum method (#5214)

Evanf53819050f99
diff --git a/packages/core/src/sheets/util.ts b/packages/core/src/sheets/util.ts
index 69a75d6a99..b831ea8053 100644
--- a/packages/core/src/sheets/util.ts
+++ b/packages/core/src/sheets/util.ts
@@ -15,14 +15,16 @@
*/
import type { Nullable } from '../shared';
+import type { CellValueType, TextDirection } from '../types/enum';
+import type { IDocumentData, IPaddingData, IStyleBase, IStyleData, ITextRotation, ITextStyle } from '../types/interfaces';
import type { IRange, IUnitRange } from './typedef';
import { DEFAULT_EMPTY_DOCUMENT_VALUE } from '../common/const';
import { BuildTextUtils, DocumentDataModel } from '../docs';
import { TextX } from '../docs/data-model/text-x/text-x';
import { convertTextRotation } from '../docs/data-model/utils';
import { Rectangle } from '../shared';
-import { type CellValueType, HorizontalAlign, type TextDirection, VerticalAlign, WrapStrategy } from '../types/enum';
-import { CustomRangeType, type IDocumentData, type IPaddingData, type IStyleBase, type IStyleData, type ITextRotation, type ITextStyle } from '../types/interfaces';
+import { HorizontalAlign, VerticalAlign, WrapStrategy } from '../types/enum';
+import { CustomRangeType } from '../types/interfaces';
export interface IFontLocale {
fontList: string[];
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index 3df40248db..059b10e56d 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -66,6 +66,7 @@ const DEFAULT_CELL_DOCUMENT_MODEL_OPTION = {
displayRawFormula: false,
ignoreTextRotation: false,
};
+
/**
* The model of a Worksheet.
*/
diff --git a/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
index cb158cd7de..0c6960c049 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
@@ -40,6 +40,7 @@ import {
promptSelectionShortcutItemShift,
singleEditorPromptSelectionShortcutItem,
} from './shortcuts/prompt.shortcut';
+import { QuickSumShortcut } from './shortcuts/quick-sum.shortcut';
export class FormulaUIController extends Disposable {
constructor(
@@ -87,6 +88,7 @@ export class FormulaUIController extends Disposable {
...promptSelectionShortcutItemCtrl(),
...promptSelectionShortcutItemCtrlAndShift(),
...singleEditorPromptSelectionShortcutItem(),
+ QuickSumShortcut,
ChangeRefToAbsoluteShortcut,
].forEach((item) => {
this.disposeWithMe(this._shortcutService.registerShortcut(item));
diff --git a/packages/sheets-formula-ui/src/controllers/shortcuts/quick-sum.shortcut.ts b/packages/sheets-formula-ui/src/controllers/shortcuts/quick-sum.shortcut.ts
new file mode 100644
index 0000000000..55bb48f860
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/shortcuts/quick-sum.shortcut.ts
@@ -0,0 +1,29 @@
+/**
+ * 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 { IShortcutItem } from '@univerjs/ui';
+import { QuickSumCommand } from '@univerjs/sheets-formula';
+import { whenSheetEditorFocused } from '@univerjs/sheets-ui';
+import { KeyCode, MetaKeys } from '@univerjs/ui';
+
+export const QuickSumShortcut: IShortcutItem = {
+ id: QuickSumCommand.id,
+ binding: MetaKeys.ALT | KeyCode.EQUAL,
+ preconditions: whenSheetEditorFocused,
+ mac: MetaKeys.CTRL_COMMAND | MetaKeys.ALT | KeyCode.EQUAL,
+ description: 'shortcut.sheets-formula-ui.quick-sum',
+ group: '4_sheet-edit',
+};
diff --git a/packages/sheets-formula-ui/src/locale/en-US.ts b/packages/sheets-formula-ui/src/locale/en-US.ts
index 63aecbc274..7b126a629d 100644
--- a/packages/sheets-formula-ui/src/locale/en-US.ts
+++ b/packages/sheets-formula-ui/src/locale/en-US.ts
@@ -31,6 +31,11 @@ import univer from './function-list/univer/en-US';
import web from './function-list/web/en-US';
export default {
+ shortcut: {
+ 'sheets-formula-ui': {
+ 'quick-sum': 'Quick Sum',
+ },
+ },
formula: {
insert: {
tooltip: 'Functions',
diff --git a/packages/sheets-formula-ui/src/locale/fa-IR.ts b/packages/sheets-formula-ui/src/locale/fa-IR.ts
index 189ce3b9c7..568eee9504 100644
--- a/packages/sheets-formula-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-formula-ui/src/locale/fa-IR.ts
@@ -31,6 +31,11 @@ import univer from './function-list/univer/en-US';
import web from './function-list/web/en-US';
export default {
+ shortcut: {
+ 'sheets-formula-ui': {
+ 'quick-sum': 'جمع سریع',
+ },
+ },
formula: {
insert: {
tooltip: 'توابع',
diff --git a/packages/sheets-formula-ui/src/locale/fr-FR.ts b/packages/sheets-formula-ui/src/locale/fr-FR.ts
index 17b55969b5..ba19142bfe 100644
--- a/packages/sheets-formula-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-formula-ui/src/locale/fr-FR.ts
@@ -31,6 +31,11 @@ import univer from './function-list/univer/en-US';
import web from './function-list/web/en-US';
export default {
+ shortcut: {
+ 'sheets-formula-ui': {
+ 'quick-sum': 'Somme rapide',
+ },
+ },
formula: {
insert: {
tooltip: 'Fonctions',
diff --git a/packages/sheets-formula-ui/src/locale/ru-RU.ts b/packages/sheets-formula-ui/src/locale/ru-RU.ts
index 730b0300eb..710ab542af 100644
--- a/packages/sheets-formula-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-formula-ui/src/locale/ru-RU.ts
@@ -31,6 +31,11 @@ import univer from './function-list/univer/ru-RU';
import web from './function-list/web/ru-RU';
export default {
+ shortcut: {
+ 'sheets-formula-ui': {
+ 'quick-sum': 'Быстрая сумма',
+ },
+ },
formula: {
insert: {
tooltip: 'Функции',
diff --git a/packages/sheets-formula-ui/src/locale/vi-VN.ts b/packages/sheets-formula-ui/src/locale/vi-VN.ts
index e651b4285b..f0f4719fa1 100644
--- a/packages/sheets-formula-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-formula-ui/src/locale/vi-VN.ts
@@ -31,6 +31,11 @@ import univer from './function-list/univer/vi-VN';
import web from './function-list/web/vi-VN';
export default {
+ shortcut: {
+ 'sheets-formula-ui': {
+ 'quick-sum': 'Tổng nhanh',
+ },
+ },
formula: {
insert: {
tooltip: 'Hàm',
diff --git a/packages/sheets-formula-ui/src/locale/zh-CN.ts b/packages/sheets-formula-ui/src/locale/zh-CN.ts
index 531c22ee4d..6d7c19bf57 100644
--- a/packages/sheets-formula-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-formula-ui/src/locale/zh-CN.ts
@@ -31,6 +31,11 @@ import univer from './function-list/univer/zh-CN';
import web from './function-list/web/zh-CN';
export default {
+ shortcut: {
+ 'sheets-formula-ui': {
+ 'quick-sum': '快速求和',
+ },
+ },
formula: {
insert: {
tooltip: '函数',
diff --git a/packages/sheets-formula-ui/src/locale/zh-TW.ts b/packages/sheets-formula-ui/src/locale/zh-TW.ts
index 2fdd689fa4..b9fc78f1df 100644
--- a/packages/sheets-formula-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-formula-ui/src/locale/zh-TW.ts
@@ -31,6 +31,11 @@ import univer from './function-list/univer/zh-TW';
import web from './function-list/web/zh-TW';
export default {
+ shortcut: {
+ 'sheets-formula-ui': {
+ 'quick-sum': '快速求和',
+ },
+ },
formula: {
insert: {
tooltip: '函數',
diff --git a/packages/sheets-formula/src/commands/commands/quick-sum.command.ts b/packages/sheets-formula/src/commands/commands/quick-sum.command.ts
new file mode 100644
index 0000000000..1c9cdf940d
--- /dev/null
+++ b/packages/sheets-formula/src/commands/commands/quick-sum.command.ts
@@ -0,0 +1,119 @@
+/**
+ * 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 { IAccessor, ICellData, ICommand } from '@univerjs/core';
+import type { ISetRangeValuesCommandParams, ISetSelectionsOperationParams } from '@univerjs/sheets';
+import { CommandType, ICommandService, IUniverInstanceService, ObjectMatrix, Rectangle, sequenceExecuteAsync } from '@univerjs/core';
+import { serializeRange } from '@univerjs/engine-formula';
+import { alignToMergedCellsBorders, expandToContinuousRange, findFirstNonEmptyCell, getSheetCommandTarget, SetRangeValuesCommand, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
+
+/**
+ * Tries to insert =SUM formulas in selection regions.
+ */
+export const QuickSumCommand: ICommand = {
+ id: 'sheets-formula.command.quick-sum',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor) => {
+ const selectionsService = accessor.get(SheetsSelectionsService);
+ const currentSelection = selectionsService.getCurrentLastSelection();
+ if (!currentSelection) return false;
+
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const target = getSheetCommandTarget(univerInstanceService);
+ if (!target) return false;
+
+ const range = currentSelection.range;
+ const { worksheet } = target;
+ let firstCell = findFirstNonEmptyCell(range, worksheet);
+ if (!firstCell) return false;
+
+ firstCell = alignToMergedCellsBorders(firstCell, worksheet);
+ const targetRange = expandToContinuousRange({
+ startRow: firstCell.startRow,
+ startColumn: firstCell.startColumn,
+ endRow: range.endRow,
+ endColumn: range.endColumn,
+ }, { left: true, right: true, up: true, down: true }, worksheet);
+
+ const setValueMatrix = new ObjectMatrix<ICellData>();
+
+ const lastRow = alignToMergedCellsBorders({
+ startRow: targetRange.endRow,
+ endRow: targetRange.endRow,
+ startColumn: targetRange.startColumn,
+ endColumn: targetRange.endColumn,
+ }, worksheet);
+ if (!Rectangle.equals(lastRow, targetRange)) {
+ for (const cell of worksheet.iterateByColumn(lastRow)) {
+ if (!cell.value || !worksheet.cellHasValue(cell.value)) {
+ setValueMatrix.setValue(cell.row, cell.col, {
+ f: `=SUM(${serializeRange({
+ startColumn: cell.col,
+ endColumn: cell.col,
+ startRow: targetRange.startRow,
+ endRow: cell.row - 1,
+ })})`,
+ });
+ }
+ }
+ }
+
+ const lastColumn = alignToMergedCellsBorders({
+ startRow: targetRange.startRow,
+ startColumn: targetRange.endColumn,
+ endRow: targetRange.endRow,
+ endColumn: targetRange.endColumn,
+ }, worksheet);
+ if (!Rectangle.equals(lastColumn, targetRange)) {
+ for (const cell of worksheet.iterateByRow(lastColumn)) {
+ if (!cell.value || !worksheet.cellHasValue(cell.value)) {
+ setValueMatrix.setValue(cell.row, cell.col, {
+ f: `=SUM(${serializeRange({
+ startColumn: targetRange.startColumn,
+ endColumn: cell.col - 1,
+ startRow: cell.row,
+ endRow: cell.row,
+ })})`,
+ });
+ }
+ }
+ }
+
+ const commandService = accessor.get(ICommandService);
+
+ return (await sequenceExecuteAsync([
+ {
+ id: SetRangeValuesCommand.id,
+ params: {
+ range: targetRange,
+ value: setValueMatrix.getMatrix(),
+ } as ISetRangeValuesCommandParams,
+ },
+ {
+ id: SetSelectionsOperation.id,
+ params: {
+ unitId: target.unitId,
+ subUnitId: target.subUnitId,
+ selections: [{
+ range: targetRange,
+ primary: Rectangle.contains(targetRange, currentSelection.primary) ? currentSelection.primary : { ...firstCell, actualRow: firstCell.startRow, actualColumn: firstCell.startColumn },
+ style: null,
+ }],
+ } as ISetSelectionsOperationParams,
+ },
+ ], commandService)).result;
+ },
+};
diff --git a/packages/sheets-formula/src/controllers/formula.controller.ts b/packages/sheets-formula/src/controllers/formula.controller.ts
index 0cedf14988..ad6860f05e 100644
--- a/packages/sheets-formula/src/controllers/formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula.controller.ts
@@ -16,6 +16,7 @@
import { Disposable, ICommandService } from '@univerjs/core';
import { InsertFunctionCommand } from '../commands/commands/insert-function.command';
+import { QuickSumCommand } from '../commands/commands/quick-sum.command';
import { OtherFormulaMarkDirty } from '../commands/mutations/formula.mutation';
export class FormulaController extends Disposable {
@@ -26,6 +27,7 @@ export class FormulaController extends Disposable {
[
InsertFunctionCommand,
+ QuickSumCommand,
OtherFormulaMarkDirty,
].forEach((c) => this._commandService.registerCommand(c));
}
diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.ts
index 6ea568599e..e0c1d466fd 100644
--- a/packages/sheets-formula/src/index.ts
+++ b/packages/sheets-formula/src/index.ts
@@ -14,15 +14,19 @@
* limitations under the License.
*/
+// #region - all commands
+
export { type IInsertFunction, type IInsertFunctionCommandParams, InsertFunctionCommand } from './commands/commands/insert-function.command';
+export { QuickSumCommand } from './commands/commands/quick-sum.command';
export { OtherFormulaMarkDirty } from './commands/mutations/formula.mutation';
+
+// #endregion
+
export { UpdateDefinedNameController } from './controllers/update-defined-name.controller';
export { TriggerCalculationController } from './controllers/trigger-calculation.controller';
export { CalculationMode, type IUniverSheetsFormulaBaseConfig, PLUGIN_CONFIG_KEY_BASE } from './controllers/config.schema';
export type { IRegisterAsyncFunction, IRegisterFunction, ISingleFunctionRegisterParams } from './services/register-function.service';
export { calculateFormula } from './util/calculate';
-// #region - all commands
-
export { UpdateFormulaController } from './controllers/update-formula.controller';
export { DescriptionService, IDescriptionService, type ISearchItem } from './services/description.service';
export type { IFormulaInfo, IOtherFormulaResult } from './services/formula-common';
@@ -33,5 +37,3 @@ export { IRegisterFunctionService } from './services/register-function.service';
export { RegisterOtherFormulaService } from './services/register-other-formula.service';
export { IRemoteRegisterFunctionService, RemoteRegisterFunctionService } from './services/remote/remote-register-function.service';
export { UniverRemoteSheetsFormulaPlugin, UniverSheetsFormulaPlugin } from './plugin';
-
-// #endregion
diff --git a/packages/sheets/src/basics/expand-range.ts b/packages/sheets/src/basics/expand-range.ts
index 0d5bb7204c..e8894dd335 100644
--- a/packages/sheets/src/basics/expand-range.ts
+++ b/packages/sheets/src/basics/expand-range.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { createRowColIter, ObjectMatrix, Rectangle } from '@univerjs/core';
import type { ICellData, IRange, Worksheet } from '@univerjs/core';
+import { createRowColIter, ObjectMatrix, Rectangle } from '@univerjs/core';
export interface IExpandParams {
left?: boolean;
diff --git a/packages/sheets/src/basics/utils.ts b/packages/sheets/src/basics/utils.ts
index 7948908698..a4c19be135 100644
--- a/packages/sheets/src/basics/utils.ts
+++ b/packages/sheets/src/basics/utils.ts
@@ -15,7 +15,6 @@
*/
import type { IAccessor, ICellData, IObjectMatrixPrimitiveType, IRange, Nullable, UniverInstanceService, Workbook, Worksheet } from '@univerjs/core';
-import type { IExpandParams } from '../commands/commands/utils/selection-utils';
import type { IDiscreteRange } from './interfaces';
import { IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';
@@ -53,113 +52,26 @@ export const createUniqueKey = (initValue = 0) => {
};
};
-function cellHasValue(cell: ICellData | undefined): boolean {
+function cellHasValue(cell: Nullable<ICellData>): boolean {
if (cell === undefined || cell === null) {
return false;
}
return (cell.v !== undefined && cell.v !== null && cell.v !== '') || cell.p !== undefined;
}
-// eslint-disable-next-line max-lines-per-function
-export function expandToContinuousRange(startRange: IRange, directions: IExpandParams, worksheet: Worksheet): IRange {
- const { left, right, up, down } = directions;
- const maxRow = worksheet.getMaxRows();
- const maxColumn = worksheet.getMaxColumns();
-
- let changed = true;
- const destRange: IRange = { ...startRange }; // startRange should not be used below
-
- const allMatrix = worksheet.getMatrixWithMergedCells(0, 0, maxRow - 1, maxColumn - 1);
- while (changed) {
- changed = false;
-
- if (up && destRange.startRow !== 0) {
- // see if there are value in the upper row of contents
- // set `changed` to true if `startRow` really changes
- const destRow = destRange.startRow - 1; // it may decrease if there are merged cell
-
- const checkRange = {
- startRow: destRow,
- startColumn: destRange.startColumn,
- endRow: destRow,
- endColumn: destRange.endColumn,
- };
- for (let col = checkRange.startColumn; col <= checkRange.endColumn; col++) {
- const cell = allMatrix.getValue(checkRange.startRow, col)!;
- if (cellHasValue(cell)) {
- destRange.startRow = Math.min(checkRange.startRow, destRange.startRow);
- destRange.startColumn = Math.min(col, destRange.startColumn);
- destRange.endColumn = Math.max(col, destRange.endColumn);
- changed = true;
- }
- }
- }
-
- if (down && destRange.endRow !== maxRow - 1) {
- const destRow = destRange.endRow + 1;
- const checkRange = {
- startRow: destRow,
- startColumn: destRange.startColumn,
- endRow: destRow,
- endColumn: destRange.endColumn,
- };
- for (let col = checkRange.startColumn; col <= checkRange.endColumn; col++) {
- const cellValue = allMatrix.getValue(checkRange.startRow, col)!;
- if (cellHasValue(cellValue)) {
- destRange.endRow = Math.max(checkRange.endRow, destRange.endRow);
- destRange.endRow = Math.max(
- checkRange.endRow + (cellValue.rowSpan !== undefined ? cellValue.rowSpan - 1 : 0),
- destRange.endRow
- );
- destRange.startColumn = Math.min(col, destRange.startColumn);
- destRange.endColumn = Math.max(col, destRange.endColumn);
- changed = true;
- }
- }
- }
-
- if (left && destRange.startColumn !== 0) {
- const destCol = destRange.startColumn - 1;
- const checkRange = {
- startRow: destRange.startRow,
- startColumn: destCol,
- endRow: destRange.endRow,
- endColumn: destCol,
- };
- for (let row = checkRange.startRow; row <= checkRange.endRow; row++) {
- const cell = allMatrix.getValue(row, checkRange.startColumn)!;
- if (cellHasValue(cell)) {
- destRange.startColumn = Math.min(checkRange.startColumn, destRange.startColumn);
- destRange.startRow = Math.min(row, destRange.startRow);
- destRange.endRow = Math.max(row, destRange.endRow);
- changed = true;
- }
- }
- }
-
- if (right && destRange.endColumn !== maxColumn - 1) {
- const destCol = destRange.endColumn + 1;
- const checkRange = {
- startRow: destRange.startRow,
- startColumn: destCol,
- endRow: destRange.endRow,
- endColumn: destCol,
- };
- for (let row = checkRange.startRow; row <= checkRange.endRow; row++) {
- const cellValue = allMatrix.getValue(row, checkRange.endColumn)!;
- if (cellHasValue(cellValue)) {
- destRange.endColumn = Math.max(
- checkRange.endColumn + (cellValue.colSpan !== undefined ? cellValue.colSpan - 1 : 0),
- destRange.endColumn
- );
- changed = true;
- }
+export function findFirstNonEmptyCell(range: IRange, worksheet: Worksheet): IRange | null {
+ for (let row = range.startRow; row <= range.endRow; row++) {
+ for (let col = range.startColumn; col <= range.endColumn; col++) {
+ const cell = worksheet.getCell(row, col);
+ if (cellHasValue(cell)) {
+ return { startRow: row, startColumn: col, endRow: row, endColumn: col };
}
}
}
- return destRange;
+ return null;
}
+
/**
* Generate cellValue from range and set null
* @param range
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index fc40c719ab..a2a52b6176 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -109,6 +109,7 @@ export { AddMergeRedoSelectionsOperationFactory, AddMergeUndoSelectionsOperation
export type { FormatType } from './services/numfmt/type';
export { expandToContinuousRange } from './basics/expand-range';
+export { findFirstNonEmptyCell } from './basics/utils';
export { SplitDelimiterEnum, splitRangeText } from './basics/split-range-text';
export { getNextPrimaryCell } from './services/selections/move-active-cell-util';
export { checkCellValueType } from './basics/cell-type';