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(formula): formula calculate, array formula, register function (#623)

Dushusir38d4d4469caa
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 633beece5b..6d256c628f 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -56,6 +56,7 @@
"redi",
"Sider",
"SUMIF",
+ "SUMIFS",
"Tahoma",
"tinycolor",
"undoredo",
diff --git a/packages/core/src/shared/object-array.ts b/packages/core/src/shared/object-array.ts
index 36af4d538a..f1da919492 100644
--- a/packages/core/src/shared/object-array.ts
+++ b/packages/core/src/shared/object-array.ts
@@ -513,7 +513,13 @@ export class ObjectArray<T> {
// move all items after toIndex in backward order
for (let i = fromIndex - 1; i >= toIndex; i--) {
- array[i + count] = array[i];
+ const item = array[i];
+ array[i + count] = item;
+
+ // Prevent undefined, otherwise the forValue loop will report an error
+ if (item == null) {
+ delete array[i + count];
+ }
}
// insert cached items to toIndex
@@ -533,7 +539,13 @@ export class ObjectArray<T> {
// move all items after toIndex in forward order
for (let i = fromIndex + count; i < toIndex; i++) {
- array[i - count] = array[i];
+ const item = array[i];
+ array[i - count] = item;
+
+ // Prevent undefined, otherwise the forValue loop will report an error
+ if (item == null) {
+ delete array[i - count];
+ }
}
// insert cached items to toIndex
diff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.ts
index 388f4e391e..f6c7f49c26 100644
--- a/packages/core/src/shared/object-matrix.ts
+++ b/packages/core/src/shared/object-matrix.ts
@@ -410,6 +410,15 @@ export class ObjectMatrix<T> {
return ranges;
}
+ merge(newObject: ObjectMatrix<T>) {
+ this.forValue((row, column) => {
+ const cellValue = newObject.getValue(row, column);
+ if (cellValue != null) {
+ this.setValue(row, column, cellValue);
+ }
+ });
+ }
+
private _setOriginValue(matrix: ObjectMatrixPrimitiveType<T> = {}) {
this._matrix = matrix;
this._option = new ObjectArray<ObjectArrayPrimitiveType<T>>(matrix);
diff --git a/packages/core/src/types/interfaces/i-cell-data.ts b/packages/core/src/types/interfaces/i-cell-data.ts
index 1e3d0818da..abc9da27c9 100644
--- a/packages/core/src/types/interfaces/i-cell-data.ts
+++ b/packages/core/src/types/interfaces/i-cell-data.ts
@@ -28,7 +28,7 @@ export interface ICellData {
*/
m?: Nullable<string>; // formatted value
// Usually the type is automatically determined based on the data, or the user directly specifies
- t?: Nullable<CellValueType>; // 0 string, 1 number, 2 boolean, 3 force string, green icon, set null for cell clear all
+ t?: Nullable<CellValueType>; // 1 string, 2 number, 3 boolean, 4 force string, green icon, set null for cell clear all
f?: Nullable<string>; // formula '=SUM(1)'
si?: Nullable<string>; // formula id
/**
@@ -62,7 +62,8 @@ export function isICellData(value: any): value is ICellData {
((value as ICellData).s !== undefined ||
(value as ICellData).p !== undefined ||
(value as ICellData).v !== undefined)) ||
- (value as ICellData).f !== undefined
+ (value as ICellData).f !== undefined ||
+ (value as ICellData).si !== undefined
);
}
@@ -80,3 +81,25 @@ export function getCellValueType(cell: ICellData) {
return CellValueType.BOOLEAN;
}
}
+
+export function isNullCell(cell: Nullable<ICellData>) {
+ if (cell == null) {
+ return true;
+ }
+
+ const { v, f, si, p, s } = cell;
+
+ if (!(v == null || (typeof v === 'string' && v.length === 0))) {
+ return false;
+ }
+
+ if ((f != null && f.length > 0) || (si != null && si.length > 0)) {
+ return false;
+ }
+
+ if (p != null) {
+ return false;
+ }
+
+ return true;
+}
diff --git a/packages/engine-formula/package.json b/packages/engine-formula/package.json
index 2a7782d0ea..91332b0b24 100644
--- a/packages/engine-formula/package.json
+++ b/packages/engine-formula/package.json
@@ -46,7 +46,8 @@
},
"dependencies": {
"@univerjs/core": "workspace:*",
- "@wendellhu/redi": "^0.12.11"
+ "@wendellhu/redi": "^0.12.11",
+ "rxjs": "^7.8.1"
},
"devDependencies": {
"@vitest/coverage-istanbul": "^0.34.6",
diff --git a/packages/engine-formula/src/ast-node/reference-node.ts b/packages/engine-formula/src/ast-node/reference-node.ts
index 1dee1a0237..226740301f 100644
--- a/packages/engine-formula/src/ast-node/reference-node.ts
+++ b/packages/engine-formula/src/ast-node/reference-node.ts
@@ -42,10 +42,12 @@ export class ReferenceNode extends BaseAstNode {
this._referenceObject.setUnitData(currentConfigService.getUnitData());
this._referenceObject.setForcedSheetId(currentConfigService.getSheetNameMap());
+ this._referenceObject.setArrayFormulaCellData(currentConfigService.getArrayFormulaCellData());
- this._referenceObject.setDefaultSheetId(runtimeService.currentSheetId);
+ this._referenceObject.setDefaultSheetId(runtimeService.currentSubComponentId);
this._referenceObject.setDefaultUnitId(runtimeService.currentUnitId);
this._referenceObject.setRuntimeData(runtimeService.getUnitData());
+ this._referenceObject.setRuntimeArrayFormulaCellData(runtimeService.getRuntimeArrayFormulaCellData());
const { x, y } = this.getRefOffset();
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index 72ccc54e73..3a4d3e7196 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -3,18 +3,11 @@ import type {
ICellData,
IRange,
IUnitRange,
+ Nullable,
ObjectMatrix,
ObjectMatrixPrimitiveType,
} from '@univerjs/core';
-export interface ArrayFormulaDataType {
- [sheetId: string]: ObjectMatrix<IRange>;
-}
-
-export interface UnitArrayFormulaDataType {
- [unitId: string]: ArrayFormulaDataType;
-}
-
export const ERROR_VALUE_OBJECT_CLASS_TYPE = 'errorValueObject';
export const ASYNC_OBJECT_CLASS_TYPE = 'asyncObject';
@@ -51,18 +44,38 @@ export interface IUnitData {
[unitId: string]: ISheetData;
}
-export interface IRuntimeSheetData {
- [sheetId: string]: ObjectMatrix<ICellData>;
+export interface IRuntimeUnitDataType {
+ [unitId: string]: { [sheetId: string]: ObjectMatrix<ICellData> };
}
-export interface IRuntimeUnitDataType {
- [unitId: string]: IRuntimeSheetData;
+export interface IRuntimeOtherUnitDataType {
+ [unitId: string]: { [sheetId: string]: { [formulaId: string]: ICellData } };
}
export interface IUnitSheetNameMap {
[unitId: string]: { [sheetName: string]: string };
}
+export interface IDirtyUnitSheetNameMap {
+ [unitId: string]: { [sheetId: string]: Nullable<string> };
+}
+
+export interface IArrayFormulaRangeType {
+ [unitId: string]: { [sheetId: string]: ObjectMatrixPrimitiveType<IRange> };
+}
+
+export interface IArrayFormulaUnitCellType {
+ [unitId: string]: { [sheetId: string]: ObjectMatrixPrimitiveType<ICellData> };
+}
+
+export interface IFormulaData {
+ [unitId: string]: { [sheetId: string]: ObjectMatrixPrimitiveType<IFormulaDataItem> };
+}
+
+export interface IOtherFormulaData {
+ [unitId: string]: { [subComponentId: string]: { [formulaId: string]: IFormulaDataItem } };
+}
+
/**
* @f formulaString, the text string of the formula.
* @si The formula ID can be utilized in scenarios such as copy-pasting and drag-filling to convert formulas into references, eliminating the need for recreating the formulaString.
@@ -77,10 +90,6 @@ export interface IFormulaDataItem {
// sheetId: string;
}
-export interface IFormulaData {
- [unitId: string]: { [sheetId: string]: ObjectMatrixPrimitiveType<IFormulaDataItem> };
-}
-
export interface ISuperTable {
sheetId: string;
hasCustomTitle: BooleanNumber;
@@ -95,12 +104,17 @@ export enum TableOptionType {
TOTALS = '#Totals',
}
+export interface IUnitExcludedCell {
+ [unitId: string]: { [sheetId: string]: ObjectMatrix<boolean> };
+}
+
export interface IFormulaDatasetConfig {
- unitData: IUnitData;
formulaData: IFormulaData;
- sheetNameMap: IUnitSheetNameMap;
+ arrayFormulaCellData: IArrayFormulaUnitCellType;
forceCalculate: boolean;
dirtyRanges: IUnitRange[];
+ dirtyNameMap: IDirtyUnitSheetNameMap;
+ excludedCell?: IUnitExcludedCell;
}
export enum ConcatenateType {
diff --git a/packages/engine-formula/src/basics/dirty.ts b/packages/engine-formula/src/basics/dirty.ts
new file mode 100644
index 0000000000..83c2e4b5ad
--- /dev/null
+++ b/packages/engine-formula/src/basics/dirty.ts
@@ -0,0 +1,28 @@
+import type { IUnitRange } from '@univerjs/core';
+
+export function isInDirtyRange(
+ dirtyRanges: IUnitRange[],
+ unitId: string,
+ sheetId: string,
+ row: number,
+ column: number
+) {
+ for (let i = 0, len = dirtyRanges.length; i < len; i++) {
+ const dirtyRange = dirtyRanges[i];
+ if (unitId !== dirtyRange.unitId) {
+ continue;
+ }
+
+ if (sheetId !== dirtyRange.sheetId) {
+ continue;
+ }
+
+ const { startRow, startColumn, endRow, endColumn } = dirtyRange.range;
+
+ if (row >= startRow && row <= endRow && column >= startColumn && column <= endColumn) {
+ return true;
+ }
+ }
+
+ return false;
+}
diff --git a/packages/engine-formula/src/basics/object-class-type.ts b/packages/engine-formula/src/basics/object-class-type.ts
index 1d9d2d64c6..de836cb1a8 100644
--- a/packages/engine-formula/src/basics/object-class-type.ts
+++ b/packages/engine-formula/src/basics/object-class-type.ts
@@ -16,4 +16,8 @@ export class ObjectClassType extends Disposable {
isValueObject() {
return false;
}
+
+ isEqual(object: ObjectClassType) {
+ return false;
+ }
}
diff --git a/packages/engine-formula/src/basics/set-zero-time-out.ts b/packages/engine-formula/src/basics/set-zero-time-out.ts
new file mode 100644
index 0000000000..4304dec957
--- /dev/null
+++ b/packages/engine-formula/src/basics/set-zero-time-out.ts
@@ -0,0 +1,28 @@
+const timeouts: any[] = [];
+const messageName = 'zero-timeout-message';
+
+const globalObject = typeof self !== 'undefined' ? self : window;
+
+/**
+ * Maintain the form of setTimeout, only accept a single function parameter,
+ * and the delay is always 0.
+ * @param fn
+ */
+export function setZeroTimeout(fn: any) {
+ timeouts.push(fn);
+ globalObject.postMessage(messageName);
+}
+
+function handleMessage(event: MessageEvent) {
+ if (typeof self === 'undefined') {
+ globalObject.postMessage(messageName);
+ } else if (event.source === globalObject && event.data === messageName) {
+ event.stopPropagation();
+ if (timeouts.length > 0) {
+ const fn = timeouts.shift()!;
+ fn();
+ }
+ }
+}
+
+globalObject.addEventListener('message', handleMessage, true);
diff --git a/packages/engine-formula/src/dependency/dependency-tree.ts b/packages/engine-formula/src/dependency/dependency-tree.ts
index 3a31ccdd14..4f1bbbff1a 100644
--- a/packages/engine-formula/src/dependency/dependency-tree.ts
+++ b/packages/engine-formula/src/dependency/dependency-tree.ts
@@ -2,6 +2,7 @@ import type { IRange, IUnitRange, Nullable } from '@univerjs/core';
import { Disposable } from '@univerjs/core';
import type { BaseAstNode } from '../ast-node/base-ast-node';
+import type { IUnitExcludedCell } from '../basics/common';
export enum FDtreeStateType {
DEFAULT,
@@ -22,12 +23,14 @@ export class FormulaDependencyTree extends Disposable {
column: number = -1;
- sheetId: string = '';
+ subComponentId: string = '';
unitId: string = '';
rangeList: IUnitRange[] = [];
+ formulaId: Nullable<string>;
+
private _state = FDtreeStateType.DEFAULT;
override dispose(): void {
@@ -76,7 +79,10 @@ export class FormulaDependencyTree extends Disposable {
* @param dependencyRangeList
* @returns
*/
- dependencyRange(dependencyRangeList: Map<string, Map<string, IRange[]>>) {
+ dependencyRange(
+ dependencyRangeList: Map<string, Map<string, IRange[]>>,
+ unitExcludedCell: Nullable<IUnitExcludedCell>
+ ) {
if (this.rangeList.length === 0) {
return false;
}
@@ -99,6 +105,8 @@ export class FormulaDependencyTree extends Disposable {
const dependencyRanges = sheetRangeMap.get(sheetId)!;
+ const excludedCell = unitExcludedCell?.[unitId]?.[sheetId];
+
for (const dependencyRange of dependencyRanges) {
const { startRow, startColumn, endRow, endColumn } = dependencyRange;
@@ -110,7 +118,26 @@ export class FormulaDependencyTree extends Disposable {
) {
continue;
} else {
- return true;
+ let isInclude = true;
+ /**
+ * The position of the primary cell in the array formula needs to be excluded when calculating the impact of the array formula on dependencies.
+ * This is because its impact was already considered during the first calculation.
+ */
+ excludedCell?.forValue((row, column) => {
+ if (
+ row >= range.startRow &&
+ row <= range.endRow &&
+ column >= range.startColumn &&
+ column <= range.endColumn
+ ) {
+ isInclude = false;
+ return false;
+ }
+ });
+
+ if (isInclude) {
+ return true;
+ }
}
}
}
@@ -149,7 +176,7 @@ export class FormulaDependencyTree extends Disposable {
if (
dependenceTree.unitId === unitId &&
- dependenceTree.sheetId === sheetId &&
+ dependenceTree.subComponentId === sheetId &&
dependenceTree.compareRangeData(range)
) {
return true;
diff --git a/packages/engine-formula/src/dependency/formula-dependency.ts b/packages/engine-formula/src/dependency/formula-dependency.ts
index 9efd3c1b08..c1ec167dc6 100644
--- a/packages/engine-formula/src/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/dependency/formula-dependency.ts
@@ -10,7 +10,7 @@ import type { BaseAstNode } from '../ast-node/base-ast-node';
import { ErrorNode } from '../ast-node/base-ast-node';
import { NodeType } from '../ast-node/node-type';
import { FormulaAstLRU } from '../basics/cache-lru';
-import type { IFormulaData } from '../basics/common';
+import type { IFormulaData, IOtherFormulaData } from '../basics/common';
import { ErrorType } from '../basics/error-type';
import type { PreCalculateNodeType } from '../basics/node-type';
import { prefixToken, suffixToken } from '../basics/token';
@@ -50,11 +50,62 @@ export class FormulaDependencyGenerator extends Disposable {
const formulaData = this._currentConfigService.getFormulaData();
- const treeList = await this._generateTreeList(formulaData);
+ const otherFormulaData = this._currentConfigService.getOtherFormulaData();
+
+ const treeList = await this._generateTreeList(formulaData, otherFormulaData);
const updateTreeList = this._getUpdateTreeListAndMakeDependency(treeList);
- return Promise.resolve(this._calculateRunList(updateTreeList));
+ const isCycleDependency = this._checkIsCycleDependency(updateTreeList);
+
+ if (isCycleDependency) {
+ this._runtimeService.enableCycleDependency();
+ }
+
+ const finalTreeList = this._calculateRunList(updateTreeList);
+
+ return Promise.resolve(finalTreeList);
+ }
+
+ private _isCyclicUtil(
+ node: FormulaDependencyTree,
+ visited: Set<FormulaDependencyTree>,
+ recursionStack: Set<FormulaDependencyTree>
+ ) {
+ if (!visited.has(node)) {
+ // Mark the current node as visited and part of recursion stack
+ visited.add(node);
+ recursionStack.add(node);
+
+ // Recur for all the children of this node
+ for (let i = 0; i < node.children.length; i++) {
+ if (!visited.has(node.children[i]) && this._isCyclicUtil(node.children[i], visited, recursionStack)) {
+ return true;
+ }
+ if (recursionStack.has(node.children[i])) {
+ return true;
+ }
+ }
+ }
+ recursionStack.delete(node); // remove the node from recursion stack
+ return false;
+ }
+
+ private _checkIsCycleDependency(treeList: FormulaDependencyTree[]) {
+ const visited = new Set<FormulaDependencyTree>();
+ const recursionStack = new Set<FormulaDependencyTree>();
+
+ // Call the recursive helper function to detect cycle in different
+ // DFS trees
+ for (let i = 0, len = treeList.length; i < len; i++) {
+ const tree = treeList[i];
+ const isCycle = this._isCyclicUtil(tree, visited, recursionStack);
+ if (isCycle === true) {
+ return true;
+ }
+ }
+
+ return false;
}
/**
@@ -62,9 +113,11 @@ export class FormulaDependencyGenerator extends Disposable {
* @param formulaData
* @returns
*/
- private async _generateTreeList(formulaData: IFormulaData) {
+ private async _generateTreeList(formulaData: IFormulaData, otherFormulaData: IOtherFormulaData) {
const formulaDataKeys = Object.keys(formulaData);
+ const otherFormulaDataKeys = Object.keys(otherFormulaData);
+
const treeList: FormulaDependencyTree[] = [];
for (const unitId of formulaDataKeys) {
@@ -85,7 +138,7 @@ export class FormulaDependencyGenerator extends Disposable {
FDtree.node = node;
FDtree.formula = formulaString;
FDtree.unitId = unitId;
- FDtree.sheetId = sheetId;
+ FDtree.subComponentId = sheetId;
FDtree.row = row;
FDtree.column = column;
@@ -94,10 +147,41 @@ export class FormulaDependencyGenerator extends Disposable {
}
}
+ for (const unitId of otherFormulaDataKeys) {
+ const subComponentData = otherFormulaData[unitId];
+
+ const subComponentKeys = Object.keys(subComponentData);
+
+ for (const subComponentId of subComponentKeys) {
+ const subFormulaData = subComponentData[subComponentId];
+
+ const subFormulaDataKeys = Object.keys(subFormulaData);
+
+ for (const subFormulaDataId of subFormulaDataKeys) {
+ const formulaDataItem = subFormulaData[subFormulaDataId];
+
+ const { f: formulaString } = formulaDataItem;
+
+ const node = this._generateAstNode(formulaString);
+
+ const FDtree = new FormulaDependencyTree();
+
+ FDtree.node = node;
+ FDtree.formula = formulaString;
+ FDtree.unitId = unitId;
+ FDtree.subComponentId = subComponentId;
+
+ FDtree.formulaId = subFormulaDataId;
+
+ treeList.push(FDtree);
+ }
+ }
+ }
+
for (let i = 0, len = treeList.length; i < len; i++) {
const tree = treeList[i];
- this._runtimeService.setCurrent(tree.row, tree.column, tree.sheetId, tree.unitId);
+ this._runtimeService.setCurrent(tree.row, tree.column, tree.subComponentId, tree.unitId);
if (tree.node == null) {
throw new Error('tree node is null');
@@ -320,7 +404,12 @@ export class FormulaDependencyGenerator extends Disposable {
* includeTree: modification range contains formula
*/
if (
- (forceCalculate || tree.dependencyRange(this._updateRangeFlattenCache) || this._includeTree(tree)) &&
+ (forceCalculate ||
+ tree.dependencyRange(
+ this._updateRangeFlattenCache,
+ this._currentConfigService.getExcludedRange()
+ ) ||
+ this._includeTree(tree)) &&
!existTree.has(tree)
) {
newTreeList.push(tree);
@@ -339,7 +428,25 @@ export class FormulaDependencyGenerator extends Disposable {
*/
private _includeTree(tree: FormulaDependencyTree) {
const unitId = tree.unitId;
- const sheetId = tree.sheetId;
+ const subComponentId = tree.subComponentId;
+
+ const excludedCell = this._currentConfigService.getExcludedRange()?.[unitId]?.[subComponentId];
+
+ /**
+ * The position of the primary cell in the array formula needs to be excluded when calculating the impact of the array formula on dependencies.
+ * This is because its impact was already considered during the first calculation.
+ */
+ let isExclude = false;
+ excludedCell?.forValue((row, column) => {
+ if (tree.row === row && tree.column === column) {
+ isExclude = true;
+ return false;
+ }
+ });
+
+ if (isExclude) {
+ return false;
+ }
if (!this._updateRangeFlattenCache.has(unitId)) {
return false;
@@ -347,11 +454,11 @@ export class FormulaDependencyGenerator extends Disposable {
const sheetRangeMap = this._updateRangeFlattenCache.get(unitId)!;
- if (!sheetRangeMap.has(sheetId)) {
+ if (!sheetRangeMap.has(subComponentId)) {
return false;
}
- const ranges = sheetRangeMap.get(sheetId)!;
+ const ranges = sheetRangeMap.get(subComponentId)!;
for (const range of ranges) {
if (tree.compareRangeData(range)) {
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index a77c2a9b98..5878865e25 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -1,19 +1,33 @@
export { LexerNode } from './analysis/lexer-node';
export type {
- ArrayFormulaDataType,
+ IArrayFormulaRangeType,
+ IArrayFormulaUnitCellType,
+ IDirtyUnitSheetNameMap,
IFormulaData,
IFormulaDataItem,
IFormulaDatasetConfig,
+ IRuntimeUnitDataType,
ISheetData,
IUnitData,
IUnitSheetNameMap,
} from './basics/common';
+export { isInDirtyRange } from './basics/dirty';
+export { ErrorType } from './basics/error-type';
export { FUNCTION_NAMES, FunctionType, type IFunctionInfo, type IFunctionParam } from './basics/function';
export { includeFormulaLexerToken, isFormulaLexerToken, normalizeSheetName } from './basics/match-token';
export { generateStringWithSequence, type ISequenceNode, sequenceNodeType } from './basics/sequence';
export { matchToken } from './basics/token';
+export { compareToken } from './basics/token';
+export { BaseFunction } from './functions/base-function';
+export { ErrorValueObject } from './other-object/error-value-object';
export { BaseFormulaEnginePlugin } from './plugin';
+export { BaseReferenceObject, type FunctionVariantType } from './reference-object/base-reference-object';
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';
+export { FormulaExecutedStateType, type IAllRuntimeData } from './services/runtime.service';
+export { ArrayValueObject } from './value-object/array-value-object';
+export { BaseValueObject } from './value-object/base-value-object';
+export { NumberValueObject } from './value-object/primitive-object';
+export { BooleanValueObject } from './value-object/primitive-object';
+export { StringValueObject } from './value-object/primitive-object';
diff --git a/packages/engine-formula/src/interpreter/interpreter.ts b/packages/engine-formula/src/interpreter/interpreter.ts
index d85824c789..e73f0c1d9a 100644
--- a/packages/engine-formula/src/interpreter/interpreter.ts
+++ b/packages/engine-formula/src/interpreter/interpreter.ts
@@ -8,8 +8,13 @@ import { ErrorType } from '../basics/error-type';
import type { PreCalculateNodeType } from '../basics/node-type';
import { ErrorValueObject } from '../other-object/error-value-object';
import type { FunctionVariantType } from '../reference-object/base-reference-object';
+import { IFormulaRuntimeService } from '../services/runtime.service';
export class Interpreter extends Disposable {
+ constructor(@IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService) {
+ super();
+ }
+
override dispose(): void {}
async executeAsync(node: BaseAstNode): Promise<FunctionVariantType> {
@@ -82,6 +87,9 @@ export class Interpreter extends Disposable {
}
private async _executeAsync(node: BaseAstNode): Promise<AstNodePromiseType> {
+ if (this._runtimeService.isStopExecution()) {
+ return Promise.resolve(AstNodePromiseType.ERROR);
+ }
const children = node.getChildren();
const childrenCount = children.length;
for (let i = 0; i < childrenCount; i++) {
@@ -99,6 +107,9 @@ export class Interpreter extends Disposable {
}
private _execute(node: BaseAstNode): AstNodePromiseType {
+ if (this._runtimeService.isStopExecution()) {
+ return AstNodePromiseType.ERROR;
+ }
const children = node.getChildren();
const childrenCount = children.length;
for (let i = 0; i < childrenCount; i++) {
diff --git a/packages/engine-formula/src/other-object/error-value-object.ts b/packages/engine-formula/src/other-object/error-value-object.ts
index 2fc57398c1..df811d32b2 100644
--- a/packages/engine-formula/src/other-object/error-value-object.ts
+++ b/packages/engine-formula/src/other-object/error-value-object.ts
@@ -21,6 +21,13 @@ export class ErrorValueObject extends ObjectClassType {
return this._errorType;
}
+ override isEqual(object: ObjectClassType) {
+ if ((object as ErrorValueObject).getErrorType() === this.getErrorType()) {
+ return true;
+ }
+ return false;
+ }
+
override isErrorObject() {
return true;
}
diff --git a/packages/engine-formula/src/reference-object/base-reference-object.ts b/packages/engine-formula/src/reference-object/base-reference-object.ts
index fd6831c11d..1cf28bb3d9 100644
--- a/packages/engine-formula/src/reference-object/base-reference-object.ts
+++ b/packages/engine-formula/src/reference-object/base-reference-object.ts
@@ -39,6 +39,10 @@ export class BaseReferenceObject extends ObjectClassType {
private _runtimeData: IRuntimeUnitDataType = {};
+ private _arrayFormulaCellData: IRuntimeUnitDataType = {};
+
+ private _runtimeArrayFormulaCellData: IRuntimeUnitDataType = {};
+
private _refOffsetX = 0;
private _refOffsetY = 0;
@@ -208,6 +212,22 @@ export class BaseReferenceObject extends ObjectClassType {
this._runtimeData = runtimeData;
}
+ getArrayFormulaCellData() {
+ return this._arrayFormulaCellData;
+ }
+
+ setArrayFormulaCellData(unitData: IRuntimeUnitDataType) {
+ this._arrayFormulaCellData = unitData;
+ }
+
+ getRuntimeArrayFormulaCellData() {
+ return this._runtimeArrayFormulaCellData;
+ }
+
+ setRuntimeArrayFormulaCellData(unitData: IRuntimeUnitDataType) {
+ this._runtimeArrayFormulaCellData = unitData;
+ }
+
getRowCount() {
return this.getCurrentActiveSheetData().rowCount;
}
@@ -281,12 +301,29 @@ export class BaseReferenceObject extends ObjectClassType {
return this._runtimeData?.[this.getUnitId()]?.[this.getSheetId()];
}
+ getCurrentActiveArrayFormulaCellData() {
+ return this._arrayFormulaCellData?.[this.getUnitId()]?.[this.getSheetId()];
+ }
+
+ getCurrentRuntimeActiveArrayFormulaCellData() {
+ return this._runtimeArrayFormulaCellData?.[this.getUnitId()]?.[this.getSheetId()];
+ }
+
getCellData(row: number, column: number) {
const activeSheetData = this.getCurrentActiveSheetData();
const activeRuntimeData = this.getCurrentRuntimeSheetData();
- return activeRuntimeData?.getValue(row, column) || activeSheetData.cellData.getValue(row, column);
+ const activeArrayFormulaCellData = this.getCurrentActiveArrayFormulaCellData();
+
+ const activeRuntimeArrayFormulaCellData = this.getCurrentRuntimeActiveArrayFormulaCellData();
+
+ return (
+ activeRuntimeData?.getValue(row, column) ||
+ activeRuntimeArrayFormulaCellData?.getValue(row, column) ||
+ activeArrayFormulaCellData?.getValue(row, column) ||
+ activeSheetData.cellData.getValue(row, column)
+ );
}
getCellByPosition(row?: number, column?: number) {
diff --git a/packages/engine-formula/src/reference-object/cell-reference-object.ts b/packages/engine-formula/src/reference-object/cell-reference-object.ts
index 17f4d64667..2b9ad4d843 100644
--- a/packages/engine-formula/src/reference-object/cell-reference-object.ts
+++ b/packages/engine-formula/src/reference-object/cell-reference-object.ts
@@ -80,6 +80,10 @@ export class CellReferenceObject extends BaseReferenceObject {
rangeReferenceObject.setRuntimeData(this.getRuntimeData());
+ rangeReferenceObject.setArrayFormulaCellData(this.getArrayFormulaCellData());
+
+ rangeReferenceObject.setRuntimeArrayFormulaCellData(this.getRuntimeArrayFormulaCellData());
+
const { x, y } = this.getRefOffset();
rangeReferenceObject.setRefOffset(x, y);
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index a5801c4600..cc9046a9d1 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -1,14 +1,29 @@
-import type { IUnitRange } from '@univerjs/core';
-import { Disposable } from '@univerjs/core';
+import type { IUnitRange, Nullable } from '@univerjs/core';
+import { Disposable, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
-import type { IFormulaData, IFormulaDatasetConfig, IUnitData, IUnitSheetNameMap } from '../basics/common';
+import type {
+ IArrayFormulaUnitCellType,
+ IDirtyUnitSheetNameMap,
+ IFormulaData,
+ IFormulaDatasetConfig,
+ IOtherFormulaData,
+ IRuntimeUnitDataType,
+ ISheetData,
+ IUnitData,
+ IUnitExcludedCell,
+ IUnitSheetNameMap,
+} from '../basics/common';
+
+export const DEFAULT_DOCUMENT_SUB_COMPONENT_ID = '__default_document_sub_component_id20231101__';
export interface IFormulaCurrentConfigService {
getUnitData(): IUnitData;
getFormulaData(): IFormulaData;
+ getOtherFormulaData(): IOtherFormulaData;
+
getSheetNameMap(): IUnitSheetNameMap;
isForceCalculate(): boolean;
@@ -20,22 +35,46 @@ export interface IFormulaCurrentConfigService {
registerFormulaData(formulaData: IFormulaData): void;
registerSheetNameMap(sheetNameMap: IUnitSheetNameMap): void;
+
+ getExcludedRange(): Nullable<IUnitExcludedCell>;
+
+ loadDirtyRangesAndExcludedCell(dirtyRanges: IUnitRange[], excludedCell?: IUnitExcludedCell): void;
}
export class FormulaCurrentConfigService extends Disposable implements IFormulaCurrentConfigService {
private _unitData: IUnitData = {};
+
+ private _arrayFormulaCellData: IRuntimeUnitDataType = {};
+
+ private _otherFormulaData: IOtherFormulaData = {};
+
private _formulaData: IFormulaData = {};
+
private _sheetNameMap: IUnitSheetNameMap = {};
private _forceCalculate: boolean = false;
private _dirtyRanges: IUnitRange[] = [];
+ private _dirtyNameMap: IDirtyUnitSheetNameMap = {};
+
+ private _excludedCell: Nullable<IUnitExcludedCell>;
+
+ constructor(@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService) {
+ super();
+ }
+
override dispose(): void {
this._unitData = {};
this._formulaData = {};
+ this._arrayFormulaCellData = {};
this._sheetNameMap = {};
this._dirtyRanges = [];
+ this._excludedCell = {};
+ }
+
+ getExcludedRange() {
+ return this._excludedCell;
}
getUnitData() {
@@ -46,6 +85,14 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
return this._formulaData;
}
+ getArrayFormulaCellData() {
+ return this._arrayFormulaCellData;
+ }
+
+ getOtherFormulaData() {
+ return this._otherFormulaData;
+ }
+
getSheetNameMap() {
return this._sheetNameMap;
}
@@ -59,13 +106,31 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
}
load(config: IFormulaDatasetConfig) {
- this._unitData = config.unitData;
+ const { allUnitData, unitSheetNameMap } = this._loadSheetData();
+
+ this._unitData = allUnitData;
+
this._formulaData = config.formulaData;
- this._sheetNameMap = config.sheetNameMap;
+
+ this._arrayFormulaCellData = this._dataToRuntime(config.arrayFormulaCellData);
+
+ this._sheetNameMap = unitSheetNameMap;
+
+ this._otherFormulaData = this._loadOtherFormulaData();
this._forceCalculate = config.forceCalculate;
this._dirtyRanges = config.dirtyRanges;
+
+ this._dirtyNameMap = config.dirtyNameMap;
+
+ this._excludedCell = config.excludedCell;
+ }
+
+ loadDirtyRangesAndExcludedCell(dirtyRanges: IUnitRange[], excludedCell?: IUnitExcludedCell) {
+ this._dirtyRanges = dirtyRanges;
+
+ this._excludedCell = excludedCell;
}
registerUnitData(unitData: IUnitData) {
@@ -79,6 +144,141 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
registerSheetNameMap(sheetNameMap: IUnitSheetNameMap) {
this._sheetNameMap = sheetNameMap;
}
+
+ private _dataToRuntime(unitData: IArrayFormulaUnitCellType) {
+ const arrayFormulaCellData: IRuntimeUnitDataType = {};
+ Object.keys(unitData).forEach((unitId) => {
+ const sheetData = unitData[unitId];
+
+ if (arrayFormulaCellData[unitId] == null) {
+ arrayFormulaCellData[unitId] = {};
+ }
+
+ Object.keys(sheetData).forEach((sheetId) => {
+ const cellData = sheetData[sheetId];
+
+ arrayFormulaCellData[unitId][sheetId] = new ObjectMatrix(cellData);
+ });
+ });
+
+ return arrayFormulaCellData;
+ }
+
+ private _loadOtherFormulaData() {
+ const unitAllDoc = this._currentUniverService.getAllUniverDocsInstance();
+
+ const unitAllSlide = this._currentUniverService.getAllUniverSlidesInstance();
+
+ const otherFormulaData: IOtherFormulaData = {};
+
+ for (const documentDataModel of unitAllDoc) {
+ const unitId = documentDataModel.getUnitId();
+
+ if (otherFormulaData[unitId] == null) {
+ otherFormulaData[unitId] = {};
+ }
+
+ if (otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] == null) {
+ otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] = {};
+ }
+
+ const subComponent = otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID];
+
+ const customRanges = documentDataModel.getBody()?.customRanges;
+
+ if (customRanges == null) {
+ continue;
+ }
+
+ for (const customRange of customRanges) {
+ subComponent[customRange.rangeId] = {
+ f: customRange.endIndex.toString(),
+ };
+ }
+ }
+
+ for (const slide of unitAllSlide) {
+ const unitId = slide.getUnitId();
+
+ if (otherFormulaData[unitId] == null) {
+ otherFormulaData[unitId] = {};
+ }
+
+ if (otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] == null) {
+ otherFormulaData[unitId][DEFAULT_DOCUMENT_SUB_COMPONENT_ID] = {};
+ }
+
+ const pages = slide.getPages();
+
+ if (pages == null) {
+ continue;
+ }
+
+ const pageIds = Object.keys(pages);
+
+ for (const pageId of pageIds) {
+ const page = pages[pageId];
+
+ const subComponent = otherFormulaData[unitId][pageId];
+
+ const pageElements = page.pageElements;
+
+ if (pageElements == null) {
+ continue;
+ }
+
+ const pageElementIds = Object.keys(pageElements);
+
+ for (const pageElementId of pageElementIds) {
+ const pageElement = pageElements[pageElementId];
+ subComponent[pageElementId] = {
+ f: pageElement.title,
+ };
+ }
+ }
+ }
+
+ return otherFormulaData;
+ }
+
+ private _loadSheetData() {
+ const unitAllSheet = this._currentUniverService.getAllUniverSheetsInstance();
+
+ const allUnitData: IUnitData = {};
+
+ const unitSheetNameMap: IUnitSheetNameMap = {};
+
+ for (const workbook of unitAllSheet) {
+ const unitId = workbook.getUnitId();
+
+ const sheets = workbook.getSheets();
+
+ const sheetData: ISheetData = {};
+
+ const sheetNameMap: { [sheetName: string]: string } = {};
+
+ for (const sheet of sheets) {
+ const sheetId = sheet.getSheetId();
+
+ const sheetConfig = sheet.getConfig();
+ sheetData[sheetId] = {
+ cellData: new ObjectMatrix(sheetConfig.cellData),
+ rowCount: sheetConfig.rowCount,
+ columnCount: sheetConfig.columnCount,
+ };
+ sheetNameMap[sheet.getName()] = sheet.getSheetId();
+ }
+
+ allUnitData[unitId] = sheetData;
+
+ unitSheetNameMap[unitId] = sheetNameMap;
+ }
+
+ return {
+ allUnitData,
+ unitSheetNameMap,
+ };
+ }
}
export const IFormulaCurrentConfigService = createIdentifier<FormulaCurrentConfigService>(
diff --git a/packages/engine-formula/src/services/formula-engine.service.ts b/packages/engine-formula/src/services/formula-engine.service.ts
index e050629057..a40118b33a 100644
--- a/packages/engine-formula/src/services/formula-engine.service.ts
+++ b/packages/engine-formula/src/services/formula-engine.service.ts
@@ -1,6 +1,8 @@
-import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import type { IUnitRange } from '@univerjs/core';
+import { Disposable, IConfigService, LifecycleStages, ObjectMatrix, OnLifecycle } from '@univerjs/core';
import type { Ctor, Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
+import { Subject } from 'rxjs';
import { LexerTreeBuilder } from '../analysis/lexer';
import type { LexerNode } from '../analysis/lexer-node';
@@ -16,7 +18,7 @@ import { ReferenceNodeFactory } from '../ast-node/reference-node';
import { SuffixNodeFactory } from '../ast-node/suffix-node';
import { UnionNodeFactory } from '../ast-node/union-node';
import { ValueNodeFactory } from '../ast-node/value-node';
-import type { IFormulaDatasetConfig } from '../basics/common';
+import type { IArrayFormulaRangeType, IFormulaDatasetConfig, IUnitExcludedCell } from '../basics/common';
import { ErrorType } from '../basics/error-type';
import type { IFunctionInfo } from '../basics/function';
import { FUNCTION_NAMES } from '../basics/function';
@@ -44,12 +46,34 @@ import type { FunctionVariantType } from '../reference-object/base-reference-obj
import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from './current-data.service';
import { DefinedNamesService, IDefinedNamesService } from './defined-names.service';
import { FunctionService, IFunctionService } from './function.service';
-import { FormulaRuntimeService, IFormulaRuntimeService } from './runtime.service';
+import type { IAllRuntimeData, IExecutionInProgressParams } from './runtime.service';
+import { FormulaExecuteStageType, FormulaRuntimeService, IFormulaRuntimeService } from './runtime.service';
import { ISuperTableService, SuperTableService } from './super-table.service';
+export const DEFAULT_CYCLE_REFERENCE_COUNT = 1;
+
+export const CYCLE_REFERENCE_COUNT = 'cycleReferenceCount';
+
+export const EVERY_N_FUNCTION_EXECUTION_PAUSE = 100;
+
@OnLifecycle(LifecycleStages.Rendered, FormulaEngineService)
export class FormulaEngineService extends Disposable {
- constructor(@Inject(Injector) private readonly _injector: Injector) {
+ private readonly _executionStartListener$ = new Subject<boolean>();
+
+ readonly executionStartListener$ = this._executionStartListener$.asObservable();
+
+ private readonly _executionCompleteListener$ = new Subject<IAllRuntimeData>();
+
+ readonly executionCompleteListener$ = this._executionCompleteListener$.asObservable();
+
+ private readonly _executionInProgressListener$ = new Subject<IExecutionInProgressParams>();
+
+ readonly executionInProgressListener$ = this._executionInProgressListener$.asObservable();
+
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
super();
this._initializeDependencies();
this._initializeFunctions();
@@ -129,13 +153,6 @@ export class FormulaEngineService extends Disposable {
return this.functionService.getDescriptions();
}
- getRunTimeData(unitId: string) {
- return {
- sheetData: this.runtimeService.getSheetData(unitId),
- arrayFormulaData: this.runtimeService.getSheetArrayFormula(unitId),
- };
- }
-
builderLexerTree(formulaString: string) {
const lexerNode = this.lexerTreeBuilder.treeBuilder(formulaString, false);
@@ -177,17 +194,109 @@ export class FormulaEngineService extends Disposable {
* @param dirtyRanges input external unit data for multi workbook
* @returns
*/
- async execute(unitId: string, formulaDatasetConfig: IFormulaDatasetConfig) {
+ async execute(formulaDatasetConfig: IFormulaDatasetConfig) {
+ this._executionStartListener$.next(true);
+
this.currentConfigService.load(formulaDatasetConfig);
this.runtimeService.reset();
- // const dependencyGenerator = FormulaDependencyGenerator.create(formulaData, forceCalculate);
+ const cycleReferenceCount = (this._configService.getConfig('CYCLE_REFERENCE_COUNT') ||
+ DEFAULT_CYCLE_REFERENCE_COUNT) as number;
+
+ for (let i = 0; i < cycleReferenceCount; i++) {
+ await this._execute();
+ const isCycleDependency = this.runtimeService.isCycleDependency();
+ if (!isCycleDependency) {
+ break;
+ }
+ }
+
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CALCULATION_COMPLETED);
+
+ this._executionInProgressListener$.next(this.runtimeService.getRuntimeState());
+
+ this._executionCompleteListener$.next(this.runtimeService.getAllRuntimeData());
+ }
+
+ private async _execute() {
+ const executeState = await this._apply();
+
+ if (executeState == null) {
+ return;
+ }
+
+ const { arrayFormulaRange } = executeState;
+
+ const { dirtyRanges, excludedCell } = this._getArrayFormulaDirtyRangeAndExcludedRange(arrayFormulaRange);
+
+ if (dirtyRanges == null || dirtyRanges.length === 0) {
+ return true;
+ }
+
+ this.currentConfigService.loadDirtyRangesAndExcludedCell(dirtyRanges, excludedCell);
+
+ await this._apply(true);
+
+ return true;
+ }
+
+ private _getArrayFormulaDirtyRangeAndExcludedRange(arrayFormulaRange: IArrayFormulaRangeType) {
+ const dirtyRanges: IUnitRange[] = [];
+ const excludedCell: IUnitExcludedCell = {};
+ Object.keys(arrayFormulaRange).forEach((unitId) => {
+ const sheetArrayFormulaRange = arrayFormulaRange[unitId];
+ Object.keys(sheetArrayFormulaRange).forEach((sheetId) => {
+ const cellValue = new ObjectMatrix(sheetArrayFormulaRange[sheetId]);
+
+ if (cellValue == null) {
+ return true;
+ }
+
+ const newCellData = new ObjectMatrix<boolean>();
+
+ cellValue.forValue((row, column, range) => {
+ newCellData.setValue(row, column, true);
+
+ dirtyRanges.push({ unitId, sheetId, range });
+ });
+
+ if (excludedCell[unitId] == null) {
+ excludedCell[unitId] = {};
+ }
+
+ excludedCell[unitId][sheetId] = newCellData;
+ });
+ });
+
+ return { dirtyRanges, excludedCell };
+ }
+
+ private async _apply(isArrayFormulaState = false) {
+ if (isArrayFormulaState) {
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA);
+ } else {
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_DEPENDENCY);
+ }
+
+ this._executionInProgressListener$.next(this.runtimeService.getRuntimeState());
const treeList = await this.formulaDependencyGenerator.generate();
const interpreter = this.interpreter;
+ if (isArrayFormulaState) {
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_CALCULATION_ARRAY_FORMULA);
+
+ this.runtimeService.setTotalArrayFormulasToCalculate(treeList.length);
+ } else {
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START_CALCULATION);
+
+ this.runtimeService.setTotalFormulasToCalculate(treeList.length);
+ }
+
+ this._executionInProgressListener$.next(this.runtimeService.getRuntimeState());
+
for (let i = 0, len = treeList.length; i < len; i++) {
const tree = treeList[i];
const astNode = tree.node;
@@ -197,20 +306,56 @@ export class FormulaEngineService extends Disposable {
throw new Error('astNode is null');
}
- this.runtimeService.setCurrent(tree.row, tree.column, tree.sheetId, tree.unitId);
+ this.runtimeService.setCurrent(tree.row, tree.column, tree.subComponentId, tree.unitId);
if (interpreter.checkAsyncNode(astNode)) {
value = await interpreter.executeAsync(astNode);
} else {
value = interpreter.execute(astNode);
}
- this.runtimeService.setRuntimeData(value);
+
+ /**
+ * For every 100 functions, execute a setTimeout to wait for external command input.
+ */
+ if (i % EVERY_N_FUNCTION_EXECUTION_PAUSE === 0) {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ }
+
+ if (this.runtimeService.isStopExecution()) {
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
+ this.runtimeService.markedAsStopFunctionsExecuted();
+ this._executionCompleteListener$.next(this.runtimeService.getAllRuntimeData());
+ return;
+ }
+
+ if (tree.formulaId != null) {
+ this.runtimeService.setRuntimeOtherData(tree.formulaId, value);
+ } else {
+ this.runtimeService.setRuntimeData(value);
+ }
+
+ if (isArrayFormulaState) {
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA);
+
+ this.runtimeService.setCompletedArrayFormulasCount(i + 1);
+ } else {
+ this.runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CURRENTLY_CALCULATING);
+
+ this.runtimeService.setCompletedFormulasCount(i + 1);
+ }
+
+ this._executionInProgressListener$.next(this.runtimeService.getRuntimeState());
+ }
+
+ if (treeList.length > 0) {
+ this.runtimeService.markedAsSuccessfullyExecuted();
+ } else if (!isArrayFormulaState) {
+ this.runtimeService.markedAsNoFunctionsExecuted();
}
- return {
- sheetData: this.runtimeService.getSheetData(unitId),
- arrayFormulaData: this.runtimeService.getSheetArrayFormula(unitId),
- };
+ return this.runtimeService.getAllRuntimeData();
}
calculate(formulaString: string, transformSuffix: boolean = true) {
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index c5195bd037..04324478b2 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -1,25 +1,69 @@
import type { ICellData, IRange, Nullable } from '@univerjs/core';
-import { CellValueType, Disposable, ObjectMatrix } from '@univerjs/core';
+import { CellValueType, Disposable, isNullCell, ObjectMatrix } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
import type { BaseAstNode } from '../ast-node/base-ast-node';
-import type {
- ArrayFormulaDataType,
- IRuntimeSheetData,
- IRuntimeUnitDataType,
- UnitArrayFormulaDataType,
-} from '../basics/common';
-import type { ErrorValueObject } from '../other-object/error-value-object';
+import type { IArrayFormulaRangeType, IRuntimeOtherUnitDataType, IRuntimeUnitDataType } from '../basics/common';
+import { isInDirtyRange } from '../basics/dirty';
+import { ErrorType } from '../basics/error-type';
+import { ErrorValueObject } from '../other-object/error-value-object';
import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
import type { ArrayValueObject } from '../value-object/array-value-object';
import type { BaseValueObject, CalculateValueType } from '../value-object/base-value-object';
+import { IFormulaCurrentConfigService } from './current-data.service';
+
+/**
+ * IDLE: Idle phase of the formula engine.
+ *
+ * DEPENDENCY: Dependency calculation phase, where the formulas that need to be calculated are determined by the modified area,
+ * as well as their dependencies. This outputs an array of formulas to execute.
+ *
+ * INTERPRETER:Formula execution phase, where the calculation of formulas begins.
+ *
+ */
+export enum FormulaExecuteStageType {
+ IDLE,
+ START_DEPENDENCY,
+ START_CALCULATION,
+ CURRENTLY_CALCULATING,
+ START_DEPENDENCY_ARRAY_FORMULA,
+ START_CALCULATION_ARRAY_FORMULA,
+ CURRENTLY_CALCULATING_ARRAY_FORMULA,
+ CALCULATION_COMPLETED,
+}
+
+export enum FormulaExecutedStateType {
+ INITIAL,
+ STOP_EXECUTION,
+ NOT_EXECUTED,
+ SUCCESS,
+}
+
+export interface IAllRuntimeData {
+ unitData: IRuntimeUnitDataType;
+ arrayFormulaRange: IArrayFormulaRangeType;
+ unitOtherData: IRuntimeOtherUnitDataType;
+ functionsExecutedState: FormulaExecutedStateType;
+ arrayFormulaCellData: IRuntimeUnitDataType;
+ clearArrayFormulaCellData: IRuntimeUnitDataType;
+}
+
+export interface IExecutionInProgressParams {
+ totalFormulasToCalculate: number;
+ completedFormulasCount: number;
+
+ totalArrayFormulasToCalculate: number;
+ completedArrayFormulasCount: number;
+
+ stage: FormulaExecuteStageType;
+}
export interface IFormulaRuntimeService {
currentRow: number;
currentColumn: number;
- currentSheetId: string;
+ currentSubComponentId: string;
currentUnitId: string;
@@ -35,28 +79,98 @@ export interface IFormulaRuntimeService {
setRuntimeData(functionVariant: FunctionVariantType): void;
- getSheetData(unitId: string): IRuntimeSheetData;
+ getUnitData(): IRuntimeUnitDataType;
- getSheetArrayFormula(unitId: string): ArrayFormulaDataType;
+ getUnitArrayFormula(): IArrayFormulaRangeType;
- getUnitData(): IRuntimeUnitDataType;
+ stopExecution(): void;
+
+ setFormulaExecuteStage(type: FormulaExecuteStageType): void;
+
+ isStopExecution(): boolean;
+
+ getFormulaExecuteStage(): FormulaExecuteStageType;
+
+ setRuntimeOtherData(formulaId: string, functionVariant: FunctionVariantType): void;
+
+ getRuntimeOtherData(): IRuntimeOtherUnitDataType;
+
+ getAllRuntimeData(): IAllRuntimeData;
+
+ markedAsSuccessfullyExecuted(): void;
- getUnitArrayFormula(): UnitArrayFormulaDataType;
+ markedAsNoFunctionsExecuted(): void;
+
+ markedAsStopFunctionsExecuted(): void;
+
+ markedAsInitialFunctionsExecuted(): void;
+
+ setTotalFormulasToCalculate(value: number): void;
+
+ getTotalFormulasToCalculate(): number;
+
+ setCompletedFormulasCount(value: number): void;
+
+ getCompletedFormulasCount(): number;
+
+ getRuntimeState(): IExecutionInProgressParams;
+
+ setTotalArrayFormulasToCalculate(value: number): void;
+
+ getTotalArrayFormulasToCalculate(): number;
+
+ setCompletedArrayFormulasCount(value: number): void;
+
+ getCompletedArrayFormulasCount(): number;
+
+ enableCycleDependency(): void;
+
+ disableCycleDependency(): void;
+
+ isCycleDependency(): boolean;
+
+ getRuntimeArrayFormulaCellData(): IRuntimeUnitDataType;
}
export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeService {
+ private _formulaExecuteStage: FormulaExecuteStageType = FormulaExecuteStageType.IDLE;
+
+ private _stopState = false;
+
private _currentRow: number = 0;
private _currentColumn: number = 0;
- private _currentSheetId: string = '';
+ private _currentSubComponentId: string = '';
private _currentUnitId: string = '';
private _runtimeData: IRuntimeUnitDataType = {};
- private _unitArrayFormulaData: UnitArrayFormulaDataType = {};
+ private _runtimeOtherData: IRuntimeOtherUnitDataType = {}; // Data returned by other businesses through formula calculation, excluding the sheet.
+
+ private _unitArrayFormulaRange: IArrayFormulaRangeType = {};
+
+ private _runtimeArrayFormulaCellData: IRuntimeUnitDataType = {};
+
+ private _runtimeClearArrayFormulaCellData: IRuntimeUnitDataType = {};
+
+ private _functionsExecutedState: FormulaExecutedStateType = FormulaExecutedStateType.INITIAL;
// lambdaId: { key: BaseAstNode }
private _functionDefinitionPrivacyVar: Map<string, Map<string, Nullable<BaseAstNode>>> = new Map();
+ private _totalFormulasToCalculate: number = 0;
+
+ private _completedFormulasCount: number = 0;
+
+ private _totalArrayFormulasToCalculate: number = 0;
+
+ private _completedArrayFormulasCount: number = 0;
+
+ private _isCycleDependency: boolean = false;
+
+ constructor(@IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService) {
+ super();
+ }
+
get currentRow() {
return this._currentRow;
}
@@ -65,8 +179,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
return this._currentColumn;
}
- get currentSheetId() {
- return this._currentSheetId;
+ get currentSubComponentId() {
+ return this._currentSubComponentId;
}
get currentUnitId() {
@@ -77,16 +191,104 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
this.reset();
}
+ enableCycleDependency() {
+ this._isCycleDependency = true;
+ }
+
+ disableCycleDependency() {
+ this._isCycleDependency = false;
+ }
+
+ isCycleDependency() {
+ return this._isCycleDependency;
+ }
+
+ setTotalArrayFormulasToCalculate(value: number) {
+ this._totalArrayFormulasToCalculate = value;
+ }
+
+ getTotalArrayFormulasToCalculate() {
+ return this._totalArrayFormulasToCalculate;
+ }
+
+ setCompletedArrayFormulasCount(value: number) {
+ this._completedArrayFormulasCount = value;
+ }
+
+ getCompletedArrayFormulasCount() {
+ return this._completedArrayFormulasCount;
+ }
+
+ setTotalFormulasToCalculate(value: number) {
+ this._totalFormulasToCalculate = value;
+ }
+
+ getTotalFormulasToCalculate() {
+ return this._totalFormulasToCalculate;
+ }
+
+ setCompletedFormulasCount(value: number) {
+ this._completedFormulasCount = value;
+ }
+
+ getCompletedFormulasCount() {
+ return this._completedFormulasCount;
+ }
+
+ markedAsSuccessfullyExecuted() {
+ this._functionsExecutedState = FormulaExecutedStateType.SUCCESS;
+ }
+
+ markedAsNoFunctionsExecuted() {
+ this._functionsExecutedState = FormulaExecutedStateType.NOT_EXECUTED;
+ }
+
+ markedAsStopFunctionsExecuted() {
+ this._functionsExecutedState = FormulaExecutedStateType.STOP_EXECUTION;
+ }
+
+ markedAsInitialFunctionsExecuted() {
+ this._functionsExecutedState = FormulaExecutedStateType.INITIAL;
+ }
+
+ stopExecution() {
+ this._stopState = true;
+
+ this.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
+ }
+
+ isStopExecution() {
+ return this._stopState;
+ }
+
+ setFormulaExecuteStage(type: FormulaExecuteStageType) {
+ this._formulaExecuteStage = type;
+ }
+
+ getFormulaExecuteStage() {
+ return this._formulaExecuteStage;
+ }
+
reset() {
+ this._formulaExecuteStage = FormulaExecuteStageType.IDLE;
this._runtimeData = {};
- this._unitArrayFormulaData = {};
+ this._runtimeOtherData = {};
+ this._unitArrayFormulaRange = {};
+ this._runtimeArrayFormulaCellData = {};
+ this._runtimeClearArrayFormulaCellData = {};
this._functionDefinitionPrivacyVar.clear();
+ this.markedAsInitialFunctionsExecuted();
+
+ this._isCycleDependency = false;
+
+ this._totalFormulasToCalculate = 0;
+ this._completedFormulasCount = 0;
}
setCurrent(row: number, column: number, sheetId: string, unitId: string) {
this._currentRow = row;
this._currentColumn = column;
- this._currentSheetId = sheetId;
+ this._currentSubComponentId = sheetId;
this._currentUnitId = unitId;
}
@@ -102,73 +304,171 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
return this._functionDefinitionPrivacyVar.get(lambdaId);
}
+ setRuntimeOtherData(formulaId: string, functionVariant: FunctionVariantType) {
+ const subComponentId = this._currentSubComponentId;
+ const unitId = this._currentUnitId;
+
+ if (this._runtimeOtherData[unitId] === undefined) {
+ this._runtimeOtherData[unitId] = {};
+ }
+
+ const unitData = this._runtimeOtherData[unitId];
+
+ if (unitData[subComponentId] === undefined) {
+ unitData[subComponentId] = {};
+ }
+
+ const subComponentData = unitData[subComponentId];
+
+ subComponentData[formulaId] = this._objectValueToCellValue(functionVariant as CalculateValueType)!;
+ }
+
setRuntimeData(functionVariant: FunctionVariantType) {
const row = this._currentRow;
const column = this._currentColumn;
- const sheetId = this._currentSheetId;
+ const sheetId = this._currentSubComponentId;
const unitId = this._currentUnitId;
- if (this._runtimeData[unitId] === undefined) {
+ if (this._runtimeData[unitId] == null) {
this._runtimeData[unitId] = {};
}
const unitData = this._runtimeData[unitId];
- if (unitData[sheetId] === undefined) {
+ if (unitData[sheetId] == null) {
unitData[sheetId] = new ObjectMatrix<ICellData>();
}
- if (this._unitArrayFormulaData[unitId] === undefined) {
- this._unitArrayFormulaData[unitId] = {};
+ if (this._unitArrayFormulaRange[unitId] == null) {
+ this._unitArrayFormulaRange[unitId] = {};
}
- const arrayFormulaData = this._unitArrayFormulaData[unitId];
+ const arrayFormulaRange = this._unitArrayFormulaRange[unitId];
+
+ let arrayData = new ObjectMatrix<IRange>();
+
+ if (!arrayFormulaRange[sheetId]) {
+ arrayData = new ObjectMatrix(arrayFormulaRange[sheetId]);
+ }
+
+ if (this._runtimeArrayFormulaCellData[unitId] === undefined) {
+ this._runtimeArrayFormulaCellData[unitId] = {};
+ }
+
+ const arrayFormulaCellData = this._runtimeArrayFormulaCellData[unitId];
+
+ if (arrayFormulaCellData[sheetId] == null) {
+ arrayFormulaCellData[sheetId] = new ObjectMatrix<ICellData>();
+ }
- if (arrayFormulaData[sheetId] === undefined) {
- arrayFormulaData[sheetId] = new ObjectMatrix<IRange>();
+ if (this._runtimeClearArrayFormulaCellData[unitId] === undefined) {
+ this._runtimeClearArrayFormulaCellData[unitId] = {};
+ }
+
+ const clearArrayFormulaCellData = this._runtimeClearArrayFormulaCellData[unitId];
+
+ if (clearArrayFormulaCellData[sheetId] == null) {
+ clearArrayFormulaCellData[sheetId] = new ObjectMatrix<ICellData>();
}
const sheetData = unitData[sheetId];
- const arrayData = arrayFormulaData[sheetId];
+
+ const arrayUnitData = arrayFormulaCellData[sheetId];
+
+ const clearArrayUnitData = clearArrayFormulaCellData[sheetId];
+
if (
functionVariant.isReferenceObject() ||
(functionVariant.isValueObject() && (functionVariant as BaseValueObject).isArray())
) {
const objectValueRefOrArray = functionVariant as BaseReferenceObject | ArrayValueObject;
+
const { startRow, startColumn, endRow, endColumn } = objectValueRefOrArray.getRangePosition();
- objectValueRefOrArray.iterator((valueObject, rowIndex, columnIndex) => {
- sheetData.setValue(
- rowIndex - startRow + row,
- columnIndex - startColumn + column,
- this._objectValueToCellValue(valueObject)
- );
- });
-
- arrayData.setValue(row, column, {
+
+ const arrayRange = {
startRow: row,
startColumn: column,
- endRow: endRow - startRow + 1 + row,
- endColumn: endColumn - startColumn + 1 + column,
- });
+ endRow: endRow - startRow + row,
+ endColumn: endColumn - startColumn + column,
+ };
+
+ if (this._checkIfArrayFormulaRangeHasData(unitId, sheetId, row, column, arrayRange)) {
+ const errorObject = this._objectValueToCellValue(new ErrorValueObject(ErrorType.SPILL));
+ sheetData.setValue(row, column, errorObject);
+ clearArrayUnitData.setValue(row, column, errorObject);
+ } else {
+ const spillError = new ErrorValueObject(ErrorType.SPILL);
+ objectValueRefOrArray.iterator((valueObject, rowIndex, columnIndex) => {
+ const value = this._objectValueToCellValue(valueObject);
+ if (rowIndex === startRow && columnIndex === startColumn) {
+ /**
+ * If the referenced range contains an error in the spill of the array formula,
+ * then the current array formula should report an error together.
+ */
+ if (valueObject.isErrorObject() && valueObject.isEqual(spillError)) {
+ clearArrayUnitData.setValue(row, column, {});
+ sheetData.setValue(row, column, { ...this._objectValueToCellValue(spillError) });
+ return false;
+ }
+ sheetData.setValue(row, column, { ...value });
+ }
+ arrayUnitData.setValue(rowIndex - startRow + row, columnIndex - startColumn + column, value);
+ });
+
+ arrayData.setValue(row, column, arrayRange);
+
+ arrayFormulaRange[sheetId] = arrayData.getData();
+ }
} else {
- sheetData.setValue(row, column, this._objectValueToCellValue(functionVariant as CalculateValueType));
+ const valueObject = this._objectValueToCellValue(functionVariant as CalculateValueType);
+ sheetData.setValue(row, column, valueObject);
+ clearArrayUnitData.setValue(row, column, valueObject);
}
}
- getSheetData(unitId: string) {
- return this._runtimeData[unitId];
+ getUnitData() {
+ return this._runtimeData;
}
- getSheetArrayFormula(unitId: string) {
- return this._unitArrayFormulaData[unitId];
+ getUnitArrayFormula() {
+ return this._unitArrayFormulaRange;
}
- getUnitData() {
- return this._runtimeData;
+ getRuntimeOtherData() {
+ return this._runtimeOtherData;
}
- getUnitArrayFormula() {
- return this._unitArrayFormulaData;
+ getRuntimeArrayFormulaCellData() {
+ return this._runtimeArrayFormulaCellData;
+ }
+
+ getRuntimeClearArrayFormulaCellData() {
+ return this._runtimeClearArrayFormulaCellData;
+ }
+
+ getAllRuntimeData(): IAllRuntimeData {
+ return {
+ unitData: this.getUnitData(),
+ arrayFormulaRange: this.getUnitArrayFormula(),
+ unitOtherData: this.getRuntimeOtherData(),
+ functionsExecutedState: this._functionsExecutedState,
+ arrayFormulaCellData: this.getRuntimeArrayFormulaCellData(),
+ clearArrayFormulaCellData: this.getRuntimeClearArrayFormulaCellData(),
+ };
+ }
+
+ getRuntimeState(): IExecutionInProgressParams {
+ return {
+ totalFormulasToCalculate: this.getTotalFormulasToCalculate(),
+
+ completedFormulasCount: this.getCompletedFormulasCount(),
+
+ totalArrayFormulasToCalculate: this.getTotalArrayFormulasToCalculate(),
+
+ completedArrayFormulasCount: this.getCompletedArrayFormulasCount(),
+
+ stage: this.getFormulaExecuteStage(),
+ };
}
private _objectValueToCellValue(objectValue: CalculateValueType) {
@@ -199,6 +499,44 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
};
}
}
+
+ private _checkIfArrayFormulaRangeHasData(
+ formulaUnitId: string,
+ formulaSheetId: string,
+ formulaRow: number,
+ formulaColumn: number,
+ arrayRange: IRange
+ ) {
+ const { startRow, startColumn, endRow, endColumn } = arrayRange;
+
+ const unitData = this._currentConfigService.getUnitData();
+
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ if (r === formulaRow && formulaColumn === c) {
+ continue;
+ }
+
+ const cell = this._runtimeData?.[formulaUnitId]?.[formulaSheetId]?.getValue(r, c);
+
+ const currentCell = unitData?.[formulaUnitId]?.[formulaSheetId]?.cellData?.getValue(r, c);
+
+ if (
+ (!isNullCell(cell) || !isNullCell(currentCell)) &&
+ this._isInDirtyRange(formulaUnitId, formulaSheetId, r, c)
+ ) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private _isInDirtyRange(unitId: string, sheetId: string, row: number, column: number) {
+ const dirtyRanges = this._currentConfigService.getDirtyRanges();
+ return isInDirtyRange(dirtyRanges, unitId, sheetId, row, column);
+ }
}
export const IFormulaRuntimeService = createIdentifier<FormulaRuntimeService>('univer.formula.runtime.service');
diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.ts
index 7932bdeff7..f902c7fcf5 100644
--- a/packages/engine-render/src/basics/tools.ts
+++ b/packages/engine-render/src/basics/tools.ts
@@ -247,7 +247,7 @@ export function getFontStyleString(textStyle?: IStyleBase, localeService?: Local
// TODO: @jikkai @DR-Univer should read default font from configuration, not from locale service
const defaultFont = 'Arial';
- const defaultFontSize = 14;
+ const defaultFontSize = 13;
// const { fontList, defaultFontSize } = fontLocale;
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
index 08ac3445ff..ee743db172 100644
--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
@@ -1085,7 +1085,7 @@ export class SpreadsheetSkeleton extends Skeleton {
wrapStrategy,
}
);
- } else if (cell.v) {
+ } else if (cell.v != null) {
const textStyle = this._getFontFormat(style);
fontString = getFontStyleString(textStyle, this._localService).fontCache;
diff --git a/packages/formula/package.json b/packages/formula/package.json
index 95f0f1f6f4..3aaf1b5880 100644
--- a/packages/formula/package.json
+++ b/packages/formula/package.json
@@ -37,7 +37,10 @@
"private": false,
"scripts": {
"esbuild": "node ./esbuild.config.mjs && tsc -p tsconfig.esbuild.json",
- "typedoc": "typedoc"
+ "typedoc": "typedoc",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage"
},
"dependencies": {
"@univerjs/engine-formula": "workspace:*",
@@ -46,8 +49,13 @@
"@wendellhu/redi": "^0.12.11"
},
"devDependencies": {
- "esbuild": "^0.19.5",
+ "@vitest/coverage-istanbul": "^0.34.6",
"typedoc": "^0.25.4",
- "typescript": "^5.3.2"
+ "esbuild": "^0.19.8",
+ "happy-dom": "^12.10.3",
+ "less": "^4.2.0",
+ "ts-node": "^10.9.1",
+ "typescript": "^5.3.2",
+ "vitest": "^0.34.6"
}
}
diff --git a/packages/formula/src/commands/mutations/set-array-formula-data.mutation.ts b/packages/formula/src/commands/mutations/set-array-formula-data.mutation.ts
new file mode 100644
index 0000000000..a27cb0eb35
--- /dev/null
+++ b/packages/formula/src/commands/mutations/set-array-formula-data.mutation.ts
@@ -0,0 +1,32 @@
+import type { IMutation } from '@univerjs/core';
+import { CommandType, Tools } from '@univerjs/core';
+import type { IArrayFormulaRangeType, IArrayFormulaUnitCellType } from '@univerjs/engine-formula';
+import type { IAccessor } from '@wendellhu/redi';
+
+import { FormulaDataModel } from '../../models/formula-data.model';
+
+export interface ISetArrayFormulaDataMutationParams {
+ arrayFormulaRange: IArrayFormulaRangeType;
+ arrayFormulaCellData: IArrayFormulaUnitCellType;
+}
+
+export const SetArrayFormulaDataUndoMutationFactory = (accessor: IAccessor): ISetArrayFormulaDataMutationParams => {
+ const formulaDataModel = accessor.get(FormulaDataModel);
+ const arrayFormulaRange = Tools.deepClone(formulaDataModel.getArrayFormulaRange());
+ const arrayFormulaCellData = Tools.deepClone(formulaDataModel.getArrayFormulaCellData());
+ return {
+ arrayFormulaRange,
+ arrayFormulaCellData,
+ };
+};
+
+export const SetArrayFormulaDataMutation: IMutation<ISetArrayFormulaDataMutationParams> = {
+ id: 'formula.mutation.set-array-formula-data',
+ type: CommandType.MUTATION,
+ handler: (accessor: IAccessor, params: ISetArrayFormulaDataMutationParams) => {
+ const formulaDataModel = accessor.get(FormulaDataModel);
+ formulaDataModel.setArrayFormulaRange(params.arrayFormulaRange);
+ formulaDataModel.setArrayFormulaCellData(params.arrayFormulaCellData);
+ return true;
+ },
+};
diff --git a/packages/formula/src/commands/mutations/set-formula-calculation.mutation.ts b/packages/formula/src/commands/mutations/set-formula-calculation.mutation.ts
new file mode 100644
index 0000000000..5938de01d8
--- /dev/null
+++ b/packages/formula/src/commands/mutations/set-formula-calculation.mutation.ts
@@ -0,0 +1,21 @@
+import type { ICommandInfo, IMutation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+
+export interface ISetFormulaCalculationStartMutation {
+ commands: ICommandInfo[];
+}
+
+export const setFormulaCalculationStartMutation: IMutation<ISetFormulaCalculationStartMutation> = {
+ id: 'formula.mutation.set-formula-calculation-start',
+ type: CommandType.MUTATION,
+ handler: (accessor: IAccessor, params: ISetFormulaCalculationStartMutation) => true,
+};
+
+export interface ISetFormulaCalculationStopMutation {}
+
+export const setFormulaCalculationStopMutation: IMutation<ISetFormulaCalculationStopMutation> = {
+ id: 'formula.mutation.set-formula-calculation-stop',
+ type: CommandType.MUTATION,
+ handler: (accessor: IAccessor, params: ISetFormulaCalculationStopMutation) => true,
+};
diff --git a/packages/formula/src/controllers/__tests__/create-command-test-bed.ts b/packages/formula/src/controllers/__tests__/create-command-test-bed.ts
new file mode 100644
index 0000000000..1bf5d8c94b
--- /dev/null
+++ b/packages/formula/src/controllers/__tests__/create-command-test-bed.ts
@@ -0,0 +1,80 @@
+import type { IWorkbookData } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import { FormulaEngineService } from '@univerjs/engine-formula';
+import { SelectionManagerService } from '@univerjs/sheets';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ '1': {
+ '1': {
+ v: 1,
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+};
+
+export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+
+ let get: Injector['get'] | undefined;
+
+ /**
+ * This plugin hooks into Sheet's DI system to expose API to test scripts
+ */
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Sheet;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ get = this._injector.get.bind(this._injector);
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([SelectionManagerService]);
+ injector.add([FormulaEngineService]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onDestroy(): void {
+ get = undefined;
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA_DEMO);
+
+ if (get === undefined) {
+ throw new Error('[TestPlugin]: not hooked on!');
+ }
+
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test');
+
+ const logService = get(ILogService);
+ logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+
+ return {
+ univer,
+ get,
+ sheet,
+ };
+}
diff --git a/packages/formula/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/formula/src/controllers/__tests__/update-formula.controller.spec.ts
new file mode 100644
index 0000000000..fd997ff86a
--- /dev/null
+++ b/packages/formula/src/controllers/__tests__/update-formula.controller.spec.ts
@@ -0,0 +1,74 @@
+import type { ICellData, Nullable, Univer } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, RANGE_TYPE } from '@univerjs/core';
+import { MoveRowsCommand, NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '@univerjs/sheets';
+import type { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, it } from 'vitest';
+
+import { createCommandTestBed } from './create-command-test-bed';
+
+// TODO@Dushusir: add move range,insert range,delete range test case
+describe('Test insert function operation', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let getValueByPosition: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Nullable<ICellData>;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(MoveRowsCommand);
+
+ getValueByPosition = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Nullable<ICellData> =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValue();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ describe('update formula', () => {
+ describe('correct situations', () => {
+ it('move rows update formula', async () => {
+ const selectionManager = get(SelectionManagerService);
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ // A1
+ selectionManager.add([
+ {
+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ const params = {
+ fromRow: 0,
+ toRow: 1,
+ };
+
+ await commandService.executeCommand(MoveRowsCommand.id, params);
+ });
+ });
+ });
+});
diff --git a/packages/formula/src/controllers/__tests__/utils.spec.ts b/packages/formula/src/controllers/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..a346704c29
--- /dev/null
+++ b/packages/formula/src/controllers/__tests__/utils.spec.ts
@@ -0,0 +1,686 @@
+import {
+ DeleteRangeMoveLeftCommand,
+ DeleteRangeMoveUpCommand,
+ InsertColCommand,
+ InsertRangeMoveDownCommand,
+ InsertRangeMoveRightCommand,
+ InsertRowCommand,
+ MoveColsCommand,
+ MoveRangeCommand,
+ MoveRowsCommand,
+ RemoveColCommand,
+ RemoveRowCommand,
+} from '@univerjs/sheets';
+import { describe, expect, it } from 'vitest';
+
+import { offsetArrayFormula, offsetFormula } from '../utils';
+
+describe('utils test', () => {
+ describe('function offsetFormula', () => {
+ it('move range', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A5)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: MoveRangeCommand.id,
+ params: {
+ fromRange: {
+ startRow: 0,
+ startColumn: 3,
+ endRow: 0,
+ endColumn: 3,
+ },
+ toRange: {
+ startRow: 3,
+ startColumn: 3,
+ endRow: 3,
+ endColumn: 3,
+ },
+ },
+ };
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': null,
+ },
+ '3': {
+ '3': {
+ f: '=SUM(A5)',
+ },
+ },
+ },
+ },
+ });
+ });
+ it('move rows', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A5)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: MoveRowsCommand.id,
+ params: {
+ fromRow: 0,
+ toRow: 4,
+ },
+ };
+
+ const selections = [
+ {
+ range: {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 19,
+ rangeType: 1,
+ },
+ primary: {
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ },
+ style: {
+ strokeWidth: 2,
+ stroke: '#409f11',
+ fill: 'rgba(53, 50, 43, 0.1)',
+ widgets: {},
+ widgetSize: 6,
+ widgetStrokeWidth: 1,
+ widgetStroke: '#ffffff',
+ hasAutoFill: true,
+ AutofillSize: 6,
+ AutofillStrokeWidth: 1,
+ AutofillStroke: '#ffffff',
+ hasRowHeader: true,
+ rowHeaderFill: 'rgba(53, 50, 43, 0.1)',
+ rowHeaderStroke: '#409f11',
+ rowHeaderStrokeWidth: 1,
+ hasColumnHeader: true,
+ columnHeaderFill: 'rgba(53, 50, 43, 0.1)',
+ columnHeaderStroke: '#409f11',
+ columnHeaderStrokeWidth: 1,
+ },
+ },
+ ];
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId, selections);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '3': {
+ '3': {
+ f: '=SUM(A5)',
+ },
+ },
+ },
+ },
+ });
+ });
+ it('move columns', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '0': {
+ f: '=SUM(E2)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: MoveColsCommand.id,
+ params: {
+ fromCol: 0,
+ toCol: 4,
+ },
+ };
+
+ const selections = [
+ {
+ range: {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 999,
+ endColumn: 0,
+ rangeType: 2,
+ },
+ primary: {
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ },
+ style: {
+ strokeWidth: 2,
+ stroke: '#409f11',
+ fill: 'rgba(53, 50, 43, 0.1)',
+ widgets: {},
+ widgetSize: 6,
+ widgetStrokeWidth: 1,
+ widgetStroke: '#ffffff',
+ hasAutoFill: true,
+ AutofillSize: 6,
+ AutofillStrokeWidth: 1,
+ AutofillStroke: '#ffffff',
+ hasRowHeader: true,
+ rowHeaderFill: 'rgba(53, 50, 43, 0.1)',
+ rowHeaderStroke: '#409f11',
+ rowHeaderStrokeWidth: 1,
+ hasColumnHeader: true,
+ columnHeaderFill: 'rgba(53, 50, 43, 0.1)',
+ columnHeaderStroke: '#409f11',
+ columnHeaderStrokeWidth: 1,
+ },
+ },
+ ];
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId, selections);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(E2)',
+ },
+ },
+ },
+ },
+ });
+ });
+ it('insert row', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A1)',
+ },
+ },
+ '1': {
+ '3': {
+ f: '=SUM(A3)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: InsertRowCommand.id,
+ params: {
+ workbookId: unitId,
+ worksheetId: sheetId,
+ direction: 2,
+ range: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 19,
+ },
+ },
+ };
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A1)',
+ },
+ },
+ // '1': {},
+ '2': {
+ '3': {
+ f: '=SUM(A3)',
+ },
+ },
+ },
+ },
+ });
+ });
+ it('insert column', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '2': {
+ f: '=SUM(C2)',
+ },
+ '3': {
+ f: '=SUM(D2)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: InsertColCommand.id,
+ params: {
+ workbookId: unitId,
+ worksheetId: sheetId,
+ direction: 1,
+ range: {
+ startColumn: 1,
+ endColumn: 1,
+ startRow: 0,
+ endRow: 3,
+ },
+ },
+ };
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(C2)',
+ },
+ '4': {
+ f: '=SUM(D2)',
+ },
+ },
+ },
+ },
+ });
+ });
+ it('insert range move right', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '2': {
+ f: '=SUM(B2)',
+ },
+ '3': {
+ f: '=SUM(C2)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: InsertRangeMoveRightCommand.id,
+ params: {
+ ranges: [
+ {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ rangeType: 0,
+ },
+ ],
+ },
+ };
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(B2)',
+ },
+ '4': {
+ f: '=SUM(C2)',
+ },
+ },
+ },
+ },
+ });
+ });
+ it('insert range move down', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A2)',
+ },
+ },
+ '1': {
+ '3': {
+ f: '=SUM(A3)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: InsertRangeMoveDownCommand.id,
+ params: {
+ ranges: [
+ {
+ startRow: 0,
+ startColumn: 3,
+ endRow: 0,
+ endColumn: 3,
+ rangeType: 0,
+ },
+ ],
+ },
+ };
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ // '0': {},
+ '1': {
+ '3': {
+ f: '=SUM(A2)',
+ },
+ },
+ '2': {
+ '3': {
+ f: '=SUM(A3)',
+ },
+ },
+ },
+ },
+ });
+ });
+ it('remove row', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '1': {
+ '3': {
+ f: '=SUM(A1)',
+ },
+ },
+ '2': {
+ '3': {
+ f: '=SUM(A2)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: RemoveRowCommand.id,
+ params: {
+ ranges: [
+ {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 19,
+ rangeType: 1,
+ },
+ ],
+ },
+ };
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A1)',
+ },
+ },
+ '1': {
+ '3': {
+ f: '=SUM(A2)',
+ },
+ },
+ // '2': {},
+ },
+ },
+ });
+ });
+ it('remove column', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '2': {
+ f: '=SUM(C2)',
+ },
+ '3': {
+ f: '=SUM(D2)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: RemoveColCommand.id,
+ params: {
+ ranges: [
+ {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 999,
+ endColumn: 0,
+ rangeType: 2,
+ },
+ ],
+ },
+ };
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '1': {
+ f: '=SUM(C2)',
+ },
+ '2': {
+ f: '=SUM(D2)',
+ },
+ },
+ },
+ },
+ });
+ });
+ it('delete range move up', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '1': {
+ '3': {
+ f: '=SUM(A2)',
+ },
+ },
+ '2': {
+ '3': {
+ f: '=SUM(A3)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: DeleteRangeMoveUpCommand.id,
+ params: {
+ ranges: [
+ {
+ startRow: 0,
+ startColumn: 3,
+ endRow: 0,
+ endColumn: 3,
+ rangeType: 0,
+ },
+ ],
+ },
+ };
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '3': {
+ f: '=SUM(A2)',
+ },
+ },
+ '1': {
+ '3': {
+ f: '=SUM(A3)',
+ },
+ },
+ // '2': {},
+ },
+ },
+ });
+ });
+ it('delete range move left', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const formulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '2': {
+ f: '=SUM(B2)',
+ },
+ '3': {
+ f: '=SUM(C2)',
+ },
+ },
+ },
+ },
+ };
+
+ const command = {
+ id: DeleteRangeMoveLeftCommand.id,
+ params: {
+ ranges: [
+ {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ rangeType: 0,
+ },
+ ],
+ },
+ };
+
+ const newFormulaData = offsetFormula(formulaData, command, unitId, sheetId);
+ expect(newFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '0': {
+ '1': {
+ f: '=SUM(B2)',
+ },
+ '2': {
+ f: '=SUM(C2)',
+ },
+ },
+ },
+ },
+ });
+ });
+ });
+ describe('function offsetArrayFormula', () => {
+ it('offset array formula data', () => {
+ const unitId = 'workbook-01';
+ const sheetId = 'sheet-0011';
+ const arrayFormulaData = {
+ [unitId]: {
+ [sheetId]: {
+ '7': {
+ '0': {
+ startRow: 6,
+ startColumn: 0,
+ endRow: 9,
+ endColumn: 3,
+ },
+ '5': {
+ startRow: 6,
+ startColumn: 5,
+ endRow: 9,
+ endColumn: 8,
+ },
+ },
+ },
+ },
+ };
+
+ const newArrayFormulaData = offsetArrayFormula(arrayFormulaData, unitId, sheetId);
+ expect(newArrayFormulaData).toStrictEqual({
+ [unitId]: {
+ [sheetId]: {
+ '7': {
+ '0': {
+ startRow: 7,
+ startColumn: 0,
+ endRow: 10,
+ endColumn: 3,
+ },
+ '5': {
+ startRow: 7,
+ startColumn: 5,
+ endRow: 10,
+ endColumn: 8,
+ },
+ },
+ },
+ },
+ });
+ });
+ });
+});
diff --git a/packages/formula/src/controllers/array-formula-display.controller.ts b/packages/formula/src/controllers/array-formula-display.controller.ts
new file mode 100644
index 0000000000..784a39adb6
--- /dev/null
+++ b/packages/formula/src/controllers/array-formula-display.controller.ts
@@ -0,0 +1,80 @@
+import type { ICommandInfo } from '@univerjs/core';
+import {
+ Disposable,
+ ICommandService,
+ INTERCEPTOR_POINT,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ SheetInterceptorService,
+} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
+import type { ISetArrayFormulaDataMutationParams } from '../commands/mutations/set-array-formula-data.mutation';
+import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
+import { FormulaDataModel } from '../models/formula-data.model';
+
+@OnLifecycle(LifecycleStages.Ready, ArrayFormulaDisplayController)
+export class ArrayFormulaDisplayController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._commandExecutedListener();
+
+ this._initInterceptorCellContent();
+ }
+
+ private _commandExecutedListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ // Synchronous data from worker
+ if (command.id !== SetArrayFormulaDataMutation.id) {
+ return;
+ }
+
+ const params = command.params as ISetArrayFormulaDataMutationParams;
+
+ if (params == null) {
+ return;
+ }
+
+ const { arrayFormulaRange, arrayFormulaCellData } = params;
+ this._formulaDataModel.setArrayFormulaRange(arrayFormulaRange);
+ this._formulaDataModel.setArrayFormulaCellData(arrayFormulaCellData);
+ })
+ );
+ }
+
+ private _initInterceptorCellContent() {
+ this.disposeWithMe(
+ this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
+ priority: 100,
+ handler: (cell, location, next) => {
+ const { workbookId, worksheetId, row, col } = location;
+ const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();
+ const arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();
+ const cellData = arrayFormulaCellData?.[workbookId]?.[worksheetId]?.[row]?.[col];
+ const cellRange = arrayFormulaRange?.[workbookId]?.[worksheetId]?.[row]?.[col];
+ if (cellData == null) {
+ return next(cell);
+ }
+
+ if (cellRange != null && cellRange.startRow === row && cellRange.startColumn === col) {
+ return next(cell);
+ }
+
+ return next({ ...cell, ...cellData });
+ },
+ })
+ );
+ }
+}
diff --git a/packages/formula/src/controllers/calculate.controller.ts b/packages/formula/src/controllers/calculate.controller.ts
index 1c691301cd..eee1ba3cd1 100644
--- a/packages/formula/src/controllers/calculate.controller.ts
+++ b/packages/formula/src/controllers/calculate.controller.ts
@@ -1,28 +1,60 @@
-import type { ICommandInfo, IUnitRange } from '@univerjs/core';
+import type { ICellData, ICommandInfo, IRange, IUnitRange, ObjectMatrixPrimitiveType } from '@univerjs/core';
import {
+ Dimension,
Disposable,
ICommandService,
- IConfigService,
IUniverInstanceService,
LifecycleStages,
ObjectMatrix,
OnLifecycle,
} from '@univerjs/core';
-import type { IFormulaData, ISheetData, IUnitData, IUnitSheetNameMap } from '@univerjs/engine-formula';
-import { FormulaEngineService } from '@univerjs/engine-formula';
-import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { SetRangeValuesMutation } from '@univerjs/sheets';
+import type { IAllRuntimeData, IDirtyUnitSheetNameMap, IFormulaData } from '@univerjs/engine-formula';
+import { FormulaEngineService, FormulaExecutedStateType } from '@univerjs/engine-formula';
+import type {
+ IAddWorksheetMergeMutationParams,
+ IDeleteRangeMutationParams,
+ IMoveColumnsMutationParams,
+ IMoveRangeMutationParams,
+ IMoveRowsMutationParams,
+ IRemoveRowsMutationParams,
+ IRemoveSheetMutationParams,
+ ISetRangeValuesMutationParams,
+ ISetWorksheetNameMutationParams,
+} from '@univerjs/sheets';
+import {
+ AddWorksheetMergeMutation,
+ DeleteRangeMutation,
+ InsertRangeMutation,
+ MoveColsMutation,
+ MoveRangeMutation,
+ MoveRowsMutation,
+ RemoveColMutation,
+ RemoveRowMutation,
+ RemoveSheetMutation,
+ SetRangeValuesMutation,
+ SetStyleCommand,
+ SetWorksheetNameMutation,
+} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
-
+import type { Nullable } from 'vitest';
+
+import type { ISetArrayFormulaDataMutationParams } from '../commands/mutations/set-array-formula-data.mutation';
+import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
+import type { ISetFormulaCalculationStartMutation } from '../commands/mutations/set-formula-calculation.mutation';
+import { setFormulaCalculationStartMutation } from '../commands/mutations/set-formula-calculation.mutation';
+import type { ISetFormulaDataMutationParams } from '../commands/mutations/set-formula-data.mutation';
+import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';
import { FormulaDataModel } from '../models/formula-data.model';
+import type { FormulaService } from '../services/formula.service';
+import { IFormulaService } from '../services/formula.service';
-@OnLifecycle(LifecycleStages.Starting, CalculateController)
+@OnLifecycle(LifecycleStages.Ready, CalculateController)
export class CalculateController extends Disposable {
constructor(
- @IConfigService private readonly _configService: IConfigService,
- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @Inject(IFormulaService) private readonly _formulaService: FormulaService,
@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
) {
super();
@@ -32,164 +64,424 @@ export class CalculateController extends Disposable {
private _initialize(): void {
this._commandExecutedListener();
+ this._initialExecuteFormulaListener();
+ this._registerFunctions();
}
private _commandExecutedListener() {
- // TODO@Dushusir: sheet rename
- const updateCommandList = [SetRangeValuesMutation.id];
-
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (!updateCommandList.includes(command.id)) {
- return;
- }
+ if (command.id === SetFormulaDataMutation.id) {
+ const formulaData = (command.params as ISetFormulaDataMutationParams).formulaData as IFormulaData;
+ this._formulaDataModel.setFormulaData(formulaData);
+ } else if (command.id === setFormulaCalculationStartMutation.id) {
+ const params = command.params as ISetFormulaCalculationStartMutation;
+ const { dirtyRanges, dirtyNameMap } = this._generateDirty(params.commands);
+
+ this._calculate(dirtyRanges, dirtyNameMap);
+ } else if (command.id === SetArrayFormulaDataMutation.id) {
+ const params = command.params as ISetArrayFormulaDataMutationParams;
+
+ if (params == null) {
+ return;
+ }
- this._calculate(command as ICommandInfo<ISetRangeValuesMutationParams>);
+ const { arrayFormulaRange, arrayFormulaCellData } = params;
+ this._formulaDataModel.setArrayFormulaRange(arrayFormulaRange);
+ this._formulaDataModel.setArrayFormulaCellData(arrayFormulaCellData);
+ }
})
);
}
- private _calculate(command: ICommandInfo<ISetRangeValuesMutationParams>) {
- const { params } = command;
- if (!params || params.isFormulaUpdate === true) return;
+ private _generateDirty(commands: ICommandInfo[]) {
+ const dirtyRanges: IUnitRange[] = [];
+ const dirtyNameMap: IDirtyUnitSheetNameMap = {};
+
+ for (const command of commands) {
+ if (command.id === SetRangeValuesMutation.id) {
+ const params = command.params as ISetRangeValuesMutationParams;
+ /**
+ * Changes in the cell value caused by the formula or style
+ * will not trigger the formula to be marked as dirty for calculation.
+ */
+ if (params.isFormulaUpdate === true || params.trigger === SetStyleCommand.id) {
+ continue;
+ }
+ dirtyRanges.push(...this._getSetRangeValuesMutationDirtyRange(params));
+ } else if (command.id === MoveRangeMutation.id) {
+ const params = command.params as IMoveRangeMutationParams;
+ dirtyRanges.push(...this._getMoveRangeMutationDirtyRange(params));
+ } else if (command.id === MoveRowsMutation.id || command.id === MoveColsMutation.id) {
+ const params = command.params as IMoveRowsMutationParams | IMoveColumnsMutationParams;
+ dirtyRanges.push(...this._getMoveRowsMutationDirtyRange(params));
+ } else if (command.id === DeleteRangeMutation.id || command.id === InsertRangeMutation.id) {
+ const params = command.params as IDeleteRangeMutationParams;
+ dirtyRanges.push(...this._getDeleteRangeMutationDirtyRange(params));
+ } else if (command.id === RemoveRowMutation.id || command.id === RemoveColMutation.id) {
+ const params = command.params as IRemoveRowsMutationParams;
+ const isRow = command.id === RemoveRowMutation.id;
+ dirtyRanges.push(...this._getRemoveRowOrColumnMutation(params, isRow));
+ } else if (command.id === RemoveSheetMutation.id) {
+ const params = command.params as IRemoveSheetMutationParams;
+ this._getSheetMutationDirtyName(dirtyNameMap, params);
+ } else if (command.id === SetWorksheetNameMutation.id) {
+ const params = command.params as ISetWorksheetNameMutationParams;
+ this._getSheetMutationDirtyName(dirtyNameMap, params, params.name);
+ } else if (command.id === AddWorksheetMergeMutation.id) {
+ const params = command.params as IAddWorksheetMergeMutationParams;
+ this._getSheetMutationDirtyName(dirtyNameMap, params);
+ }
+ }
+
+ return {
+ dirtyRanges,
+ dirtyNameMap,
+ };
+ }
+ private _getSetRangeValuesMutationDirtyRange(params: ISetRangeValuesMutationParams) {
const { worksheetId: sheetId, workbookId: unitId, cellValue } = params;
- if (cellValue == null) return;
- // const formulaData = this._formulaDataModel.getFormulaData();
+ const dirtyRanges: IUnitRange[] = [];
+
+ if (cellValue == null) {
+ return dirtyRanges;
+ }
+
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, cellValue));
+
+ dirtyRanges.push(...this._getDirtyRangesForArrayFormula(unitId, sheetId, cellValue));
+
+ return dirtyRanges;
+ }
+
+ private _getMoveRangeMutationDirtyRange(params: IMoveRangeMutationParams) {
+ const { worksheetId: sheetId, workbookId: unitId, from, to } = params;
const dirtyRanges: IUnitRange[] = [];
- const discreteRanges = new ObjectMatrix(cellValue).getDiscreteRanges();
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, from));
- discreteRanges.forEach((range) => {
- dirtyRanges.push({ unitId, sheetId, range });
- });
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, to));
- if (dirtyRanges.length === 0) return;
+ dirtyRanges.push(...this._getDirtyRangesForArrayFormula(unitId, sheetId, to));
+
+ return dirtyRanges;
+ }
+
+ private _getMoveRowsMutationDirtyRange(params: IMoveRowsMutationParams) {
+ const { worksheetId: sheetId, workbookId: unitId, sourceRange, targetRange } = params;
+
+ const dirtyRanges: IUnitRange[] = [];
+
+ const sourceMatrix = this._rangeToMatrix(sourceRange).getData();
+
+ const targetMatrix = this._rangeToMatrix(targetRange).getData();
- const { allUnitData, formulaData, unitSheetNameMap } = this._getCalculateData();
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, sourceMatrix));
- this._executeFormula(unitId, allUnitData, formulaData, unitSheetNameMap, false, dirtyRanges);
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, targetMatrix));
+
+ dirtyRanges.push(...this._getDirtyRangesForArrayFormula(unitId, sheetId, targetMatrix));
+
+ return dirtyRanges;
}
- private _executeFormula(
- unitId: string,
- allUnitData: IUnitData,
- formulaData: IFormulaData,
- unitSheetNameMap: IUnitSheetNameMap,
- forceCalculate: boolean = false,
- dirtyRanges: IUnitRange[]
- ) {
- // Add mutation after calculating the formula
- this._formulaEngineService
- .execute(unitId, {
- unitData: allUnitData,
- formulaData,
- sheetNameMap: unitSheetNameMap,
- forceCalculate,
- dirtyRanges,
- })
- .then((data) => {
- const { sheetData, arrayFormulaData } = data;
+ private _getDeleteRangeMutationDirtyRange(params: IDeleteRangeMutationParams) {
+ const { worksheetId: sheetId, workbookId: unitId, ranges, shiftDimension } = params;
- if (!sheetData) {
- console.error('No sheetData from Formula Engine!');
- return;
- }
+ const dirtyRanges: IUnitRange[] = [];
- if (arrayFormulaData) {
- // TODO@Dushusir: refresh array formula view
- this._formulaDataModel.setArrayFormulaData(arrayFormulaData);
- }
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+
+ const worksheet = workbook?.getSheetBySheetId(sheetId);
- const sheetIds = Object.keys(sheetData);
-
- // Update each calculated value, possibly involving all cells
- const redoMutationsInfo: ICommandInfo[] = [];
- sheetIds.forEach((sheetId) => {
- const cellData = sheetData[sheetId];
- const setRangeValuesMutation: ISetRangeValuesMutationParams = {
- worksheetId: sheetId,
- workbookId: unitId,
- cellValue: cellData.getData(),
- isFormulaUpdate: true,
- };
-
- redoMutationsInfo.push({
- id: SetRangeValuesMutation.id,
- params: setRangeValuesMutation,
- });
+ const lastEndRow = worksheet?.getLastRowWithContent() || 0;
+
+ const lastEndColumn = worksheet?.getLastColumnWithContent() || 0;
+
+ const matrix = new ObjectMatrix<ICellData | null>();
+
+ for (const range of ranges) {
+ let newMatrix: Nullable<ObjectMatrix<ICellData | null>> = null;
+ const { startRow, startColumn, endRow, endColumn } = range;
+ if (shiftDimension === Dimension.ROWS) {
+ newMatrix = this._rangeToMatrix({
+ startRow,
+ startColumn,
+ endRow: lastEndRow,
+ endColumn,
});
+ } else if (shiftDimension === Dimension.COLUMNS) {
+ newMatrix = this._rangeToMatrix({
+ startRow,
+ startColumn,
+ endRow,
+ endColumn: lastEndColumn,
+ });
+ }
- const result = redoMutationsInfo.every((m) => this._commandService.executeCommand(m.id, m.params));
- return result;
- });
+ if (newMatrix != null) {
+ matrix.merge(newMatrix);
+ }
+ }
+
+ const matrixData = matrix.getData();
+
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, matrixData));
+
+ dirtyRanges.push(...this._getDirtyRangesForArrayFormula(unitId, sheetId, matrixData));
+
+ return dirtyRanges;
}
- private _getCalculateData() {
- const unitAllSheet = this._currentUniverService.getAllUniverSheetsInstance();
+ private _getRemoveRowOrColumnMutation(params: IRemoveRowsMutationParams, isRow: boolean = true) {
+ const { worksheetId: sheetId, workbookId: unitId, ranges } = params;
+
+ const dirtyRanges: IUnitRange[] = [];
- const formulaData: IFormulaData = {};
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
- const allUnitData: IUnitData = {};
+ const worksheet = workbook?.getSheetBySheetId(sheetId);
- const unitSheetNameMap: IUnitSheetNameMap = {};
+ const rowCount = worksheet?.getRowCount() || 0;
- for (const workbook of unitAllSheet) {
- const unitId = workbook.getUnitId();
- if (formulaData[unitId] == null) {
- formulaData[unitId] = {};
+ const columnCount = worksheet?.getColumnCount() || 0;
+
+ const matrix = new ObjectMatrix<ICellData | null>();
+
+ for (const range of ranges) {
+ let newMatrix: Nullable<ObjectMatrix<ICellData | null>> = null;
+ const { startRow, endRow, startColumn, endColumn } = range;
+
+ if (isRow === true) {
+ newMatrix = this._rangeToMatrix({
+ startRow,
+ startColumn: 0,
+ endRow,
+ endColumn: columnCount - 1,
+ });
+ } else {
+ newMatrix = this._rangeToMatrix({
+ startRow: 0,
+ startColumn,
+ endRow: rowCount,
+ endColumn,
+ });
}
- const sheets = workbook.getSheets();
- const workbookFormulaData = formulaData[unitId];
+ if (newMatrix != null) {
+ matrix.merge(newMatrix);
+ }
+ }
- const sheetData: ISheetData = {};
+ const matrixData = matrix.getData();
- const sheetNameMap: { [sheetName: string]: string } = {};
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, matrixData));
- for (const sheet of sheets) {
- const sheetId = sheet.getSheetId();
- if (workbookFormulaData[sheetId] == null) {
- workbookFormulaData[sheetId] = {};
- }
+ dirtyRanges.push(...this._getDirtyRangesForArrayFormula(unitId, sheetId, matrixData));
+
+ return dirtyRanges;
+ }
+
+ private _getSheetMutationDirtyName(
+ dirtyNameMap: IDirtyUnitSheetNameMap,
+ params: IRemoveSheetMutationParams,
+ name?: Nullable<string>
+ ) {
+ const { worksheetId: sheetId, workbookId: unitId } = params;
- const sheetFormulaData = workbookFormulaData[sheetId];
+ // const dirtyNameMap: IDirtyUnitSheetNameMap = {};
- const cellDatas = sheet.getCellMatrix();
+ if (dirtyNameMap[unitId] == null) {
+ dirtyNameMap[unitId] = {};
+ }
+
+ dirtyNameMap[unitId][sheetId] = name;
+
+ return dirtyNameMap;
+ }
+
+ private _rangeToMatrix(range: IRange) {
+ const matrix = new ObjectMatrix<ICellData | null>();
+
+ const { startRow, startColumn, endRow, endColumn } = range;
+
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ matrix.setValue(r, c, {});
+ }
+ }
+
+ return matrix;
+ }
+
+ private _getDirtyRangesByCellValue(
+ unitId: string,
+ sheetId: string,
+ cellValue?: ObjectMatrixPrimitiveType<ICellData | null>
+ ) {
+ const dirtyRanges: IUnitRange[] = [];
+
+ if (cellValue == null) {
+ return dirtyRanges;
+ }
+
+ const cellMatrix = new ObjectMatrix(cellValue);
- cellDatas.forValue((row, column, cellData) => {
- if (cellData?.f != null) {
- if (sheetFormulaData[row] == null) {
- sheetFormulaData[row] = {};
- }
- sheetFormulaData[row][column] = {
- f: cellData.f,
- x: 0,
- y: 0,
- };
+ const discreteRanges = cellMatrix.getDiscreteRanges();
+
+ discreteRanges.forEach((range) => {
+ dirtyRanges.push({ unitId, sheetId, range });
+ });
+
+ return dirtyRanges;
+ }
+
+ /**
+ * The array formula is a range where only the top-left corner contains the formula value.
+ * All other positions, apart from the top-left corner, need to be marked as dirty.
+ */
+ private _getDirtyRangesForArrayFormula(
+ unitId: string,
+ sheetId: string,
+ cellValue: ObjectMatrixPrimitiveType<ICellData | null>
+ ) {
+ const dirtyRanges: IUnitRange[] = [];
+
+ if (cellValue == null) {
+ return dirtyRanges;
+ }
+
+ const cellMatrix = new ObjectMatrix(cellValue);
+
+ const arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();
+
+ /**
+ * The array formula is a range where only the top-left corner contains the formula value.
+ * All other positions, apart from the top-left corner, need to be marked as dirty.
+ */
+ if (arrayFormulaRange?.[unitId]?.[sheetId]) {
+ const cellRangeData = new ObjectMatrix<IRange>(arrayFormulaRange?.[unitId]?.[sheetId]);
+ cellMatrix.forValue((row, column) => {
+ cellRangeData.forValue((arrayFormulaRow, arrayFormulaColumn, arrayFormulaRange) => {
+ const { startRow, startColumn, endRow, endColumn } = arrayFormulaRange;
+ if (row >= startRow && row <= endRow && column >= startColumn && column <= endColumn) {
+ dirtyRanges.push({
+ unitId,
+ sheetId,
+ range: {
+ startRow,
+ startColumn,
+ endRow: startRow,
+ endColumn: startColumn,
+ },
+ });
}
});
+ });
+ }
- const sheetConfig = sheet.getConfig();
- sheetData[sheetId] = {
- cellData: new ObjectMatrix(sheetConfig.cellData),
- rowCount: sheetConfig.rowCount,
- columnCount: sheetConfig.columnCount,
- };
- sheetNameMap[sheet.getName()] = sheet.getSheetId();
+ return dirtyRanges;
+ }
+
+ private async _calculate(dirtyRanges: IUnitRange[], dirtyNameMap: IDirtyUnitSheetNameMap) {
+ if (dirtyRanges.length === 0) return;
+
+ const formulaData = this._formulaDataModel.getFormulaData();
+
+ const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();
+
+ // Synchronous to the main thread
+ // this._commandService.executeCommand(SetFormulaDataMutation.id, { formulaData });
+ this._formulaEngineService.execute({
+ formulaData,
+ arrayFormulaCellData,
+ forceCalculate: false,
+ dirtyRanges,
+ dirtyNameMap,
+ });
+ }
+
+ private _initialExecuteFormulaListener() {
+ /**
+ * Assignment operation after formula calculation.
+ */
+ this._formulaEngineService.executionCompleteListener$.subscribe((data) => {
+ const functionsExecutedState = data.functionsExecutedState;
+ switch (functionsExecutedState) {
+ case FormulaExecutedStateType.NOT_EXECUTED:
+ break;
+ case FormulaExecutedStateType.STOP_EXECUTION:
+ break;
+ case FormulaExecutedStateType.SUCCESS:
+ this._applyFormula(data);
+ break;
+ case FormulaExecutedStateType.INITIAL:
+ break;
}
+ });
+ }
- allUnitData[unitId] = sheetData;
+ private async _applyFormula(data: IAllRuntimeData) {
+ const { unitData, arrayFormulaRange, arrayFormulaCellData, clearArrayFormulaCellData } = data;
- unitSheetNameMap[unitId] = sheetNameMap;
+ if (!unitData) {
+ console.error('No sheetData from Formula Engine!');
+ return;
}
- return {
- formulaData,
- allUnitData,
- unitSheetNameMap,
- };
+ // const deleteMutationInfo = this._deletePreviousArrayFormulaValue(arrayFormulaRange);
+
+ if (arrayFormulaRange) {
+ this._formulaDataModel.clearPreviousArrayFormulaCellData(clearArrayFormulaCellData);
+
+ this._formulaDataModel.mergeArrayFormulaCellData(arrayFormulaCellData);
+
+ this._formulaDataModel.mergeArrayFormulaRange(arrayFormulaRange);
+
+ // Synchronous to the main thread
+ this._commandService.executeCommand(SetArrayFormulaDataMutation.id, {
+ arrayFormulaRange: this._formulaDataModel.getArrayFormulaRange(),
+ arrayFormulaCellData: this._formulaDataModel.getArrayFormulaCellData(),
+ });
+ }
+
+ const unitIds = Object.keys(unitData);
+
+ // Update each calculated value, possibly involving all cells
+ const redoMutationsInfo: ICommandInfo[] = [];
+
+ unitIds.forEach((unitId) => {
+ const sheetData = unitData[unitId];
+
+ const sheetIds = Object.keys(sheetData);
+
+ sheetIds.forEach((sheetId) => {
+ const cellData = sheetData[sheetId];
+
+ // const arrayFormula = arrayFormulaRange[unitId][sheetId];
+
+ const setRangeValuesMutation: ISetRangeValuesMutationParams = {
+ worksheetId: sheetId,
+ workbookId: unitId,
+ cellValue: cellData.getData(),
+ isFormulaUpdate: true,
+ };
+
+ redoMutationsInfo.push({
+ id: SetRangeValuesMutation.id,
+ params: setRangeValuesMutation,
+ });
+ });
+ });
+
+ const result = redoMutationsInfo.every((m) => this._commandService.executeCommand(m.id, m.params));
+ return result;
+ }
+
+ private _registerFunctions() {
+ this._formulaService.registerFunctions();
}
}
diff --git a/packages/formula/src/controllers/formula.controller.ts b/packages/formula/src/controllers/formula.controller.ts
index 1bce2467ab..35d1546ed7 100644
--- a/packages/formula/src/controllers/formula.controller.ts
+++ b/packages/formula/src/controllers/formula.controller.ts
@@ -1,5 +1,10 @@
import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
+import {
+ setFormulaCalculationStartMutation,
+ setFormulaCalculationStopMutation,
+} from '../commands/mutations/set-formula-calculation.mutation';
import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';
@OnLifecycle(LifecycleStages.Ready, FormulaController)
@@ -15,8 +20,11 @@ export class FormulaController extends Disposable {
}
private _registerCommands(): void {
- [SetFormulaDataMutation].forEach((command) =>
- this.disposeWithMe(this._commandService.registerCommand(command))
- );
+ [
+ SetFormulaDataMutation,
+ SetArrayFormulaDataMutation,
+ setFormulaCalculationStartMutation,
+ setFormulaCalculationStopMutation,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
}
diff --git a/packages/formula/src/controllers/trigger-calculation.controller.ts b/packages/formula/src/controllers/trigger-calculation.controller.ts
new file mode 100644
index 0000000000..214119789f
--- /dev/null
+++ b/packages/formula/src/controllers/trigger-calculation.controller.ts
@@ -0,0 +1,135 @@
+import type { ICommandInfo } from '@univerjs/core';
+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { FormulaEngineService, FormulaExecutedStateType } from '@univerjs/engine-formula';
+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
+import {
+ AddWorksheetMergeMutation,
+ DeleteRangeMutation,
+ InsertRangeMutation,
+ MoveColsMutation,
+ MoveRangeMutation,
+ MoveRowsMutation,
+ RemoveColMutation,
+ RemoveRowMutation,
+ RemoveSheetMutation,
+ SetRangeValuesMutation,
+ SetStyleCommand,
+ SetWorksheetNameMutation,
+} from '@univerjs/sheets';
+import { Inject } from '@wendellhu/redi';
+
+import { setFormulaCalculationStartMutation } from '../commands/mutations/set-formula-calculation.mutation';
+
+const globalObject = typeof self !== 'undefined' ? self : window;
+
+@OnLifecycle(LifecycleStages.Ready, TriggerCalculationController)
+export class TriggerCalculationController extends Disposable {
+ private _waitingCommandQueue: ICommandInfo[] = [];
+
+ private _setTimeoutKey: number = -1;
+
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._commandExecutedListener();
+
+ this._initialExecuteFormulaResultListener();
+
+ this._initialExecuteFormulaProcessListener();
+ }
+
+ private _commandExecutedListener() {
+ const updateCommandList = [
+ SetRangeValuesMutation.id,
+ MoveRangeMutation.id,
+ MoveRowsMutation.id,
+ MoveColsMutation.id,
+ DeleteRangeMutation.id,
+ InsertRangeMutation.id,
+ RemoveRowMutation.id,
+ RemoveColMutation.id,
+ RemoveSheetMutation.id,
+ SetWorksheetNameMutation.id,
+ AddWorksheetMergeMutation.id,
+ ];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!updateCommandList.includes(command.id)) {
+ return;
+ }
+
+ if (command.id === SetRangeValuesMutation.id) {
+ const params = command.params as ISetRangeValuesMutationParams;
+
+ if (params.isFormulaUpdate === true || params.trigger === SetStyleCommand.id) {
+ return;
+ }
+ }
+
+ this._waitingCommandQueue.push(command);
+
+ globalObject.clearTimeout(this._setTimeoutKey);
+
+ this._setTimeoutKey = globalObject.setTimeout(() => {
+ this._commandService.executeCommand(setFormulaCalculationStartMutation.id, {
+ commands: this._waitingCommandQueue,
+ });
+ }, 100);
+ })
+ );
+ }
+
+ private _initialExecuteFormulaResultListener() {
+ /**
+ * Assignment operation after formula calculation.
+ */
+ this._formulaEngineService.executionCompleteListener$.subscribe((data) => {
+ const functionsExecutedState = data.functionsExecutedState;
+ switch (functionsExecutedState) {
+ case FormulaExecutedStateType.NOT_EXECUTED:
+ break;
+ case FormulaExecutedStateType.STOP_EXECUTION:
+ break;
+ case FormulaExecutedStateType.SUCCESS:
+ this._waitingCommandQueue = [];
+ console.log(`functions execute complete.`);
+ break;
+ case FormulaExecutedStateType.INITIAL:
+ break;
+ }
+ });
+ }
+
+ private _initialExecuteFormulaProcessListener() {
+ /**
+ * Assignment operation after formula calculation.
+ */
+ this._formulaEngineService.executionInProgressListener$.subscribe((data) => {
+ const {
+ totalFormulasToCalculate,
+ completedFormulasCount,
+ totalArrayFormulasToCalculate,
+ completedArrayFormulasCount,
+ stage,
+ } = data;
+
+ if (totalArrayFormulasToCalculate > 0) {
+ console.log(
+ `Stage ${stage} Array formula.There are ${totalArrayFormulasToCalculate} functions to be executed, ${completedArrayFormulasCount} complete.`
+ );
+ } else {
+ console.log(
+ `Stage ${stage} .There are ${totalFormulasToCalculate} functions to be executed, ${completedFormulasCount} complete.`
+ );
+ }
+ });
+ }
+}
diff --git a/packages/formula/src/controllers/update-formula.controller.ts b/packages/formula/src/controllers/update-formula.controller.ts
index 0fc3157342..92ccf6ff6a 100644
--- a/packages/formula/src/controllers/update-formula.controller.ts
+++ b/packages/formula/src/controllers/update-formula.controller.ts
@@ -1,36 +1,38 @@
-import type { ICellData, ICommandInfo, IRange, IUnitRange, Nullable, ObjectMatrixPrimitiveType } from '@univerjs/core';
+import type { ICellData, ICommandInfo, IRange, IUnitRange, Nullable } from '@univerjs/core';
import {
deserializeRangeWithSheet,
- Dimension,
Direction,
Disposable,
ICommandService,
+ isFormulaString,
IUniverInstanceService,
LifecycleStages,
ObjectMatrix,
OnLifecycle,
+ RANGE_TYPE,
Rectangle,
serializeRangeToRefString,
+ SheetInterceptorService,
+ Tools,
} from '@univerjs/core';
-import type {
- IFormulaData,
- IFormulaDataItem,
- ISequenceNode,
- ISheetData,
- IUnitData,
- IUnitSheetNameMap,
-} from '@univerjs/engine-formula';
+import type { IFormulaData, IFormulaDataItem, ISequenceNode, IUnitSheetNameMap } from '@univerjs/engine-formula';
import { FormulaEngineService, generateStringWithSequence, sequenceNodeType } from '@univerjs/engine-formula';
import type {
- IDeleteRangeMutationParams,
- IInsertRangeMutationParams,
- IMoveColumnsMutationParams,
- IMoveRowsMutationParams,
+ IDeleteRangeMoveLeftCommandParams,
+ IDeleteRangeMoveUpCommandParams,
+ IInsertColCommandParams,
+ IInsertRowCommandParams,
+ IMoveColsCommandParams,
+ IMoveRangeCommandParams,
+ IMoveRowsCommandParams,
+ InsertRangeMoveDownCommandParams,
+ InsertRangeMoveRightCommandParams,
+ IRemoveRowColCommandParams,
ISetRangeValuesMutationParams,
- MoveRangeMutationParams,
} from '@univerjs/sheets';
import {
- DeleteRangeMutation,
+ DeleteRangeMoveLeftCommand,
+ DeleteRangeMoveUpCommand,
EffectRefRangId,
handleDeleteRangeMoveLeft,
handleDeleteRangeMoveUp,
@@ -41,20 +43,26 @@ import {
handleIRemoveCol,
handleIRemoveRow,
handleMoveRange,
- InsertColMutation,
- InsertRangeMutation,
- InsertRowMutation,
- MoveColsMutation,
- MoveRangeMutation,
- MoveRowsMutation,
- RemoveColMutation,
- RemoveRowMutation,
+ InsertColCommand,
+ InsertRangeMoveDownCommand,
+ InsertRangeMoveRightCommand,
+ InsertRowCommand,
+ MoveColsCommand,
+ MoveRangeCommand,
+ MoveRowsCommand,
+ RemoveColCommand,
+ RemoveRowCommand,
runRefRangeMutations,
+ SelectionManagerService,
SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
} from '@univerjs/sheets';
-import { Inject } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
+import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';
import { FormulaDataModel } from '../models/formula-data.model';
+import { offsetArrayFormula, offsetFormula } from './utils';
interface IUnitRangeWithOffset extends IUnitRange {
refOffsetX: number;
@@ -91,18 +99,16 @@ enum OriginRangeEdgeType {
ALL,
}
-function getRangeFromMatrixObject(matrixObject: ObjectMatrixPrimitiveType<ICellData | null>) {
- const matrix = new ObjectMatrix(matrixObject);
- return matrix.getDataRange();
-}
-
-@OnLifecycle(LifecycleStages.Starting, UpdateFormulaController)
+@OnLifecycle(LifecycleStages.Ready, UpdateFormulaController)
export class UpdateFormulaController extends Disposable {
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
+ @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
+ @Inject(Injector) readonly _injector: Injector
) {
super();
@@ -113,239 +119,388 @@ export class UpdateFormulaController extends Disposable {
this._commandExecutedListener();
}
- /**
- * TODO: @DR-Univer Temporary method, will be deleted later.
- * @returns
- */
- private _getCalculateData() {
- const unitAllSheet = this._currentUniverService.getAllUniverSheetsInstance();
-
- const formulaData: IFormulaData = {};
-
- const allUnitData: IUnitData = {};
-
- const unitSheetNameMap: IUnitSheetNameMap = {};
+ private _commandExecutedListener() {
+ this.disposeWithMe(
+ this._sheetInterceptorService.interceptCommand({
+ getMutations: (command) => this._getUpdateFormula(command),
+ })
+ );
- for (const workbook of unitAllSheet) {
- const unitId = workbook.getUnitId();
- if (formulaData[unitId] == null) {
- formulaData[unitId] = {};
- }
- const sheets = workbook.getSheets();
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ // Synchronous data from worker
+ if (command.id === SetRangeValuesMutation.id) {
+ const params = command.params as ISetRangeValuesMutationParams;
- const workbookFormulaData = formulaData[unitId];
+ const { worksheetId: sheetId, workbookId: unitId, cellValue, isFormulaUpdate } = params;
- const sheetData: ISheetData = {};
+ if (isFormulaUpdate === true || cellValue == null) {
+ return;
+ }
- const sheetNameMap: { [sheetName: string]: string } = {};
+ this._formulaDataModel.updateFormulaData(unitId, sheetId, cellValue);
- for (const sheet of sheets) {
- const sheetId = sheet.getSheetId();
- if (workbookFormulaData[sheetId] == null) {
- workbookFormulaData[sheetId] = {};
+ this._commandService.executeCommand(SetFormulaDataMutation.id, {
+ formulaData: this._formulaDataModel.getFormulaData(),
+ });
}
+ })
+ );
+ }
- const sheetFormulaData = workbookFormulaData[sheetId];
+ private _getUpdateFormula(command: ICommandInfo) {
+ const { id } = command;
+ let result: Nullable<IFormulaReferenceMoveParam> = null;
+
+ switch (id) {
+ case MoveRangeCommand.id:
+ result = this._handleMoveRange(command as ICommandInfo<IMoveRangeCommandParams>);
+ break;
+ case MoveRowsCommand.id:
+ result = this._handleMoveRows(command as ICommandInfo<IMoveRowsCommandParams>);
+ break;
+ case MoveColsCommand.id:
+ result = this._handleMoveCols(command as ICommandInfo<IMoveColsCommandParams>);
+ break;
+ case InsertRowCommand.id:
+ result = this._handleInsertRow(command as ICommandInfo<IInsertRowCommandParams>);
+ break;
+ case InsertColCommand.id:
+ result = this._handleInsertCol(command as ICommandInfo<IInsertColCommandParams>);
+ break;
+ case InsertRangeMoveRightCommand.id:
+ result = this._handleInsertRangeMoveRight(command as ICommandInfo<InsertRangeMoveRightCommandParams>);
+ break;
+ case InsertRangeMoveDownCommand.id:
+ result = this._handleInsertRangeMoveDown(command as ICommandInfo<InsertRangeMoveDownCommandParams>);
+ break;
+ case RemoveRowCommand.id:
+ result = this._handleRemoveRow(command as ICommandInfo<IRemoveRowColCommandParams>);
+ break;
+ case RemoveColCommand.id:
+ result = this._handleRemoveCol(command as ICommandInfo<IRemoveRowColCommandParams>);
+ break;
+ case DeleteRangeMoveUpCommand.id:
+ result = this._handleDeleteRangeMoveUp(command as ICommandInfo<IDeleteRangeMoveUpCommandParams>);
+ break;
+ case DeleteRangeMoveLeftCommand.id:
+ result = this._handleDeleteRangeMoveLeft(command as ICommandInfo<IDeleteRangeMoveLeftCommandParams>);
+ break;
+ }
- const cellDatas = sheet.getCellMatrix();
+ if (result) {
+ const { unitSheetNameMap } = this._formulaDataModel.getCalculateData();
+ let oldFormulaData = this._formulaDataModel.getFormulaData();
- cellDatas.forValue((row, column, cellData) => {
- if (cellData?.f != null) {
- if (sheetFormulaData[row] == null) {
- sheetFormulaData[row] = {};
- }
- sheetFormulaData[row][column] = {
- f: cellData.f,
- x: 0,
- y: 0,
- };
- }
- });
+ // change formula reference
+ const formulaData = this._getFormulaReferenceMoveInfo(oldFormulaData, unitSheetNameMap, result);
- const sheetConfig = sheet.getConfig();
- sheetData[sheetId] = {
- cellData: new ObjectMatrix(sheetConfig.cellData),
- rowCount: sheetConfig.rowCount,
- columnCount: sheetConfig.columnCount,
- };
- sheetNameMap[sheet.getName()] = sheet.getSheetId();
- }
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const unitId = workbook.getUnitId();
+ const sheetId = workbook.getActiveSheet().getSheetId();
+ const selections = this._selectionManagerService.getSelections();
+
+ // offset arrayFormula
+ const arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();
+ const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();
+
+ let offsetArrayFormulaRange = offsetFormula(arrayFormulaRange, command, unitId, sheetId, selections);
+ offsetArrayFormulaRange = offsetArrayFormula(offsetArrayFormulaRange, unitId, sheetId);
+ const offsetArrayFormulaCellData = offsetFormula(
+ arrayFormulaCellData,
+ command,
+ unitId,
+ sheetId,
+ selections
+ );
+
+ // Synchronous to the worker thread
+ this._commandService.executeCommand(SetArrayFormulaDataMutation.id, {
+ arrayFormulaRange: offsetArrayFormulaRange,
+ arrayFormulaCellData: offsetArrayFormulaCellData,
+ });
- allUnitData[unitId] = sheetData;
+ // offset formulaData
+ oldFormulaData = offsetFormula(oldFormulaData, command, unitId, sheetId, selections);
+ const offsetFormulaData = offsetFormula(formulaData, command, unitId, sheetId, selections);
- unitSheetNameMap[unitId] = sheetNameMap;
+ return this._getUpdateFormulaMutations(oldFormulaData, offsetFormulaData);
}
return {
- formulaData,
- allUnitData,
- unitSheetNameMap,
+ undos: [],
+ redos: [],
};
}
- private _commandExecutedListener() {
- const updateCommandList = [
- MoveRangeMutation.id,
- MoveRowsMutation.id,
- MoveColsMutation.id,
- InsertRangeMutation.id,
- InsertRowMutation.id,
- InsertColMutation.id,
- DeleteRangeMutation.id,
- RemoveRowMutation.id,
- RemoveColMutation.id,
- ];
+ private _handleMoveRange(command: ICommandInfo<IMoveRangeCommandParams>) {
+ const { params } = command;
+ if (!params) return null;
- this.disposeWithMe(
- this._commandService.onCommandExecuted((command: ICommandInfo) => {
- const { id } = command;
- let result: Nullable<IFormulaReferenceMoveParam> = null;
-
- // TODO@Dushusir: handle cut operation, same as move operation
- switch (id) {
- case MoveRangeMutation.id:
- result = this._handleMoveRange(command as ICommandInfo<MoveRangeMutationParams>);
- break;
- case MoveRowsMutation.id:
- result = this._handleMoveRows(command as ICommandInfo<IMoveRowsMutationParams>);
- break;
- case MoveColsMutation.id:
- result = this._handleMoveCols(command as ICommandInfo<IMoveColumnsMutationParams>);
- break;
- case InsertRangeMutation.id:
- result = this._handleInsertRange(command as ICommandInfo<IInsertRangeMutationParams>);
- break;
- case DeleteRangeMutation.id:
- result = this._handleDeleteRange(command as ICommandInfo<IDeleteRangeMutationParams>);
- break;
- }
+ const { fromRange, toRange } = params;
+ if (!fromRange || !toRange) return null;
- // TODO@Dushusir: update formula and get update cell data matrix
- if (result) {
- const state = this._getCalculateData();
- this.getFormulaReferenceMoveInfo(state.formulaData, state.unitSheetNameMap, result).then(
- (cellValue) => {
- this._updateFormula(cellValue);
- }
- );
- }
- })
- );
+ const { unitId, sheetId } = this._getCurrentSheetInfo();
+
+ return {
+ type: FormulaReferenceMoveType.Move,
+ from: fromRange,
+ to: toRange,
+ unitId,
+ sheetId,
+ };
}
- private _handleMoveRange(command: ICommandInfo<MoveRangeMutationParams>) {
+ private _handleMoveRows(command: ICommandInfo<IMoveRowsCommandParams>) {
const { params } = command;
if (!params) return null;
- const { from, to, workbookId, worksheetId } = params;
- if (!from || !to) return null;
+ const { fromRow, toRow } = params;
+
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const unitId = workbook.getUnitId();
+ const worksheet = workbook.getActiveSheet();
+ const sheetId = worksheet.getSheetId();
+
+ const from = {
+ startRow: fromRow,
+ startColumn: 0,
+ endRow: fromRow,
+ endColumn: worksheet.getColumnCount() - 1,
+ rangeType: RANGE_TYPE.ROW,
+ };
+ const to = {
+ startRow: toRow,
+ startColumn: 0,
+ endRow: toRow,
+ endColumn: worksheet.getColumnCount() - 1,
+ rangeType: RANGE_TYPE.ROW,
+ };
return {
type: FormulaReferenceMoveType.Move,
- from: getRangeFromMatrixObject(from),
- to: getRangeFromMatrixObject(to),
- unitId: workbookId,
- sheetId: worksheetId,
+ from,
+ to,
+ unitId,
+ sheetId,
};
}
- private _handleMoveRows(command: ICommandInfo<IMoveRowsMutationParams>) {
+ private _handleMoveCols(command: ICommandInfo<IMoveColsCommandParams>) {
const { params } = command;
if (!params) return null;
- const { sourceRange, targetRange, workbookId, worksheetId } = params;
+ const { fromCol, toCol } = params;
+
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const unitId = workbook.getUnitId();
+ const worksheet = workbook.getActiveSheet();
+ const sheetId = worksheet.getSheetId();
+
+ const from = {
+ startRow: 0,
+ startColumn: fromCol,
+ endRow: worksheet.getRowCount() - 1,
+ endColumn: fromCol,
+ rangeType: RANGE_TYPE.COLUMN,
+ };
+ const to = {
+ startRow: 0,
+ startColumn: toCol,
+ endRow: worksheet.getRowCount() - 1,
+ endColumn: toCol,
+ rangeType: RANGE_TYPE.COLUMN,
+ };
+
return {
type: FormulaReferenceMoveType.Move,
- from: sourceRange,
- to: targetRange,
+ from,
+ to,
+ unitId,
+ sheetId,
+ };
+ }
+
+ private _handleInsertRow(command: ICommandInfo<IInsertRowCommandParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { range, workbookId, worksheetId } = params;
+ return {
+ type: FormulaReferenceMoveType.InsertRow,
+ ranges: [range],
unitId: workbookId,
sheetId: worksheetId,
};
}
- private _handleMoveCols(command: ICommandInfo<IMoveColumnsMutationParams>) {
+ private _handleInsertCol(command: ICommandInfo<IInsertColCommandParams>) {
const { params } = command;
if (!params) return null;
- const { sourceRange, targetRange, workbookId, worksheetId } = params;
+ const { range, workbookId, worksheetId } = params;
return {
- type: FormulaReferenceMoveType.Move,
- from: sourceRange,
- to: targetRange,
+ type: FormulaReferenceMoveType.InsertColumn,
+ ranges: [range],
unitId: workbookId,
sheetId: worksheetId,
};
}
- private _handleInsertRange(command: ICommandInfo<IInsertRangeMutationParams>) {
+ private _handleInsertRangeMoveRight(command: ICommandInfo<InsertRangeMoveRightCommandParams>) {
const { params } = command;
if (!params) return null;
- const { ranges, shiftDimension, workbookId, worksheetId } = params;
+ const { ranges } = params;
+ const { unitId, sheetId } = this._getCurrentSheetInfo();
- if (shiftDimension === Dimension.ROWS) {
- return {
- type: FormulaReferenceMoveType.InsertMoveDown,
- ranges,
- unitId: workbookId,
- sheetId: worksheetId,
- };
- }
- if (shiftDimension === Dimension.COLUMNS) {
- return {
- type: FormulaReferenceMoveType.InsertMoveRight,
- ranges,
- unitId: workbookId,
- sheetId: worksheetId,
- };
- }
+ return {
+ type: FormulaReferenceMoveType.InsertMoveRight,
+ ranges,
+ unitId,
+ sheetId,
+ };
}
- private _handleDeleteRange(command: ICommandInfo<IDeleteRangeMutationParams>) {
+ private _handleInsertRangeMoveDown(command: ICommandInfo<InsertRangeMoveDownCommandParams>) {
const { params } = command;
if (!params) return null;
- const { ranges, shiftDimension, workbookId, worksheetId } = params;
+ const { ranges } = params;
+ const { unitId, sheetId } = this._getCurrentSheetInfo();
- if (shiftDimension === Dimension.ROWS) {
- return {
- type: FormulaReferenceMoveType.DeleteMoveUp,
- ranges,
- unitId: workbookId,
- sheetId: worksheetId,
- };
- }
- if (shiftDimension === Dimension.COLUMNS) {
- return {
- type: FormulaReferenceMoveType.DeleteMoveLeft,
- ranges,
- unitId: workbookId,
- sheetId: worksheetId,
- };
- }
+ return {
+ type: FormulaReferenceMoveType.InsertMoveDown,
+ ranges,
+ unitId,
+ sheetId,
+ };
}
- private _updateFormula(formulaData: ObjectMatrixPrimitiveType<ICellData>) {
- const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
- const workbookId = workbook.getUnitId();
- const worksheetId = workbook.getActiveSheet().getSheetId();
+ private _handleRemoveRow(command: ICommandInfo<IRemoveRowColCommandParams>) {
+ const { params } = command;
+ if (!params) return null;
- const cellValue = formulaData['workbook-01' as any]['sheet-0011' as any] as any;
+ const { ranges } = params;
+ const { unitId, sheetId } = this._getCurrentSheetInfo();
- if (cellValue == null) {
- return;
- }
+ return {
+ type: FormulaReferenceMoveType.RemoveRow,
+ ranges,
+ unitId,
+ sheetId,
+ };
+ }
+
+ private _handleRemoveCol(command: ICommandInfo<IRemoveRowColCommandParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { ranges } = params;
+ const { unitId, sheetId } = this._getCurrentSheetInfo();
+
+ return {
+ type: FormulaReferenceMoveType.RemoveColumn,
+ ranges,
+ unitId,
+ sheetId,
+ };
+ }
+
+ private _handleDeleteRangeMoveUp(command: ICommandInfo<IDeleteRangeMoveUpCommandParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { ranges } = params;
+ const { unitId, sheetId } = this._getCurrentSheetInfo();
+
+ return {
+ type: FormulaReferenceMoveType.DeleteMoveUp,
+ ranges,
+ unitId,
+ sheetId,
+ };
+ }
+
+ private _handleDeleteRangeMoveLeft(command: ICommandInfo<IDeleteRangeMoveLeftCommandParams>) {
+ const { params } = command;
+ if (!params) return null;
+
+ const { ranges } = params;
+ const { unitId, sheetId } = this._getCurrentSheetInfo();
- const setRangeValuesMutation: ISetRangeValuesMutationParams = {
- worksheetId: 'sheet-0011',
- workbookId: 'workbook-01',
- cellValue,
+ return {
+ type: FormulaReferenceMoveType.DeleteMoveLeft,
+ ranges,
+ unitId,
+ sheetId,
};
+ }
+
+ private _getUpdateFormulaMutations(oldFormulaData: IFormulaData, formulaData: IFormulaData) {
+ const redos = [];
+ const undos = [];
+ const accessor = {
+ get: this._injector.get.bind(this._injector),
+ };
+
+ const formulaDataKeys = Object.keys(formulaData);
- this._commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutation);
+ for (const workbookId of formulaDataKeys) {
+ const sheetData = formulaData[workbookId];
+ const sheetDataKeys = Object.keys(sheetData);
+
+ for (const worksheetId of sheetDataKeys) {
+ const oldFormulaMatrix = new ObjectMatrix<IFormulaDataItem>(oldFormulaData[workbookId][worksheetId]);
+ const formulaMatrix = new ObjectMatrix<IFormulaDataItem>(sheetData[worksheetId]);
+ const cellMatrix = new ObjectMatrix<ICellData>();
+
+ formulaMatrix.forValue((r, c, formulaItem) => {
+ const formulaString = formulaItem?.f || '';
+ const oldFormulaString = oldFormulaMatrix.getRow(r)?.get(c)?.f || '';
+
+ if (isFormulaString(formulaString)) {
+ // formula with formula id
+ if (isFormulaString(oldFormulaString) && formulaString !== oldFormulaString) {
+ cellMatrix.setValue(r, c, { f: formulaString });
+ } else {
+ // formula with only id
+ cellMatrix.setValue(r, c, { f: formulaString, si: null });
+ }
+ }
+ });
+
+ const cellValue = cellMatrix.getData();
+ if (Tools.isEmptyObject(cellValue)) continue;
+
+ const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {
+ worksheetId,
+ workbookId,
+ cellValue,
+ };
+
+ redos.push({
+ id: SetRangeValuesMutation.id,
+ params: setRangeValuesMutationParams,
+ });
+
+ const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams =
+ SetRangeValuesUndoMutationFactory(accessor, setRangeValuesMutationParams);
+
+ undos.push({
+ id: SetRangeValuesMutation.id,
+ params: undoSetRangeValuesMutationParams,
+ });
+ }
+ }
+
+ return {
+ redos,
+ undos,
+ };
}
- async getFormulaReferenceMoveInfo(
+ private _getFormulaReferenceMoveInfo(
formulaData: IFormulaData,
unitSheetNameMap: IUnitSheetNameMap,
formulaReferenceMoveParam: IFormulaReferenceMoveParam
@@ -934,4 +1089,15 @@ export class UpdateFormulaController extends Disposable {
}
private _getInsertNewRange() {}
+
+ private _getCurrentSheetInfo() {
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const unitId = workbook.getUnitId();
+ const sheetId = workbook.getActiveSheet().getSheetId();
+
+ return {
+ unitId,
+ sheetId,
+ };
+ }
}
diff --git a/packages/formula/src/controllers/utils.ts b/packages/formula/src/controllers/utils.ts
new file mode 100644
index 0000000000..d648328bbd
--- /dev/null
+++ b/packages/formula/src/controllers/utils.ts
@@ -0,0 +1,293 @@
+import type { ICommandInfo, Nullable, ObjectMatrixPrimitiveType } from '@univerjs/core';
+import { Dimension, ObjectMatrix, RANGE_TYPE } from '@univerjs/core';
+import type { IArrayFormulaRangeType } from '@univerjs/engine-formula';
+import type {
+ IDeleteRangeMoveLeftCommandParams,
+ IDeleteRangeMoveUpCommandParams,
+ IInsertColCommandParams,
+ IInsertRowCommandParams,
+ IMoveColsCommandParams,
+ IMoveRangeCommandParams,
+ IMoveRowsCommandParams,
+ InsertRangeMoveDownCommandParams,
+ InsertRangeMoveRightCommandParams,
+ IRemoveRowColCommandParams,
+ ISelectionWithStyle,
+} from '@univerjs/sheets';
+import {
+ DeleteRangeMoveLeftCommand,
+ DeleteRangeMoveUpCommand,
+ handleDeleteRangeMutation,
+ handleInsertRangeMutation,
+ InsertColCommand,
+ InsertRangeMoveDownCommand,
+ InsertRangeMoveRightCommand,
+ InsertRowCommand,
+ MoveColsCommand,
+ MoveRangeCommand,
+ MoveRowsCommand,
+ RemoveColCommand,
+ RemoveRowCommand,
+} from '@univerjs/sheets';
+
+interface IFormulaDataGenerics<T> {
+ [unitId: string]: { [sheetId: string]: ObjectMatrixPrimitiveType<T> };
+}
+
+export function offsetFormula<T>(
+ formulaData: IFormulaDataGenerics<T>,
+ command: ICommandInfo,
+ unitId: string,
+ sheetId: string,
+ selections?: Readonly<Nullable<ISelectionWithStyle[]>>
+): IFormulaDataGenerics<T> {
+ const { id } = command;
+
+ const formulaMatrix = new ObjectMatrix(formulaData[unitId][sheetId]);
+
+ switch (id) {
+ case MoveRangeCommand.id:
+ handleMoveRange<T>(formulaMatrix, command as ICommandInfo<IMoveRangeCommandParams>);
+ break;
+ case MoveRowsCommand.id:
+ handleMoveRows<T>(formulaMatrix, command as ICommandInfo<IMoveRowsCommandParams>, selections);
+ break;
+ case MoveColsCommand.id:
+ handleMoveCols<T>(formulaMatrix, command as ICommandInfo<IMoveColsCommandParams>, selections);
+ break;
+ case InsertRowCommand.id:
+ handleInsertRow<T>(formulaMatrix, command as ICommandInfo<IInsertRowCommandParams>);
+ break;
+ case InsertColCommand.id:
+ handleInsertCol<T>(formulaMatrix, command as ICommandInfo<IInsertColCommandParams>);
+ break;
+ case InsertRangeMoveRightCommand.id:
+ handleInsertRangeMoveRight<T>(formulaMatrix, command as ICommandInfo<InsertRangeMoveRightCommandParams>);
+ break;
+ case InsertRangeMoveDownCommand.id:
+ handleInsertRangeMoveDown<T>(formulaMatrix, command as ICommandInfo<InsertRangeMoveDownCommandParams>);
+ break;
+ case RemoveRowCommand.id:
+ handleRemoveRow<T>(formulaMatrix, command as ICommandInfo<IRemoveRowColCommandParams>);
+ break;
+ case RemoveColCommand.id:
+ handleRemoveCol<T>(formulaMatrix, command as ICommandInfo<IRemoveRowColCommandParams>);
+ break;
+ case DeleteRangeMoveUpCommand.id:
+ handleDeleteRangeMoveUp<T>(formulaMatrix, command as ICommandInfo<IDeleteRangeMoveUpCommandParams>);
+ break;
+ case DeleteRangeMoveLeftCommand.id:
+ handleDeleteRangeMoveLeft<T>(formulaMatrix, command as ICommandInfo<IDeleteRangeMoveLeftCommandParams>);
+ break;
+ }
+
+ return formulaData;
+}
+
+function handleMoveRange<T>(formulaMatrix: ObjectMatrix<T>, command: ICommandInfo<IMoveRangeCommandParams>) {
+ const { params } = command;
+ if (!params) return;
+
+ const { fromRange, toRange } = params;
+ const {
+ startRow: fromStartRow,
+ endRow: fromEndRow,
+ startColumn: fromStartColumn,
+ endColumn: fromEndColumn,
+ } = fromRange;
+ const { startRow: toStartRow, endRow: toEndRow, startColumn: toStartColumn, endColumn: toEndColumn } = toRange;
+
+ const cacheMatrix = new ObjectMatrix<T>();
+
+ for (let r = fromStartRow; r <= fromEndRow; r++) {
+ for (let c = fromStartColumn; c <= fromEndColumn; c++) {
+ const cacheValue = formulaMatrix.getValue(r, c);
+ cacheMatrix.setValue(r - fromStartRow, c - fromStartColumn, cacheValue);
+
+ formulaMatrix.setValue(r, c, null);
+ }
+ }
+
+ for (let r = toStartRow; r <= toEndRow; r++) {
+ for (let c = toStartColumn; c <= toEndColumn; c++) {
+ const cacheValue = cacheMatrix.getValue(r - toStartRow, c - toStartColumn);
+ formulaMatrix.setValue(r, c, cacheValue);
+ }
+ }
+}
+
+function handleMoveRows<T>(
+ formulaMatrix: ObjectMatrix<T>,
+ command: ICommandInfo<IMoveRowsCommandParams>,
+ selections?: Readonly<Nullable<ISelectionWithStyle[]>>
+) {
+ const { params } = command;
+ if (!params) return;
+
+ const { fromRow, toRow } = params;
+
+ const filteredSelections = selections?.filter(
+ (selection) =>
+ selection.range.rangeType === RANGE_TYPE.ROW &&
+ selection.range.startRow <= fromRow &&
+ fromRow <= selection.range.endRow
+ );
+
+ if (filteredSelections?.length !== 1) return;
+
+ const rangeToMove = filteredSelections[0].range;
+ const fromRowNumber = rangeToMove.startRow;
+ const count = rangeToMove.endRow - rangeToMove.startRow + 1;
+
+ formulaMatrix.moveRows(fromRowNumber, count, toRow);
+}
+
+function handleMoveCols<T>(
+ formulaMatrix: ObjectMatrix<T>,
+ command: ICommandInfo<IMoveColsCommandParams>,
+ selections?: Readonly<Nullable<ISelectionWithStyle[]>>
+) {
+ const { params } = command;
+ if (!params) return;
+
+ const { fromCol, toCol } = params;
+
+ const filteredSelections = selections?.filter(
+ (selection) =>
+ selection.range.rangeType === RANGE_TYPE.COLUMN &&
+ selection.range.startColumn <= fromCol &&
+ fromCol <= selection.range.endColumn
+ );
+
+ if (filteredSelections?.length !== 1) return;
+
+ const rangeToMove = filteredSelections[0].range;
+ const fromColNumber = rangeToMove.startColumn;
+ const count = rangeToMove.endColumn - rangeToMove.startColumn + 1;
+
+ formulaMatrix.moveColumns(fromColNumber, count, toCol);
+}
+
+function handleInsertRow<T>(formulaMatrix: ObjectMatrix<T>, command: ICommandInfo<IInsertRowCommandParams>) {
+ const { params } = command;
+ if (!params) return;
+
+ const { range } = params;
+ const lastEndRow = formulaMatrix.getLength() - 1;
+ const lastEndColumn = formulaMatrix.getRange().endColumn;
+
+ handleInsertRangeMutation(formulaMatrix, [range], lastEndRow, lastEndColumn, Dimension.ROWS);
+}
+
+function handleInsertCol<T>(formulaMatrix: ObjectMatrix<T>, command: ICommandInfo<IInsertColCommandParams>) {
+ const { params } = command;
+ if (!params) return;
+
+ const { range } = params;
+ const lastEndRow = formulaMatrix.getLength() - 1;
+ const lastEndColumn = formulaMatrix.getRange().endColumn;
+
+ handleInsertRangeMutation(formulaMatrix, [range], lastEndRow, lastEndColumn, Dimension.COLUMNS);
+}
+
+function handleInsertRangeMoveRight<T>(
+ formulaMatrix: ObjectMatrix<T>,
+ command: ICommandInfo<InsertRangeMoveRightCommandParams>
+) {
+ const { params } = command;
+ if (!params) return;
+
+ const { ranges } = params;
+ const lastEndRow = formulaMatrix.getLength() - 1;
+ const lastEndColumn = formulaMatrix.getRange().endColumn;
+
+ handleInsertRangeMutation(formulaMatrix, ranges, lastEndRow, lastEndColumn, Dimension.COLUMNS);
+}
+
+function handleInsertRangeMoveDown<T>(
+ formulaMatrix: ObjectMatrix<T>,
+ command: ICommandInfo<InsertRangeMoveDownCommandParams>
+) {
+ const { params } = command;
+ if (!params) return;
+
+ const { ranges } = params;
+ const lastEndRow = formulaMatrix.getLength() - 1;
+ const lastEndColumn = formulaMatrix.getRange().endColumn;
+
+ handleInsertRangeMutation(formulaMatrix, ranges, lastEndRow, lastEndColumn, Dimension.ROWS);
+}
+
+function handleRemoveRow<T>(formulaMatrix: ObjectMatrix<T>, command: ICommandInfo<IRemoveRowColCommandParams>) {
+ const { params } = command;
+ if (!params) return;
+
+ const { ranges } = params;
+ const lastEndRow = formulaMatrix.getLength() - 1;
+ const lastEndColumn = formulaMatrix.getRange().endColumn;
+
+ handleDeleteRangeMutation(formulaMatrix, ranges, lastEndRow, lastEndColumn, Dimension.ROWS);
+}
+
+function handleRemoveCol<T>(formulaMatrix: ObjectMatrix<T>, command: ICommandInfo<IRemoveRowColCommandParams>) {
+ const { params } = command;
+ if (!params) return;
+
+ const { ranges } = params;
+ const lastEndRow = formulaMatrix.getLength() - 1;
+ const lastEndColumn = formulaMatrix.getRange().endColumn;
+
+ handleDeleteRangeMutation(formulaMatrix, ranges, lastEndRow, lastEndColumn, Dimension.COLUMNS);
+}
+
+function handleDeleteRangeMoveUp<T>(
+ formulaMatrix: ObjectMatrix<T>,
+ command: ICommandInfo<IDeleteRangeMoveUpCommandParams>
+) {
+ const { params } = command;
+ if (!params) return;
+
+ const { ranges } = params;
+ const lastEndRow = formulaMatrix.getLength() - 1;
+ const lastEndColumn = formulaMatrix.getRange().endColumn;
+
+ handleDeleteRangeMutation(formulaMatrix, ranges, lastEndRow, lastEndColumn, Dimension.ROWS);
+}
+
+function handleDeleteRangeMoveLeft<T>(
+ formulaMatrix: ObjectMatrix<T>,
+ command: ICommandInfo<IDeleteRangeMoveLeftCommandParams>
+) {
+ const { params } = command;
+ if (!params) return;
+
+ const { ranges } = params;
+ const lastEndRow = formulaMatrix.getLength() - 1;
+ const lastEndColumn = formulaMatrix.getRange().endColumn;
+
+ handleDeleteRangeMutation(formulaMatrix, ranges, lastEndRow, lastEndColumn, Dimension.COLUMNS);
+}
+
+export function offsetArrayFormula(arrayFormulaRange: IArrayFormulaRangeType, unitId: string, sheetId: string) {
+ const arrayFormulaRangeMatrix = new ObjectMatrix(arrayFormulaRange[unitId][sheetId]);
+ arrayFormulaRangeMatrix.forValue((row, column, range) => {
+ const { startRow, startColumn, endRow, endColumn } = range;
+ if (row === startRow && column === startColumn) {
+ return;
+ }
+
+ const rows = endRow - startRow;
+ const columns = endColumn - startColumn;
+
+ const newRange = {
+ startRow: row,
+ startColumn: column,
+ endRow: row + rows,
+ endColumn: column + columns,
+ };
+
+ arrayFormulaRangeMatrix.setValue(row, column, newRange);
+ });
+
+ return arrayFormulaRange;
+}
diff --git a/packages/formula/src/formula-plugin.ts b/packages/formula/src/formula-plugin.ts
index f81e83bf09..e900ee8e80 100644
--- a/packages/formula/src/formula-plugin.ts
+++ b/packages/formula/src/formula-plugin.ts
@@ -3,11 +3,14 @@ import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { FORMULA_PLUGIN_NAME } from './common/plugin-name';
+import { ArrayFormulaDisplayController } from './controllers/array-formula-display.controller';
import { CalculateController } from './controllers/calculate.controller';
import { FormulaController } from './controllers/formula.controller';
+import { TriggerCalculationController } from './controllers/trigger-calculation.controller';
import { UpdateFormulaController } from './controllers/update-formula.controller';
import type { IFormulaConfig } from './models/formula-data.model';
import { FormulaDataModel } from './models/formula-data.model';
+import { FormulaService, IFormulaService } from './services/formula.service';
export class FormulaPlugin extends Plugin {
static override type = PluginType.Sheet;
@@ -23,16 +26,23 @@ export class FormulaPlugin extends Plugin {
initialize(): void {
this._formulaDataModel = this._injector.createInstance(FormulaDataModel);
+
+ // main thread and worker
const dependencies: Dependency[] = [
+ // [IFormulaService, { useFactory: () => this._injector.createInstance(FormulaService) }],
// models
[FormulaDataModel, { useValue: this._formulaDataModel }],
// controllers
[FormulaController],
+ [UpdateFormulaController],
+ [ArrayFormulaDisplayController],
+ [TriggerCalculationController],
];
+ // only worker
if (!this._config?.notExecuteFormula) {
+ dependencies.push([IFormulaService, { useClass: FormulaService }]);
dependencies.push([CalculateController]);
- dependencies.push([UpdateFormulaController]);
}
dependencies.forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/formula/src/index.ts b/packages/formula/src/index.ts
index e414a2e00a..ae61b70012 100644
--- a/packages/formula/src/index.ts
+++ b/packages/formula/src/index.ts
@@ -1 +1,14 @@
export { FormulaPlugin } from './formula-plugin';
+export { FUNCTION_NAMES_ARRAY } from './services/function-list/array/function-names';
+export { FUNCTION_NAMES_COMPATIBILITY } from './services/function-list/compatibility/function-names';
+export { FUNCTION_NAMES_CUBE } from './services/function-list/cube/function-names';
+export { FUNCTION_NAMES_DATABASE } from './services/function-list/database/function-names';
+export { FUNCTION_NAMES_ENGINEERING } from './services/function-list/engineering/function-names';
+export { FUNCTION_NAMES_FINANCIAL } from './services/function-list/financial/function-names';
+export { FUNCTION_NAMES_INFORMATION } from './services/function-list/information/function-names';
+export { FUNCTION_NAMES_LOOKUP } from './services/function-list/lookup/function-names';
+export { FUNCTION_NAMES_MATH } from './services/function-list/math/function-names';
+export { FUNCTION_NAMES_STATISTICAL } from './services/function-list/statistical/function-names';
+export { FUNCTION_NAMES_TEXT } from './services/function-list/text/function-names';
+export { FUNCTION_NAMES_UNIVER } from './services/function-list/univer/function-names';
+export { FUNCTION_NAMES_WEB } from './services/function-list/web/function-names';
diff --git a/packages/formula/src/models/formula-data.model.ts b/packages/formula/src/models/formula-data.model.ts
index 33952e3b5b..9a2a7991e9 100644
--- a/packages/formula/src/models/formula-data.model.ts
+++ b/packages/formula/src/models/formula-data.model.ts
@@ -1,5 +1,22 @@
-import { Disposable, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
-import type { ArrayFormulaDataType, IFormulaData, IFormulaDataItem } from '@univerjs/engine-formula';
+import type { ICellData, IRange, ObjectMatrixPrimitiveType } from '@univerjs/core';
+import {
+ Disposable,
+ ICommandService,
+ isFormulaId,
+ isFormulaString,
+ IUniverInstanceService,
+ ObjectMatrix,
+} from '@univerjs/core';
+import type {
+ IArrayFormulaRangeType,
+ IArrayFormulaUnitCellType,
+ IFormulaData,
+ IFormulaDataItem,
+ IRuntimeUnitDataType,
+ ISheetData,
+ IUnitData,
+ IUnitSheetNameMap,
+} from '@univerjs/engine-formula';
export interface IFormulaConfig {
notExecuteFormula?: boolean;
@@ -10,12 +27,106 @@ export interface IFormulaConfig {
export class FormulaDataModel extends Disposable {
private _formulaData: IFormulaData = {};
- private _arrayFormulaData: ArrayFormulaDataType = {};
+ private _arrayFormulaRange: IArrayFormulaRangeType = {};
- constructor(@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService) {
+ private _arrayFormulaCellData: IArrayFormulaUnitCellType = {};
+
+ constructor(
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
super();
}
+ clearPreviousArrayFormulaCellData(clearArrayFormulaCellData: IRuntimeUnitDataType) {
+ Object.keys(clearArrayFormulaCellData).forEach((unitId) => {
+ const sheetData = clearArrayFormulaCellData[unitId];
+ Object.keys(sheetData).forEach((sheetId) => {
+ const cellMatrixData = sheetData[sheetId];
+ const rangeMatrix = this._arrayFormulaRange?.[unitId]?.[sheetId];
+ if (rangeMatrix == null) {
+ return true;
+ }
+
+ let arrayFormulaCellMatrixData = new ObjectMatrix<ICellData>(); // Original array formula cell data.
+
+ if (this._arrayFormulaCellData[unitId][sheetId] != null) {
+ arrayFormulaCellMatrixData = new ObjectMatrix<ICellData>(
+ this._arrayFormulaCellData[unitId][sheetId]
+ );
+ }
+
+ cellMatrixData.forValue((row, column) => {
+ const range = rangeMatrix?.[row]?.[column];
+ if (range == null) {
+ return true;
+ }
+ const { startRow, startColumn, endRow, endColumn } = range;
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ arrayFormulaCellMatrixData.setValue(r, c, null);
+ }
+ }
+ });
+
+ this._arrayFormulaCellData[unitId][sheetId] = arrayFormulaCellMatrixData.getData();
+ });
+ });
+ }
+
+ mergeArrayFormulaCellData(unitData: IRuntimeUnitDataType) {
+ Object.keys(unitData).forEach((unitId) => {
+ const sheetData = unitData[unitId];
+ if (this._arrayFormulaRange[unitId] == null) {
+ this._arrayFormulaRange[unitId] = {};
+ }
+
+ if (this._arrayFormulaCellData[unitId] == null) {
+ this._arrayFormulaCellData[unitId] = {};
+ }
+
+ Object.keys(sheetData).forEach((sheetId) => {
+ const cellMatrixData = sheetData[sheetId]; // The runtime data for array formula value calculated by the formula engine.
+
+ let arrayFormulaRangeMatrix = new ObjectMatrix<IRange>(); // Original array formula range.
+
+ let arrayFormulaCellMatrixData = new ObjectMatrix<ICellData>(); // Original array formula cell data.
+
+ if (this._arrayFormulaRange[unitId][sheetId] != null) {
+ arrayFormulaRangeMatrix = new ObjectMatrix<IRange>(this._arrayFormulaRange[unitId][sheetId]);
+ }
+
+ if (this._arrayFormulaCellData[unitId][sheetId] != null) {
+ arrayFormulaCellMatrixData = new ObjectMatrix<ICellData>(
+ this._arrayFormulaCellData[unitId][sheetId]
+ );
+ }
+
+ /**
+ * If the calculated value of the array formula is updated, clear the values within the original data formula range.
+ */
+ cellMatrixData.forValue((row, column) => {
+ const arrayFormulaRange = arrayFormulaRangeMatrix?.getValue(row, column);
+ if (arrayFormulaRange == null) {
+ return true;
+ }
+ const { startRow, startColumn, endRow, endColumn } = arrayFormulaRange;
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ arrayFormulaCellMatrixData.setValue(r, c, null);
+ }
+ }
+ });
+
+ cellMatrixData.forValue((row, column, cellData) => {
+ arrayFormulaCellMatrixData.setValue(row, column, cellData);
+ });
+
+ this._arrayFormulaCellData[unitId][sheetId] = arrayFormulaCellMatrixData.getData();
+ });
+ });
+ }
+
getFormulaData() {
return this._formulaData;
}
@@ -24,24 +135,66 @@ export class FormulaDataModel extends Disposable {
this._formulaData = value;
}
- getArrayFormulaData(): ArrayFormulaDataType {
- return this._arrayFormulaData;
+ setArrayFormulaRange(value: IArrayFormulaRangeType) {
+ this._arrayFormulaRange = value;
}
- setArrayFormulaData(value: ArrayFormulaDataType) {
- Object.keys(value).forEach((sheetId) => {
- const arrayFormula = value[sheetId];
- if (!this._arrayFormulaData[sheetId]) {
- this._arrayFormulaData[sheetId] = new ObjectMatrix();
+ getArrayFormulaRange(): IArrayFormulaRangeType {
+ return this._arrayFormulaRange;
+ }
+
+ setArrayFormulaCellData(value: IArrayFormulaUnitCellType) {
+ this._arrayFormulaCellData = value;
+ }
+
+ getArrayFormulaCellData() {
+ return this._arrayFormulaCellData;
+ }
+
+ mergeArrayFormulaRange(formulaData: IArrayFormulaRangeType) {
+ Object.keys(formulaData).forEach((unitId) => {
+ const sheetData = formulaData[unitId];
+
+ if (!this._arrayFormulaRange[unitId]) {
+ this._arrayFormulaRange[unitId] = {};
}
- arrayFormula.forValue((r, c, v) => {
- this._arrayFormulaData[sheetId].setValue(r, c, v);
+
+ Object.keys(sheetData).forEach((sheetId) => {
+ const arrayFormula = new ObjectMatrix(sheetData[sheetId]);
+
+ let rangeMatrix = new ObjectMatrix<IRange>();
+
+ if (this._arrayFormulaRange[unitId][sheetId]) {
+ rangeMatrix = new ObjectMatrix(this._arrayFormulaRange[unitId][sheetId]);
+ }
+
+ arrayFormula.forValue((r, c, v) => {
+ rangeMatrix.setValue(r, c, v);
+ });
+
+ this._arrayFormulaRange[unitId][sheetId] = rangeMatrix.getData();
});
});
}
+ deleteArrayFormulaRange(unitId: string, sheetId: string, row: number, column: number) {
+ const cellMatrixData = this._arrayFormulaRange[unitId]?.[sheetId];
+ if (cellMatrixData == null) {
+ return;
+ }
+ const rangeMatrixData = new ObjectMatrix(cellMatrixData);
+ if (rangeMatrixData.getValue(row, column)) {
+ rangeMatrixData.realDeleteValue(row, column);
+
+ this._arrayFormulaRange[unitId][sheetId] = rangeMatrixData.getData();
+ }
+ }
+
initFormulaData() {
// load formula data from workbook config data
+
+ const unitFile = this._currentUniverService.getAllUniverSheetsInstance();
+
const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
const unitId = workbook.getUnitId();
this._formulaData[unitId] = {};
@@ -49,7 +202,7 @@ export class FormulaDataModel extends Disposable {
const worksheets = workbook.getSheets();
worksheets.forEach((worksheet) => {
const cellMatrix = worksheet.getCellMatrix();
- const formulaDataMatrix = new ObjectMatrix<IFormulaDataItem>();
+ const sheetFormulaDataMatrix = new ObjectMatrix<IFormulaDataItem>();
cellMatrix.forValue((r, c, cell) => {
const formulaString = cell?.f || '';
const formulaId = cell?.si || '';
@@ -58,16 +211,16 @@ export class FormulaDataModel extends Disposable {
const checkFormulaId = isFormulaId(formulaId);
if (checkFormulaString && checkFormulaId) {
- formulaDataMatrix.setValue(r, c, {
+ sheetFormulaDataMatrix.setValue(r, c, {
f: formulaString,
si: formulaId,
});
} else if (checkFormulaString && !checkFormulaId) {
- formulaDataMatrix.setValue(r, c, {
+ sheetFormulaDataMatrix.setValue(r, c, {
f: formulaString,
});
} else if (!checkFormulaString && checkFormulaId) {
- formulaDataMatrix.setValue(r, c, {
+ sheetFormulaDataMatrix.setValue(r, c, {
f: '',
si: formulaId,
});
@@ -75,7 +228,138 @@ export class FormulaDataModel extends Disposable {
});
const sheetId = worksheet.getSheetId();
- this._formulaData[unitId][sheetId] = formulaDataMatrix.getData();
+ this._formulaData[unitId][sheetId] = sheetFormulaDataMatrix.getData();
+ });
+ }
+
+ getCalculateData() {
+ const unitAllSheet = this._currentUniverService.getAllUniverSheetsInstance();
+
+ const allUnitData: IUnitData = {};
+
+ const unitSheetNameMap: IUnitSheetNameMap = {};
+
+ for (const workbook of unitAllSheet) {
+ const unitId = workbook.getUnitId();
+
+ const sheets = workbook.getSheets();
+
+ const sheetData: ISheetData = {};
+
+ const sheetNameMap: { [sheetName: string]: string } = {};
+
+ for (const sheet of sheets) {
+ const sheetId = sheet.getSheetId();
+
+ const sheetConfig = sheet.getConfig();
+ sheetData[sheetId] = {
+ cellData: new ObjectMatrix(sheetConfig.cellData),
+ rowCount: sheetConfig.rowCount,
+ columnCount: sheetConfig.columnCount,
+ };
+ sheetNameMap[sheet.getName()] = sheet.getSheetId();
+ }
+
+ allUnitData[unitId] = sheetData;
+
+ unitSheetNameMap[unitId] = sheetNameMap;
+ }
+
+ return {
+ allUnitData,
+ unitSheetNameMap,
+ };
+ }
+
+ updateFormulaData(unitId: string, sheetId: string, cellValue: ObjectMatrixPrimitiveType<ICellData | null>) {
+ const cellMatrix = new ObjectMatrix(cellValue);
+
+ const formulaIdMap = new Map<string, { f: string; r: number; c: number }>(); // Connect the formula and ID
+ const deleteFormulaIdMap = new Map<string, string | { f: string; r: number; c: number }>();
+
+ const formulaData = this._formulaData;
+ if (formulaData[unitId] == null) {
+ formulaData[unitId] = {};
+ }
+ const workbookFormulaData = formulaData[unitId];
+
+ if (workbookFormulaData[sheetId] == null) {
+ workbookFormulaData[sheetId] = {};
+ }
+
+ const sheetFormulaDataMatrix = new ObjectMatrix<IFormulaDataItem>(workbookFormulaData[sheetId]);
+
+ cellMatrix.forValue((r, c, cell) => {
+ const formulaString = cell?.f || '';
+ const formulaId = cell?.si || '';
+
+ const checkFormulaString = isFormulaString(formulaString);
+ const checkFormulaId = isFormulaId(formulaId);
+
+ if (checkFormulaString && checkFormulaId) {
+ sheetFormulaDataMatrix.setValue(r, c, {
+ f: formulaString,
+ si: formulaId,
+ });
+
+ formulaIdMap.set(formulaId, { f: formulaString, r, c });
+ } else if (checkFormulaString && !checkFormulaId) {
+ sheetFormulaDataMatrix.setValue(r, c, {
+ f: formulaString,
+ });
+ } else if (!checkFormulaString && checkFormulaId) {
+ sheetFormulaDataMatrix.setValue(r, c, {
+ f: '',
+ si: formulaId,
+ });
+ } else if (!checkFormulaString && !checkFormulaId && sheetFormulaDataMatrix.getRow(r)?.get(c)) {
+ const currentFormulaInfo = sheetFormulaDataMatrix.getRow(r)?.get(c);
+ const f = currentFormulaInfo?.f || '';
+ const si = currentFormulaInfo?.si || '';
+
+ // The id that needs to be offset
+ if (isFormulaString(f) && isFormulaId(si)) {
+ deleteFormulaIdMap.set(si, f);
+ }
+
+ sheetFormulaDataMatrix.realDeleteValue(r, c);
+ }
+ });
+
+ // Convert the formula ID to formula string
+ sheetFormulaDataMatrix.forValue((r, c, cell) => {
+ const formulaId = cell?.si || '';
+
+ if (isFormulaId(formulaId)) {
+ const formulaInfo = formulaIdMap.get(formulaId);
+ const deleteFormula = deleteFormulaIdMap.get(formulaId);
+ if (formulaInfo) {
+ const f = formulaInfo.f;
+ const x = c - formulaInfo.c;
+ const y = r - formulaInfo.r;
+
+ sheetFormulaDataMatrix.setValue(r, c, { f, si: formulaId, x, y });
+ } else if (typeof deleteFormula === 'string') {
+ deleteFormulaIdMap.set(formulaId, {
+ r,
+ c,
+ f: deleteFormula,
+ });
+
+ sheetFormulaDataMatrix.setValue(r, c, { f: deleteFormula, si: formulaId });
+ } else if (typeof deleteFormula === 'object') {
+ const x = c - deleteFormula.c;
+ const y = r - deleteFormula.r;
+ // TODO@Dushusir: Calculate the new formula based on the offset
+ // let f = '';
+ sheetFormulaDataMatrix.setValue(r, c, {
+ f: deleteFormula.f,
+ si: formulaId,
+ x,
+ y,
+ });
+ }
+ }
});
}
}
diff --git a/packages/formula/src/services/formula.service.ts b/packages/formula/src/services/formula.service.ts
new file mode 100644
index 0000000000..6844fa2ddc
--- /dev/null
+++ b/packages/formula/src/services/formula.service.ts
@@ -0,0 +1,62 @@
+import { LifecycleStages, OnLifecycle } from '@univerjs/core';
+import type { BaseFunction } from '@univerjs/engine-formula';
+import { FormulaEngineService } from '@univerjs/engine-formula';
+import type { Ctor, IDisposable } from '@wendellhu/redi';
+import { createIdentifier, Inject, Injector } from '@wendellhu/redi';
+
+import { functionArray } from './function-list/array/function-names';
+import { functionCompatibility } from './function-list/compatibility/function-names';
+import { functionCube } from './function-list/cube/function-names';
+import { functionDatabase } from './function-list/database/function-names';
+import { functionDate } from './function-list/date/function-names';
+import { functionEngineering } from './function-list/engineering/function-names';
+import { functionFinancial } from './function-list/financial/function-names';
+import { functionInformation } from './function-list/information/function-names';
+import { functionLogical } from './function-list/logical/function-names';
+import { functionLookup } from './function-list/lookup/function-names';
+import { functionMath } from './function-list/math/function-names';
+import { functionStatistical } from './function-list/statistical/function-names';
+import { functionText } from './function-list/text/function-names';
+import { functionUniver } from './function-list/univer/function-names';
+import { functionWeb } from './function-list/web/function-names';
+
+export interface IFormulaService {}
+
+export const IFormulaService = createIdentifier<IFormulaService>('formula-calculate.formula-service');
+
+@OnLifecycle(LifecycleStages.Starting, FormulaService)
+export class FormulaService implements IFormulaService, IDisposable {
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService
+ ) {}
+
+ dispose(): void {}
+
+ registerFunctions() {
+ const functions: BaseFunction[] = [
+ ...functionArray,
+ ...functionCompatibility,
+ ...functionCube,
+ ...functionDatabase,
+ ...functionDate,
+ ...functionEngineering,
+ ...functionFinancial,
+ ...functionInformation,
+ ...functionLogical,
+ ...functionLookup,
+ ...functionMath,
+ ...functionStatistical,
+ ...functionText,
+ ...functionUniver,
+ ...functionWeb,
+ ].map((registerObject) => {
+ const Func = registerObject[0] as Ctor<BaseFunction>;
+ const name = registerObject[1] as string;
+
+ return new Func(this._injector, name);
+ });
+
+ this._formulaEngineService.registerFunction(...functions);
+ }
+}
diff --git a/packages/formula/src/services/function-list/array/function-names.ts b/packages/formula/src/services/function-list/array/function-names.ts
new file mode 100644
index 0000000000..7904c2c47b
--- /dev/null
+++ b/packages/formula/src/services/function-list/array/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_ARRAY {}
+
+export const functionArray = [];
diff --git a/packages/formula/src/services/function-list/compatibility/function-names.ts b/packages/formula/src/services/function-list/compatibility/function-names.ts
new file mode 100644
index 0000000000..996fa95f81
--- /dev/null
+++ b/packages/formula/src/services/function-list/compatibility/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_COMPATIBILITY {}
+
+export const functionCompatibility = [];
diff --git a/packages/formula/src/services/function-list/cube/function-names.ts b/packages/formula/src/services/function-list/cube/function-names.ts
new file mode 100644
index 0000000000..d8a4e715f6
--- /dev/null
+++ b/packages/formula/src/services/function-list/cube/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_CUBE {}
+
+export const functionCube = [];
diff --git a/packages/formula/src/services/function-list/database/function-names.ts b/packages/formula/src/services/function-list/database/function-names.ts
new file mode 100644
index 0000000000..34a0d8bd2f
--- /dev/null
+++ b/packages/formula/src/services/function-list/database/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_DATABASE {}
+
+export const functionDatabase = [];
diff --git a/packages/formula/src/services/function-list/date/function-names.ts b/packages/formula/src/services/function-list/date/function-names.ts
new file mode 100644
index 0000000000..51abcd18ac
--- /dev/null
+++ b/packages/formula/src/services/function-list/date/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_DATE {}
+
+export const functionDate = [];
diff --git a/packages/formula/src/services/function-list/engineering/function-names.ts b/packages/formula/src/services/function-list/engineering/function-names.ts
new file mode 100644
index 0000000000..3991fbda13
--- /dev/null
+++ b/packages/formula/src/services/function-list/engineering/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_ENGINEERING {}
+
+export const functionEngineering = [];
diff --git a/packages/formula/src/services/function-list/financial/function-names.ts b/packages/formula/src/services/function-list/financial/function-names.ts
new file mode 100644
index 0000000000..96cbbf9139
--- /dev/null
+++ b/packages/formula/src/services/function-list/financial/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_FINANCIAL {}
+
+export const functionFinancial = [];
diff --git a/packages/formula/src/services/function-list/information/function-names.ts b/packages/formula/src/services/function-list/information/function-names.ts
new file mode 100644
index 0000000000..61622a2843
--- /dev/null
+++ b/packages/formula/src/services/function-list/information/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_INFORMATION {}
+
+export const functionInformation = [];
diff --git a/packages/formula/src/services/function-list/logical/function-names.ts b/packages/formula/src/services/function-list/logical/function-names.ts
new file mode 100644
index 0000000000..c01bd9fa44
--- /dev/null
+++ b/packages/formula/src/services/function-list/logical/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_LOGICAL {}
+
+export const functionLogical = [];
diff --git a/packages/formula/src/services/function-list/lookup/function-names.ts b/packages/formula/src/services/function-list/lookup/function-names.ts
new file mode 100644
index 0000000000..91feb06101
--- /dev/null
+++ b/packages/formula/src/services/function-list/lookup/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_LOOKUP {}
+
+export const functionLookup = [];
diff --git a/packages/formula/src/services/function-list/math/function-names.ts b/packages/formula/src/services/function-list/math/function-names.ts
new file mode 100644
index 0000000000..be0c7f309a
--- /dev/null
+++ b/packages/formula/src/services/function-list/math/function-names.ts
@@ -0,0 +1,12 @@
+import { Sumif } from './sumif/sumif';
+import { Sumifs } from './sumifs/sumifs';
+
+export enum FUNCTION_NAMES_MATH {
+ SUMIF = 'SUMIF',
+ SUMIFS = 'SUMIFS',
+}
+
+export const functionMath = [
+ [Sumif, FUNCTION_NAMES_MATH.SUMIF],
+ [Sumifs, FUNCTION_NAMES_MATH.SUMIFS],
+];
diff --git a/packages/formula/src/services/function-list/math/sumif/__tests__/sumif.spec.ts b/packages/formula/src/services/function-list/math/sumif/__tests__/sumif.spec.ts
new file mode 100644
index 0000000000..704f98c096
--- /dev/null
+++ b/packages/formula/src/services/function-list/math/sumif/__tests__/sumif.spec.ts
@@ -0,0 +1,5 @@
+import { describe, it } from 'vitest';
+
+describe('test sumif', () => {
+ it('correct situations', () => {});
+});
diff --git a/packages/formula/src/services/function-list/math/sumif/sumif.ts b/packages/formula/src/services/function-list/math/sumif/sumif.ts
new file mode 100644
index 0000000000..ed420ef90d
--- /dev/null
+++ b/packages/formula/src/services/function-list/math/sumif/sumif.ts
@@ -0,0 +1,62 @@
+import type {
+ ArrayValueObject,
+ BaseReferenceObject,
+ BaseValueObject,
+ BooleanValueObject,
+ compareToken,
+ FunctionVariantType,
+} from '@univerjs/engine-formula';
+import { BaseFunction, ErrorType, ErrorValueObject, NumberValueObject } from '@univerjs/engine-formula';
+
+export class Sumif extends BaseFunction {
+ override calculate(...variants: FunctionVariantType[]) {
+ // 1. Check whether the number of parameters is correct,
+ // TODO@Dushusir: Report the allowed parameter number range and the actual number of parameters
+ if (variants.length < 2 || variants.length > 3) {
+ return ErrorValueObject.create(ErrorType.NA);
+ }
+
+ const range = variants[0];
+ const criteria = variants[1];
+ const sumRange = variants[2];
+
+ // 2. Check whether all parameter types meet the requirements
+ if (range.isErrorObject() || criteria.isErrorObject() || (sumRange && sumRange.isErrorObject())) {
+ return ErrorValueObject.create(ErrorType.VALUE);
+ }
+
+ let accumulatorAll: BaseValueObject = new NumberValueObject(0);
+
+ if (range.isReferenceObject() || (range.isValueObject() && (range as BaseValueObject).isArray())) {
+ (range as BaseReferenceObject | ArrayValueObject).iterator((valueObject, row, column) => {
+ if (!valueObject.isErrorObject() && criteria.isValueObject()) {
+ // TODO@Dushusir: criteria is referenceObject
+ const accumulator = this._validator(valueObject as BaseValueObject, criteria as BaseValueObject);
+ accumulatorAll = accumulatorAll.plus(accumulator) as BaseValueObject;
+ }
+ });
+ } else if (criteria.isValueObject()) {
+ // TODO@Dushusir: criteria is referenceObject
+ accumulatorAll = this._validator(range as BaseValueObject, criteria as BaseValueObject);
+ }
+
+ return accumulatorAll;
+ }
+
+ private _validator(rangeValue: BaseValueObject, criteriaValue: BaseValueObject) {
+ const criteriaValueString = criteriaValue.getValue();
+ if (criteriaValueString) {
+ // TODO@Dushusir: support ==, !=, >, >=, <, <=, <>, *, ?, ~?, ~*
+ const token = (criteriaValueString as string).substring(0, 1) as compareToken;
+ const criteriaString = (criteriaValueString as string).substring(1);
+ // TODO@Dushusir: support string value
+ const validator = rangeValue.compare(new NumberValueObject(criteriaString), token) as BooleanValueObject;
+ const validatorValue = validator.getValue();
+ if (!validatorValue) {
+ rangeValue = new NumberValueObject(0);
+ }
+ }
+
+ return rangeValue;
+ }
+}
diff --git a/packages/formula/src/services/function-list/math/sumifs/__tests__/sumifs.spec.ts b/packages/formula/src/services/function-list/math/sumifs/__tests__/sumifs.spec.ts
new file mode 100644
index 0000000000..e7cd9cddef
--- /dev/null
+++ b/packages/formula/src/services/function-list/math/sumifs/__tests__/sumifs.spec.ts
@@ -0,0 +1,5 @@
+import { describe, it } from 'vitest';
+
+describe('test sumifs', () => {
+ it('correct situations', () => {});
+});
diff --git a/packages/formula/src/services/function-list/math/sumifs/sumifs.ts b/packages/formula/src/services/function-list/math/sumifs/sumifs.ts
new file mode 100644
index 0000000000..31395ac7ed
--- /dev/null
+++ b/packages/formula/src/services/function-list/math/sumifs/sumifs.ts
@@ -0,0 +1,8 @@
+import type { FunctionVariantType } from '@univerjs/engine-formula';
+import { BaseFunction, ErrorType, ErrorValueObject } from '@univerjs/engine-formula';
+
+export class Sumifs extends BaseFunction {
+ override calculate(...variants: FunctionVariantType[]) {
+ return ErrorValueObject.create(ErrorType.VALUE);
+ }
+}
diff --git a/packages/formula/src/services/function-list/statistical/function-names.ts b/packages/formula/src/services/function-list/statistical/function-names.ts
new file mode 100644
index 0000000000..23c314b8a3
--- /dev/null
+++ b/packages/formula/src/services/function-list/statistical/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_STATISTICAL {}
+
+export const functionStatistical = [];
diff --git a/packages/formula/src/services/function-list/text/function-names.ts b/packages/formula/src/services/function-list/text/function-names.ts
new file mode 100644
index 0000000000..ff675c0fca
--- /dev/null
+++ b/packages/formula/src/services/function-list/text/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_TEXT {}
+
+export const functionText = [];
diff --git a/packages/formula/src/services/function-list/univer/function-names.ts b/packages/formula/src/services/function-list/univer/function-names.ts
new file mode 100644
index 0000000000..af6756f3ad
--- /dev/null
+++ b/packages/formula/src/services/function-list/univer/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_UNIVER {}
+
+export const functionUniver = [];
diff --git a/packages/formula/src/services/function-list/web/function-names.ts b/packages/formula/src/services/function-list/web/function-names.ts
new file mode 100644
index 0000000000..3932ff51b4
--- /dev/null
+++ b/packages/formula/src/services/function-list/web/function-names.ts
@@ -0,0 +1,3 @@
+export enum FUNCTION_NAMES_WEB {}
+
+export const functionWeb = [];
diff --git a/packages/formula/vitest.config.ts b/packages/formula/vitest.config.ts
new file mode 100644
index 0000000000..3c74cf802f
--- /dev/null
+++ b/packages/formula/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ provider: 'istanbul',
+ },
+ },
+});
diff --git a/packages/sheets-formula/package.json b/packages/sheets-formula/package.json
index 6c8181ecb4..8b40606226 100644
--- a/packages/sheets-formula/package.json
+++ b/packages/sheets-formula/package.json
@@ -49,6 +49,7 @@
"@ctrl/tinycolor": "^4.0.2",
"@univerjs/docs": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
+ "@univerjs/formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/ui": "workspace:*",
diff --git a/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts b/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
index 1d4071f2c2..e0903068c6 100644
--- a/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
+++ b/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
@@ -1,5 +1,5 @@
import type { ICellData, Nullable, Univer } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService, RANGE_TYPE } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
import {
NORMAL_SELECTION_PLUGIN_NAME,
SelectionManagerService,
@@ -64,17 +64,17 @@ describe('Test insert function operation', () => {
value: 'SUM',
};
- // expect(await commandService.executeCommand(InsertFunctionOperation.id, params)).toBeTruthy();
- // expect(getValue()?.f).toStrictEqual('=SUM(B2)');
- // // undo
- // expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
- // expect(getValue()).toStrictEqual({});
- // // redo
- // expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
- // expect(getValue()?.f).toStrictEqual('=SUM(B2)');
+ expect(await commandService.executeCommand(InsertFunctionOperation.id, params)).toBeTruthy();
+ expect(getValue()?.f).toStrictEqual('=SUM(B2)');
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({});
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValue()?.f).toStrictEqual('=SUM(B2)');
- // // Restore the original data
- // expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ // Restore the original data
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
});
it('insert function, match the data range left', async () => {
@@ -104,17 +104,17 @@ describe('Test insert function operation', () => {
value: 'SUM',
};
- // expect(await commandService.executeCommand(InsertFunctionOperation.id, params)).toBeTruthy();
- // expect(getValue()?.f).toStrictEqual('=SUM(B2)');
- // // undo
- // expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
- // expect(getValue()).toStrictEqual({});
- // // redo
- // expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
- // expect(getValue()?.f).toStrictEqual('=SUM(B2)');
+ expect(await commandService.executeCommand(InsertFunctionOperation.id, params)).toBeTruthy();
+ expect(getValue()?.f).toStrictEqual('=SUM(B2)');
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({});
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValue()?.f).toStrictEqual('=SUM(B2)');
- // // Restore the original data
- // expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ // Restore the original data
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
});
});
diff --git a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
index 9ca30bea16..2b0572c6b7 100644
--- a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
+++ b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
@@ -6,6 +6,7 @@ import {
ICommandService,
IUniverInstanceService,
serializeRange,
+ Tools,
} from '@univerjs/core';
import { SelectionManagerService } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
@@ -40,9 +41,9 @@ export const InsertFunctionOperation: ICommand = {
// TODO@Dushusir: no match refRange situation, enter edit mode
- // In each range (whether it is an entire row or column or multiple rows and columns),
- // 1. First get the judgment result of the primary position, and then set the formula id of other positions;
- // 2. If there is no primary range, just judge the upper left corner cell.
+ // In each range, first take the judgment result of the primary position (if there is no primary, take the upper left corner),
+ // If there is a range, set the formula range directly, and then set the formula id of other positions.
+ // If the range cannot be found, enter the edit mode.
const list: IInsertFunction[] = [];
currentSelections.some((selection) => {
const { range, primary } = selection;
@@ -53,7 +54,8 @@ export const InsertFunctionOperation: ICommand = {
const refRange = findRefRange(cellMatrix, row, column);
if (!refRange) {
- formulaInputService.inputFormula(value);
+ // TODO@Dushusir: set current position
+ formulaInputService.inputFormula(`=${value}(`);
return true;
}
@@ -72,7 +74,7 @@ export const InsertFunctionOperation: ICommand = {
return false;
});
- if (list) return false;
+ if (list.length === 0) return false;
return commandService.executeCommand(InsertFunctionCommand.id, {
list,
@@ -115,13 +117,11 @@ function findStartRow(cellMatrix: ObjectMatrix<ICellData>, row: number, column:
for (let r = row - 1; r >= 0; r--) {
const cell = cellMatrix.getValue(r, column);
- if (!cell) continue;
-
- if (getCellValueType(cell) === CellValueType.NUMBER && !isFirstNumber) {
+ if (isNumberCell(cell) && !isFirstNumber) {
if (r === 0) return 0;
isFirstNumber = true;
- } else if (isFirstNumber && getCellValueType(cell) !== CellValueType.NUMBER) {
- return r - 1;
+ } else if (isFirstNumber && !isNumberCell(cell)) {
+ return r + 1;
} else if (isFirstNumber && r === 0) {
return 0;
}
@@ -137,13 +137,12 @@ function findStartColumn(cellMatrix: ObjectMatrix<ICellData>, row: number, colum
for (let c = column - 1; c >= 0; c--) {
const cell = cellMatrix.getValue(row, c);
- if (!cell) continue;
- if (getCellValueType(cell) === CellValueType.NUMBER && !isFirstNumber) {
+ if (isNumberCell(cell) && !isFirstNumber) {
if (c === 0) return 0;
isFirstNumber = true;
- } else if (isFirstNumber && getCellValueType(cell) !== CellValueType.NUMBER) {
- return c - 1;
+ } else if (isFirstNumber && !isNumberCell(cell)) {
+ return c + 1;
} else if (isFirstNumber && c === 0) {
return 0;
}
@@ -151,3 +150,7 @@ function findStartColumn(cellMatrix: ObjectMatrix<ICellData>, row: number, colum
return column;
}
+
+function isNumberCell(cell: Nullable<ICellData>) {
+ return cell && (Tools.isStringNumber(cell.v) || getCellValueType(cell) === CellValueType.NUMBER);
+}
diff --git a/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
new file mode 100644
index 0000000000..5f6d7cfeb3
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/__tests__/create-command-test-bed.ts
@@ -0,0 +1,74 @@
+import type { IWorkbookData, Workbook } from '@univerjs/core';
+import { ILogService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';
+import { SelectionManagerService } from '@univerjs/sheets';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ '0': {
+ '0': {
+ v: 1,
+ },
+ '1': {
+ f: '=SUM(A1)',
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+};
+
+export interface ITestBed {
+ univer: Univer;
+ get: Injector['get'];
+ sheet: Workbook;
+}
+
+export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]): ITestBed {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Sheet;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([SelectionManagerService]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA_DEMO);
+
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test');
+ const logService = injector.get(ILogService);
+
+ logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+
+ return {
+ univer,
+ get: injector.get.bind(injector),
+ sheet,
+ };
+}
diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
new file mode 100644
index 0000000000..08cf38bbe1
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts
@@ -0,0 +1,162 @@
+import type { ICellData, Nullable, Univer } from '@univerjs/core';
+import {
+ ICommandService,
+ IUniverInstanceService,
+ RANGE_TYPE,
+ RedoCommand,
+ ThemeService,
+ UndoCommand,
+} from '@univerjs/core';
+import { FormulaEngineService } from '@univerjs/engine-formula';
+import {
+ AddWorksheetMergeMutation,
+ NORMAL_SELECTION_PLUGIN_NAME,
+ RemoveWorksheetMergeMutation,
+ SelectionManagerService,
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+} from '@univerjs/sheets';
+import {
+ AutoFillCommand,
+ AutoFillController,
+ AutoFillService,
+ IAutoFillService,
+ ISelectionRenderService,
+ SelectionRenderService,
+} from '@univerjs/sheets-ui';
+import type { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { FormulaAutoFillController } from '../formula-auto-fill.controller';
+import { createCommandTestBed } from './create-command-test-bed';
+
+const theme = {
+ colorBlack: '#35322b',
+};
+
+describe('Test clear selection content commands', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let autoFillController: AutoFillController;
+ let themeService: ThemeService;
+ let getValues: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Array<Array<Nullable<ICellData>>> | undefined;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed(undefined, [
+ [ISelectionRenderService, { useClass: SelectionRenderService }],
+ [AutoFillController],
+ [FormulaEngineService],
+ [IAutoFillService, { useClass: AutoFillService }],
+ [FormulaAutoFillController],
+ ]);
+ univer = testBed.univer;
+ get = testBed.get;
+ commandService = get(ICommandService);
+ themeService = get(ThemeService);
+ themeService.setTheme(theme);
+ autoFillController = get(AutoFillController);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetSelectionsOperation);
+ commandService.registerCommand(AddWorksheetMergeMutation);
+ commandService.registerCommand(RemoveWorksheetMergeMutation);
+
+ getValues = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Array<Array<Nullable<ICellData>>> | undefined =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValues();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ describe('auto fill with formula', () => {
+ describe('correct situations', () => {
+ it('one cell with formula', async () => {
+ const selectionManager = get(SelectionManagerService);
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+ selectionManager.add([
+ {
+ range: { startRow: 0, startColumn: 1, endRow: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ (autoFillController as any)._handleFill(
+ {
+ startColumn: 1,
+ endColumn: 1,
+ startRow: 0,
+ endRow: 0,
+ },
+ {
+ startColumn: 1,
+ endColumn: 1,
+ startRow: 0,
+ endRow: 2,
+ }
+ );
+
+ // values will be in the following format
+ // [
+ // [ { f: '=SUM(A1)' } ],
+ // [ { f: '=SUM(A2)', si: '1ZMZWH' } ],
+ // [ { si: '1ZMZWH' } ]
+ // ]
+ let values = getValues(0, 1, 2, 1);
+ let B2 = values && values[1][0];
+ let B3 = values && values[2][0];
+
+ expect(B2?.f).toStrictEqual('=SUM(A2)');
+ expect(B2?.si).toEqual(B3?.si);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+
+ values = getValues(0, 1, 2, 1);
+ B2 = values && values[1][0];
+ B3 = values && values[2][0];
+
+ expect(B2).toStrictEqual({});
+ expect(B3).toStrictEqual({});
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ values = getValues(0, 1, 2, 1);
+ B2 = values && values[1][0];
+ B3 = values && values[2][0];
+
+ expect(B2?.f).toStrictEqual('=SUM(A2)');
+ expect(B2?.si).toEqual(B3?.si);
+
+ // Restore the original data
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ });
+ });
+
+ describe('fault situations', () => {
+ it('will not apply when there is no selected ranges', async () => {
+ const result = await commandService.executeCommand(AutoFillCommand.id);
+ expect(result).toBeFalsy();
+ });
+ });
+ });
+});
diff --git a/packages/sheets-formula/src/controllers/formula-auto-fill.controller.ts b/packages/sheets-formula/src/controllers/formula-auto-fill.controller.ts
new file mode 100644
index 0000000000..2e949b9ccd
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/formula-auto-fill.controller.ts
@@ -0,0 +1,133 @@
+import type { ICellData, Nullable } from '@univerjs/core';
+import { Direction, Disposable, isFormulaString, LifecycleStages, OnLifecycle, Tools } from '@univerjs/core';
+import { FormulaEngineService } from '@univerjs/engine-formula';
+import type { AutoFillService, IAutoFillRule, ICopyDataInTypeIndexInfo, ICopyDataPiece } from '@univerjs/sheets-ui';
+import { APPLY_TYPE, DATA_TYPE, IAutoFillService } from '@univerjs/sheets-ui';
+import { Inject } from '@wendellhu/redi';
+
+@OnLifecycle(LifecycleStages.Ready, FormulaAutoFillController)
+export class FormulaAutoFillController extends Disposable {
+ constructor(
+ @IAutoFillService private readonly _autoFillService: AutoFillService,
+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._registerAutoFill();
+ }
+
+ private _registerAutoFill(): void {
+ const formulaRule: IAutoFillRule = {
+ type: DATA_TYPE.FORMULA,
+ priority: 1001,
+ match: (cellData) => isFormulaString(cellData?.f),
+ isContinue: (prev, cur) => {
+ if (prev.type === DATA_TYPE.FORMULA) {
+ return true;
+ }
+ return false;
+ },
+ applyFunctions: {
+ [APPLY_TYPE.COPY]: (dataWithIndex, len, direction, copyDataPiece) => {
+ const { data, index } = dataWithIndex;
+ return this._fillCopyFormula(data, len, direction, index, copyDataPiece);
+ },
+ },
+ };
+ this._autoFillService.registerRule(formulaRule);
+ }
+
+ private _fillCopyFormula(
+ data: Array<Nullable<ICellData>>,
+ len: number,
+ direction: Direction,
+ index: ICopyDataInTypeIndexInfo,
+ copyDataPiece: ICopyDataPiece
+ ) {
+ const step = getDataLength(copyDataPiece);
+ const applyData = [];
+ const formulaIdMap = new Map<number, string>();
+
+ for (let i = 1; i <= len; i++) {
+ const index = (i - 1) % data.length;
+ const d = Tools.deepClone(data[index]);
+
+ if (d) {
+ const originalFormula = data[index]?.f;
+
+ if (originalFormula) {
+ // The first position setting formula and formulaId
+ let formulaId = formulaIdMap.get(index);
+
+ if (!formulaId) {
+ formulaId = Tools.generateRandomId(6);
+ formulaIdMap.set(index, formulaId);
+
+ const { offsetX, offsetY } = directionToOffset(step, direction);
+ const shiftedFormula = this._formulaEngineService.moveFormulaRefOffset(
+ originalFormula,
+ offsetX,
+ offsetY
+ );
+
+ d.si = formulaId;
+ d.f = shiftedFormula;
+ d.v = null;
+ d.p = null;
+ } else {
+ // At the beginning of the second formula, set formulaId only
+ d.si = formulaId;
+ d.f = null;
+ d.v = null;
+ d.p = null;
+ }
+
+ if (direction === Direction.DOWN || direction === Direction.RIGHT) {
+ applyData.push(d);
+ } else {
+ applyData.unshift(d);
+ }
+ }
+ }
+ }
+
+ return applyData;
+ }
+}
+
+function directionToOffset(step: number, direction: Direction) {
+ let offsetX = 0;
+ let offsetY = 0;
+
+ switch (direction) {
+ case Direction.UP:
+ offsetY = -step;
+ break;
+ case Direction.RIGHT:
+ offsetX = step;
+ break;
+ case Direction.DOWN:
+ offsetY = step;
+ break;
+ case Direction.LEFT:
+ offsetX = -step;
+ break;
+ }
+
+ return { offsetX, offsetY };
+}
+
+function getDataLength(copyDataPiece: ICopyDataPiece) {
+ let length = 0;
+ for (const t in copyDataPiece) {
+ copyDataPiece[t].forEach((item) => {
+ length += item.data.length;
+ });
+ }
+
+ return length;
+}
diff --git a/packages/sheets-formula/src/controllers/formula-input.controller.ts b/packages/sheets-formula/src/controllers/formula-input.controller.ts
index 4271f9b7b8..d6c7bec361 100644
--- a/packages/sheets-formula/src/controllers/formula-input.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-input.controller.ts
@@ -91,13 +91,11 @@ export class FormulaInputController extends Disposable {
});
}
- const dataStream = `=${formulaString}(`;
-
- const lastSequenceNodes = this._formulaEngineService.buildSequenceNodes(dataStream) || [];
+ const lastSequenceNodes = this._formulaEngineService.buildSequenceNodes(formulaString) || [];
this._formulaInputService.setSequenceNodes(lastSequenceNodes);
- this._formulaInputService.syncToEditor(dataStream.length - 1);
+ this._formulaInputService.syncToEditor(formulaString.length - 1);
})
)
);
diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.ts
index a0571578de..076daa2803 100644
--- a/packages/sheets-formula/src/formula-ui-plugin.ts
+++ b/packages/sheets-formula/src/formula-ui-plugin.ts
@@ -4,6 +4,7 @@ import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
+import { FormulaAutoFillController } from './controllers/formula-auto-fill.controller';
import { FormulaInputController } from './controllers/formula-input.controller';
import { FormulaUIController } from './controllers/formula-ui.controller';
import { PromptController } from './controllers/prompt.controller';
@@ -48,6 +49,7 @@ export class FormulaUIPlugin extends Plugin {
[FormulaUIController],
[PromptController],
[FormulaInputController],
+ [FormulaAutoFillController],
];
dependencies.forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/sheets-formula/src/locale/function-list/math/en-US.ts b/packages/sheets-formula/src/locale/function-list/math/en-US.ts
index 53c8e2db7d..a88b36a788 100644
--- a/packages/sheets-formula/src/locale/function-list/math/en-US.ts
+++ b/packages/sheets-formula/src/locale/function-list/math/en-US.ts
@@ -13,4 +13,22 @@ export default {
},
},
},
+ SUMIF: {
+ description: 'Sum the values in a range that meet criteria that you specify.',
+ abstract: 'Adds the cells specified by a given criteria',
+ functionParameter: {
+ range: {
+ name: 'range',
+ detail: 'The range of cells that you want evaluated by criteria.',
+ },
+ criteria: {
+ name: 'criteria',
+ detail: 'The criteria in the form of a number, expression, a cell reference, text, or a function that defines which cells will be added. Wildcard characters can be included - a question mark (?) to match any single character, an asterisk (*) to match any sequence of characters. If you want to find an actual question mark or asterisk, type a tilde (~) preceding the character.',
+ },
+ sum_range: {
+ name: 'sum_range',
+ detail: 'The actual cells to add, if you want to add cells other than those specified in the range argument. If the sum_range argument is omitted, Excel adds the cells that are specified in the range argument (the same cells to which the criteria is applied).',
+ },
+ },
+ },
};
diff --git a/packages/sheets-formula/src/locale/function-list/math/zh-CN.ts b/packages/sheets-formula/src/locale/function-list/math/zh-CN.ts
index a8a8735cb0..c8ed5a7989 100644
--- a/packages/sheets-formula/src/locale/function-list/math/zh-CN.ts
+++ b/packages/sheets-formula/src/locale/function-list/math/zh-CN.ts
@@ -13,4 +13,22 @@ export default {
},
},
},
+ SUMIF: {
+ description: '对范围中符合指定条件的值求和。',
+ abstract: '按给定条件对指定单元格求和',
+ functionParameter: {
+ range: {
+ name: '范围',
+ detail: '要根据条件进行检测的范围。',
+ },
+ criteria: {
+ name: '条件',
+ detail: '以数字、表达式、单元格引用、文本或函数的形式来定义将添加哪些单元格。可包括的通配符字符 - 问号(?)以匹配任意单个字符,星号(*)以匹配任意字符序列。 如果要查找实际的问号或星号,请在该字符前键入波形符(~)。',
+ },
+ sum_range: {
+ name: '求和范围',
+ detail: '要添加的实际单元格,如果要添加在范围参数指定以外的其他单元格。 如果省略sum_range参数,Excel就会添加范围参数中指定的单元格(与应用标准的单元格相同)。',
+ },
+ },
+ },
};
diff --git a/packages/sheets-formula/src/services/function-list/math.ts b/packages/sheets-formula/src/services/function-list/math.ts
index 5f3358ee58..e191500c6d 100644
--- a/packages/sheets-formula/src/services/function-list/math.ts
+++ b/packages/sheets-formula/src/services/function-list/math.ts
@@ -1,5 +1,6 @@
import type { IFunctionInfo } from '@univerjs/engine-formula';
import { FUNCTION_NAMES, FunctionType } from '@univerjs/engine-formula';
+import { FUNCTION_NAMES_MATH } from '@univerjs/formula';
export const FUNCTION_LIST_MATH: IFunctionInfo[] = [
{
@@ -25,4 +26,34 @@ export const FUNCTION_LIST_MATH: IFunctionInfo[] = [
},
],
},
+ {
+ functionName: FUNCTION_NAMES_MATH.SUMIF,
+ aliasFunctionName: 'formula.functionList.SUMIF.aliasFunctionName',
+ functionType: FunctionType.Math,
+ description: 'formula.functionList.SUMIF.description',
+ abstract: 'formula.functionList.SUMIF.abstract',
+ functionParameter: [
+ {
+ name: 'formula.functionList.SUMIF.functionParameter.range.name',
+ detail: 'formula.functionList.SUMIF.functionParameter.range.detail',
+ example: 'A1:A20',
+ require: 1,
+ repeat: 0,
+ },
+ {
+ name: 'formula.functionList.SUMIF.functionParameter.criteria.name',
+ detail: 'formula.functionList.SUMIF.functionParameter.criteria.detail',
+ example: '>5',
+ require: 1,
+ repeat: 0,
+ },
+ {
+ name: 'formula.functionList.SUMIF.functionParameter.sum_range.name',
+ detail: 'formula.functionList.SUMIF.functionParameter.sum_range.detail',
+ example: 'B1:B20',
+ require: 0,
+ repeat: 0,
+ },
+ ],
+ },
];
diff --git a/packages/sheets-formula/src/views/more-functions/MoreFunctions.tsx b/packages/sheets-formula/src/views/more-functions/MoreFunctions.tsx
index c4e51e55a2..c1ecd32c46 100644
--- a/packages/sheets-formula/src/views/more-functions/MoreFunctions.tsx
+++ b/packages/sheets-formula/src/views/more-functions/MoreFunctions.tsx
@@ -5,6 +5,7 @@ import { ISidebarService } from '@univerjs/ui';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useState } from 'react';
+import { IFormulaInputService } from '../../services/formula-input.service';
import styles from './index.module.less';
import { InputParams } from './input-params/InputParams';
import { SelectFunction } from './select-function/SelectFunction';
@@ -17,6 +18,7 @@ export function MoreFunctions() {
const localeService = useDependency(LocaleService);
const sidebarService = useDependency(ISidebarService);
+ const formulaInputService = useDependency(IFormulaInputService);
function handleClickNextPrev() {
if (selectFunction) {
@@ -29,6 +31,7 @@ export function MoreFunctions() {
function handleConfirm() {
// TODO@Dushusir: save function `=${functionInfo?.functionName}(${params.join(',')})`
+ formulaInputService.inputFormula(`=${functionInfo?.functionName}(`);
}
return (
diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
index 2001305e09..e026b2fe31 100644
--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
@@ -251,7 +251,7 @@ export class AutoFillController extends Disposable {
// calc cell data to apply
rules.forEach((r) => {
- const { type, applyFunctions: customApplyFunctions } = r;
+ const { type, applyFunctions: customApplyFunctions = {} } = r;
const copyDataInType = copyDataPiece[type];
if (!copyDataInType) {
return;
@@ -261,7 +261,14 @@ export class AutoFillController extends Disposable {
copyDataInType.forEach((copySquad) => {
const s = getLenS(copySquad.index, rsd);
const len = copySquad.index.length * num + s;
- const arrData = this._applyFunctions(copySquad, len, direction, applyType, customApplyFunctions);
+ const arrData = this._applyFunctions(
+ copySquad,
+ len,
+ direction,
+ applyType,
+ customApplyFunctions,
+ copyDataPiece
+ );
const arrIndex = getDataIndex(csLen, asLen, copySquad.index);
applyDataInTypes[type].push({ data: arrData, index: arrIndex });
});
@@ -288,7 +295,8 @@ export class AutoFillController extends Disposable {
len: number,
direction: Direction,
applyType: APPLY_TYPE,
- customApplyFunctions?: APPLY_FUNCTIONS
+ customApplyFunctions: APPLY_FUNCTIONS,
+ copyDataPiece: ICopyDataPiece
) {
const { data } = copySquad;
const isReverse = direction === Direction.UP || direction === Direction.LEFT;
@@ -297,7 +305,7 @@ export class AutoFillController extends Disposable {
if (applyType === APPLY_TYPE.COPY) {
const custom = customApplyFunctions?.[APPLY_TYPE.COPY];
if (custom) {
- return custom(copySquad, len, direction);
+ return custom(copySquad, len, direction, copyDataPiece);
}
isReverse && data.reverse();
return fillCopy(data, len);
@@ -305,19 +313,19 @@ export class AutoFillController extends Disposable {
if (applyType === APPLY_TYPE.SERIES) {
const custom = customApplyFunctions?.[APPLY_TYPE.SERIES];
if (custom) {
- return custom(copySquad, len, direction);
+ return custom(copySquad, len, direction, copyDataPiece);
}
isReverse && data.reverse();
// special rules, if not provide custom SERIES apply functions, will be applied as copy
if (customApplyFunctions?.[APPLY_TYPE.COPY]) {
- return customApplyFunctions[APPLY_TYPE.COPY](copySquad, len, direction);
+ return customApplyFunctions[APPLY_TYPE.COPY](copySquad, len, direction, copyDataPiece);
}
return fillCopy(data, len);
}
if (applyType === APPLY_TYPE.ONLY_FORMAT) {
const custom = customApplyFunctions?.[APPLY_TYPE.ONLY_FORMAT];
if (custom) {
- return custom(copySquad, len, direction);
+ return custom(copySquad, len, direction, copyDataPiece);
}
return fillCopyStyles(data, len);
}
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index f1a6244965..47217e7511 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -2,9 +2,9 @@ import type { ICellData, IMutationInfo, IRange } from '@univerjs/core';
import { IUniverInstanceService, ObjectMatrix, Rectangle, SheetInterceptorService } from '@univerjs/core';
import type {
IAddWorksheetMergeMutationParams,
+ IMoveRangeMutationParams,
IRemoveWorksheetMergeMutationParams,
ISetRangeValuesMutationParams,
- MoveRangeMutationParams,
} from '@univerjs/sheets';
import {
AddMergeUndoMutationFactory,
@@ -142,13 +142,13 @@ export function getMoveRangeMutations(
return res;
}, new ObjectMatrix<ICellData | null>());
- const doMoveRangeMutation: MoveRangeMutationParams = {
+ const doMoveRangeMutation: IMoveRangeMutationParams = {
from: newFromCellValues.getMatrix(),
to: newToCellValues.getMatrix(),
workbookId,
worksheetId,
};
- const undoMoveRangeMutation: MoveRangeMutationParams = {
+ const undoMoveRangeMutation: IMoveRangeMutationParams = {
from: currentFromCellValues.getMatrix(),
to: currentToCellValues.getMatrix(),
workbookId,
diff --git a/packages/sheets-ui/src/controllers/editor/editing.controller.ts b/packages/sheets-ui/src/controllers/editor/editing.controller.ts
index 9954900b43..0aba3fda71 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.controller.ts
@@ -96,7 +96,7 @@ export class EditingController extends Disposable {
// dirtyRanges: [],
// })
// .then((res) => {
- // console.log(res.sheetData, res.arrayFormulaData);
+ // console.log(res.sheetData, res.arrayFormulaRange);
// });
// console.log(
diff --git a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
index 6985527ecb..6727a69090 100644
--- a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
@@ -176,6 +176,9 @@ export class EndEditController extends Disposable {
let newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;
if (isFormulaString(newDataStream)) {
+ if (cellData.f === newDataStream) {
+ return;
+ }
const bracketCount = this._formulaEngineService.checkIfAddBracket(newDataStream);
for (let i = 0; i < bracketCount; i++) {
newDataStream += matchToken.CLOSE_BRACKET;
@@ -189,7 +192,8 @@ export class EndEditController extends Disposable {
cellData.v = null;
cellData.f = null;
} else {
- if (newDataStream === cellData.v) {
+ // eslint-disable-next-line
+ if (newDataStream == cellData.v || (newDataStream == '' && cellData.v == null)) {
return;
}
cellData.v = newDataStream;
diff --git a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
index b39563dbba..ae1da4f8d3 100644
--- a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
@@ -417,7 +417,7 @@ export class StartEditController extends Disposable {
return;
}
- const { position, documentLayoutObject, canvasOffset, scaleX, scaleY, editorUnitId } = state;
+ const { position, documentLayoutObject, canvasOffset, scaleX, scaleY, editorUnitId, unitId } = state;
const editorObject = this._getEditorObject();
@@ -480,6 +480,8 @@ export class StartEditController extends Disposable {
},
]);
}
+
+ this._renderManagerService.getRenderById(unitId)?.scene.resetCursor();
});
}
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 9a459e4c54..55e32259e5 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -1,11 +1,13 @@
export * from './basics';
export { getEditorObject } from './basics/editor/get-editor-object';
+export { AutoFillCommand } from './commands/commands/auto-fill.command';
export { ExpandSelectionCommand, JumpOver, MoveSelectionCommand } from './commands/commands/set-selection.command';
export { SetCellEditVisibleArrowOperation } from './commands/operations/cell-edit.operation';
export { SetScrollOperation } from './commands/operations/scroll.operation';
export { SetEditorResizeOperation } from './commands/operations/set-editor-resize.operation';
export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
export { RangeSelector } from './components/range-selector/RangeSelector';
+export { AutoFillController } from './controllers/auto-fill.controller';
export { whenEditorInputFormulaActivated } from './controllers/shortcuts/utils';
export {
getCoordByCell,
@@ -13,10 +15,11 @@ export {
getSheetObject,
getTransformCoord,
} from './controllers/utils/component-tools';
-export { IAutoFillService } from './services/auto-fill/auto-fill.service';
+export { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';
export { getRepeatRange } from './services/auto-fill/tools';
-export type { IAutoFillHook } from './services/auto-fill/type';
-export { APPLY_TYPE, DATA_TYPE } from './services/auto-fill/type';
+export type { IAutoFillHook, ICopyDataPiece } from './services/auto-fill/type';
+export { APPLY_TYPE, DATA_TYPE, type IAutoFillRule } from './services/auto-fill/type';
+export { type ICopyDataInTypeIndexInfo } from './services/auto-fill/type';
export { CellEditorManagerService, ICellEditorManagerService } from './services/editor/cell-editor-manager.service';
export { IFormulaEditorManagerService } from './services/editor/formula-editor-manager.service';
export {
@@ -25,6 +28,7 @@ export {
type IEditorBridgeServiceVisibleParam,
} from './services/editor-bridge.service';
export { ISelectionRenderService } from './services/selection/selection-render.service';
+export { SelectionRenderService } from './services/selection/selection-render.service';
export { SelectionShape } from './services/selection/selection-shape';
export { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
export { SheetUIPlugin } from './sheet-ui-plugin';
diff --git a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
index c6ef3d5835..7591bed8a4 100644
--- a/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
+++ b/packages/sheets-ui/src/services/auto-fill/auto-fill.service.ts
@@ -18,7 +18,6 @@ import {
chnWeek2Rule,
chnWeek3Rule,
extendNumberRule,
- formulaRule,
loopSeriesRule,
numberRule,
otherRule,
@@ -93,7 +92,6 @@ export class AutoFillService extends Disposable implements IAutoFillService {
private _init() {
this._rules = [
- formulaRule,
numberRule,
extendNumberRule,
chnNumberRule,
diff --git a/packages/sheets-ui/src/services/auto-fill/rules.ts b/packages/sheets-ui/src/services/auto-fill/rules.ts
index 51904e8fb1..7ff7438584 100644
--- a/packages/sheets-ui/src/services/auto-fill/rules.ts
+++ b/packages/sheets-ui/src/services/auto-fill/rules.ts
@@ -1,11 +1,10 @@
-import { Direction, isFormulaString } from '@univerjs/core';
+import { Direction } from '@univerjs/core';
import {
chineseToNumber,
fillChnNumber,
fillChnWeek,
fillCopy,
- fillCopyFormula,
fillExtendNumber,
fillLoopSeries,
fillSeries,
@@ -352,25 +351,3 @@ export const loopSeriesRule: IAutoFillRule = {
},
},
};
-
-/**
- * TODO@Dushusir: move to formula plugin after register function is supported
- */
-export const formulaRule: IAutoFillRule = {
- type: DATA_TYPE.FORMULA,
- priority: 1000,
- match: (cellData) => isFormulaString(cellData?.f),
- isContinue: (prev, cur) => {
- if (prev.type === DATA_TYPE.FORMULA) {
- return true;
- }
- return false;
- },
- applyFunctions: {
- // FIXME@Dushusir: COPY not work
- [APPLY_TYPE.COPY]: (dataWithIndex, len, direction) => {
- const { data, index } = dataWithIndex; // TODO@Dushusir: now you have index infos when applying formula
- return fillCopyFormula(data, len, direction);
- },
- },
-};
diff --git a/packages/sheets-ui/src/services/auto-fill/tools.ts b/packages/sheets-ui/src/services/auto-fill/tools.ts
index 925c79712c..e34f3fc7f1 100644
--- a/packages/sheets-ui/src/services/auto-fill/tools.ts
+++ b/packages/sheets-ui/src/services/auto-fill/tools.ts
@@ -621,51 +621,6 @@ export function fillLoopSeries(data: Array<Nullable<ICellData>>, len: number, st
return applyData;
}
-/**
- * TODO@Dushusir: add step
- * @param data
- * @param len
- * @param direction
- * @returns
- */
-export function fillCopyFormula(data: Array<Nullable<ICellData>>, len: number, direction: Direction) {
- const applyData = [];
- let formulaId: string = '';
-
- for (let i = 1; i <= len; i++) {
- const index = (i - 1) % data.length;
- const d = Tools.deepClone(data[index]);
-
- if (d) {
- const originalFormula = data[index]?.f;
-
- if (originalFormula) {
- // The first position setting formula and formulaId
- if (i === 1) {
- const shiftedFormula = shiftFormula(originalFormula, i, direction);
- d.si = d.si || Tools.generateRandomId(6);
- formulaId = d.si;
- d.f = shiftedFormula;
- d.v = null;
- } else {
- // At the beginning of the second formula, set formulaId only
- d.si = formulaId;
- d.f = null;
- d.v = null;
- }
-
- if (direction === Direction.DOWN || direction === Direction.RIGHT) {
- applyData.push(d);
- } else {
- applyData.unshift(d);
- }
- }
- }
- }
-
- return applyData;
-}
-
export function getRepeatRange(sourceRange: IRange, targetRange: IRange) {
const repeats: Array<{
repeatStartCell: { col: number; row: number };
@@ -810,60 +765,3 @@ export function getRepeatRange(sourceRange: IRange, targetRange: IRange) {
return repeats;
}
-
-function shiftFormula(originalFormula: string, shift: number, direction: Direction): string {
- const tokens = tokenizeFormula(originalFormula);
- const shiftedTokens = [];
-
- for (const token of tokens) {
- if (isCellReference(token)) {
- const shiftedReference = shiftCellReference(token, shift, direction);
- shiftedTokens.push(shiftedReference);
- } else {
- shiftedTokens.push(token);
- }
- }
-
- return shiftedTokens.join('');
-}
-
-function tokenizeFormula(formula: string): string[] {
- const regex = /([A-Z]+\d+|[A-Z]+|\d+|\S)/g;
- return formula.match(regex) || [];
-}
-
-function isCellReference(token: string): boolean {
- const cellReferenceRegex = /^[A-Z]+\d+$/;
- return cellReferenceRegex.test(token);
-}
-
-function shiftCellReference(cellReference: string, shift: number, direction: Direction): string {
- const [col, row] = extractColRow(cellReference);
-
- let shiftedCol = col;
- let shiftedRow = row;
-
- if (direction === Direction.DOWN) {
- shiftedRow += shift;
- } else if (direction === Direction.RIGHT) {
- shiftedCol = shiftColumn(col, shift);
- } else if (direction === Direction.UP) {
- shiftedRow -= shift;
- } else if (direction === Direction.LEFT) {
- shiftedCol = shiftColumn(col, -shift);
- }
-
- return shiftedCol + shiftedRow;
-}
-
-function extractColRow(cellReference: string): [string, number] {
- const col = cellReference.replace(/\d/g, '');
- const row = parseInt(cellReference.replace(/[A-Z]+/g, ''), 10);
- return [col, row];
-}
-
-function shiftColumn(col: string, shift: number): string {
- const currentCharCode = col.charCodeAt(0);
- const shiftedCharCode = currentCharCode + shift;
- return String.fromCharCode(shiftedCharCode);
-}
diff --git a/packages/sheets-ui/src/services/auto-fill/type.ts b/packages/sheets-ui/src/services/auto-fill/type.ts
index 2539f47fec..7ffa2f83bb 100644
--- a/packages/sheets-ui/src/services/auto-fill/type.ts
+++ b/packages/sheets-ui/src/services/auto-fill/type.ts
@@ -54,7 +54,8 @@ export type APPLY_FUNCTIONS = {
[key in APPLY_TYPE]?: (
dataWithIndex: ICopyDataInType,
len: number,
- direction: Direction
+ direction: Direction,
+ copyDataPiece: ICopyDataPiece
) => Array<Nullable<ICellData>>;
};
diff --git a/packages/sheets-ui/src/services/clipboard/__test__/clipboard-service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
similarity index 100%
rename from packages/sheets-ui/src/services/clipboard/__test__/clipboard-service.spec.ts
rename to packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
diff --git a/packages/sheets-ui/src/services/clipboard/__test__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
similarity index 100%
rename from packages/sheets-ui/src/services/clipboard/__test__/clipboard-test-bed.ts
rename to packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
diff --git a/packages/sheets-ui/src/services/clipboard/__test__/mock-clipboard.ts b/packages/sheets-ui/src/services/clipboard/__tests__/mock-clipboard.ts
similarity index 100%
rename from packages/sheets-ui/src/services/clipboard/__test__/mock-clipboard.ts
rename to packages/sheets-ui/src/services/clipboard/__tests__/mock-clipboard.ts
diff --git a/packages/sheets-ui/src/services/selection/selection-shape.ts b/packages/sheets-ui/src/services/selection/selection-shape.ts
index a8167a9b89..de5bd21b28 100644
--- a/packages/sheets-ui/src/services/selection/selection-shape.ts
+++ b/packages/sheets-ui/src/services/selection/selection-shape.ts
@@ -385,14 +385,16 @@ export class SelectionShape {
AutofillSize /= scale;
AutofillStrokeWidth /= scale;
- const leftAdjustWidth = strokeWidth + SELECTION_CONTROL_BORDER_BUFFER_WIDTH;
+ const borderBuffer = SELECTION_CONTROL_BORDER_BUFFER_WIDTH / scale;
+
+ const leftAdjustWidth = strokeWidth + borderBuffer;
this.leftControl.transformByState({
height: endY - startY,
left: -leftAdjustWidth / 2,
width: strokeWidth,
- strokeWidth: SELECTION_CONTROL_BORDER_BUFFER_WIDTH,
- top: -SELECTION_CONTROL_BORDER_BUFFER_WIDTH / 2,
+ strokeWidth: borderBuffer,
+ top: -borderBuffer / 2,
});
this.leftControl.setProps({
@@ -404,8 +406,8 @@ export class SelectionShape {
height: endY - startY,
left: endX - startX - leftAdjustWidth / 2,
width: strokeWidth,
- strokeWidth: SELECTION_CONTROL_BORDER_BUFFER_WIDTH,
- top: -SELECTION_CONTROL_BORDER_BUFFER_WIDTH / 2,
+ strokeWidth: borderBuffer,
+ top: -borderBuffer / 2,
});
this.rightControl.setProps({
@@ -418,7 +420,7 @@ export class SelectionShape {
top: -leftAdjustWidth / 2,
left: -leftAdjustWidth / 2,
height: strokeWidth,
- strokeWidth: SELECTION_CONTROL_BORDER_BUFFER_WIDTH,
+ strokeWidth: borderBuffer,
});
this.topControl.setProps({
@@ -431,7 +433,7 @@ export class SelectionShape {
top: endY - startY - leftAdjustWidth / 2,
height: strokeWidth,
left: -leftAdjustWidth / 2,
- strokeWidth: SELECTION_CONTROL_BORDER_BUFFER_WIDTH,
+ strokeWidth: borderBuffer,
});
this.bottomControl.setProps({
diff --git a/packages/sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
index a0440b9fb8..f69ff0de84 100644
--- a/packages/sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/clear-selection.command.spec.ts
@@ -1,5 +1,12 @@
import type { ICellData, IRange, IStyleData, Nullable, Univer } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
+import {
+ CellValueType,
+ ICommandService,
+ IUniverInstanceService,
+ RANGE_TYPE,
+ RedoCommand,
+ UndoCommand,
+} from '@univerjs/core';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -74,6 +81,7 @@ describe('Test clear selection content commands', () => {
expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
expect(getValue()).toStrictEqual({
v: 'A1',
+ t: CellValueType.STRING,
});
// redo
expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
diff --git a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
index fca7c1cff7..60b76da1e0 100644
--- a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
@@ -29,7 +29,7 @@ import {
InsertRowBeforeCommand,
InsertRowCommand,
} from '../insert-row-col.command';
-import type { RemoveRowColCommandParams } from '../remove-row-col.command';
+import type { IRemoveRowColCommandParams } from '../remove-row-col.command';
import { RemoveColCommand, RemoveRowCommand } from '../remove-row-col.command';
import { createCommandTestBed } from './create-command-test-bed';
@@ -288,7 +288,7 @@ describe('Test insert and remove rows cols commands', () => {
endColumn: 1,
},
],
- } as RemoveRowColCommandParams);
+ } as IRemoveRowColCommandParams);
expect(getMergedInfo(12, 2)).toEqual({ startRow: 10, endRow: 13, startColumn: 2, endColumn: 2 });
});
});
@@ -303,7 +303,7 @@ describe('Test insert and remove rows cols commands', () => {
endColumn: 13,
},
],
- } as RemoveRowColCommandParams);
+ } as IRemoveRowColCommandParams);
expect(getMergedInfo(10, 12)).toEqual({ startRow: 10, endRow: 10, startColumn: 10, endColumn: 13 });
});
});
diff --git a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
index d71cc37fc7..c6b0aaf67f 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts
@@ -126,6 +126,7 @@ describe('Test set range values commands', () => {
expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
expect(getValue()).toStrictEqual({
v: 'A1',
+ t: CellValueType.STRING,
});
// redo
diff --git a/packages/sheets/src/commands/commands/delete-range-move-left.command.ts b/packages/sheets/src/commands/commands/delete-range-move-left.command.ts
index 117458f7ba..08826e47a3 100644
--- a/packages/sheets/src/commands/commands/delete-range-move-left.command.ts
+++ b/packages/sheets/src/commands/commands/delete-range-move-left.command.ts
@@ -18,7 +18,7 @@ import { SelectionManagerService } from '../../services/selection-manager.servic
import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../mutations/delete-range.mutation';
import { InsertRangeMutation } from '../mutations/insert-range.mutation';
-export interface DeleteRangeMoveLeftCommandParams {
+export interface IDeleteRangeMoveLeftCommandParams {
ranges: IRange[];
}
@@ -30,7 +30,7 @@ export const DeleteRangeMoveLeftCommand: ICommand = {
type: CommandType.COMMAND,
id: DeleteRangeMoveLeftCommandId,
- handler: async (accessor: IAccessor, params?: DeleteRangeMoveLeftCommandParams) => {
+ handler: async (accessor: IAccessor, params?: IDeleteRangeMoveLeftCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -69,7 +69,7 @@ export const DeleteRangeMoveLeftCommand: ICommand = {
const sheetInterceptor = sheetInterceptorService.onCommandExecute({
id: DeleteRangeMoveLeftCommand.id,
- params: { ranges } as DeleteRangeMoveLeftCommandParams,
+ params: { ranges } as IDeleteRangeMoveLeftCommandParams,
});
const redos: IMutationInfo[] = [{ id: DeleteRangeMutation.id, params: deleteRangeMutationParams }];
const undos: IMutationInfo[] = [{ id: InsertRangeMutation.id, params: insertRangeMutationParams }];
diff --git a/packages/sheets/src/commands/commands/delete-range-move-up.command.ts b/packages/sheets/src/commands/commands/delete-range-move-up.command.ts
index 892ed4c88c..7cef762e5f 100644
--- a/packages/sheets/src/commands/commands/delete-range-move-up.command.ts
+++ b/packages/sheets/src/commands/commands/delete-range-move-up.command.ts
@@ -18,7 +18,7 @@ import { SelectionManagerService } from '../../services/selection-manager.servic
import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../mutations/delete-range.mutation';
import { InsertRangeMutation } from '../mutations/insert-range.mutation';
-export interface DeleteRangeMoveUpCommandParams {
+export interface IDeleteRangeMoveUpCommandParams {
ranges: IRange[];
}
export const DeleteRangeMoveUpCommandId = 'sheet.command.delete-range-move-up';
@@ -29,7 +29,7 @@ export const DeleteRangeMoveUpCommand: ICommand = {
type: CommandType.COMMAND,
id: DeleteRangeMoveUpCommandId,
- handler: async (accessor: IAccessor, params: DeleteRangeMoveUpCommandParams) => {
+ handler: async (accessor: IAccessor, params: IDeleteRangeMoveUpCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -68,7 +68,7 @@ export const DeleteRangeMoveUpCommand: ICommand = {
const sheetInterceptor = sheetInterceptorService.onCommandExecute({
id: DeleteRangeMoveUpCommand.id,
- params: { ranges } as DeleteRangeMoveUpCommandParams,
+ params: { ranges } as IDeleteRangeMoveUpCommandParams,
});
const redos: IMutationInfo[] = [{ id: DeleteRangeMutation.id, params: deleteRangeMutationParams }];
const undos: IMutationInfo[] = [{ id: InsertRangeMutation.id, params: insertRangeMutationParams }];
diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.ts
index c15d70a8e7..daa60e848c 100644
--- a/packages/sheets/src/commands/commands/move-range.command.ts
+++ b/packages/sheets/src/commands/commands/move-range.command.ts
@@ -11,7 +11,7 @@ import {
import type { IAccessor } from '@wendellhu/redi';
import { NORMAL_SELECTION_PLUGIN_NAME } from '../../services/selection-manager.service';
-import type { MoveRangeMutationParams } from '../mutations/move-range.mutation';
+import type { IMoveRangeMutationParams } from '../mutations/move-range.mutation';
import { MoveRangeMutation } from '../mutations/move-range.mutation';
import { SetSelectionsOperation } from '../operations/selection.operation';
@@ -63,13 +63,13 @@ export const MoveRangeCommand: ICommand = {
return res;
}, new ObjectMatrix<ICellData | null>());
- const doMoveRangeMutation: MoveRangeMutationParams = {
+ const doMoveRangeMutation: IMoveRangeMutationParams = {
from: newFromCellValues.getMatrix(),
to: newToCellValues.getMatrix(),
workbookId,
worksheetId,
};
- const undoMoveRangeMutation: MoveRangeMutationParams = {
+ const undoMoveRangeMutation: IMoveRangeMutationParams = {
from: currentFromCellValues.getMatrix(),
to: currentToCellValues.getMatrix(),
workbookId,
diff --git a/packages/sheets/src/commands/commands/move-rows-cols.command.ts b/packages/sheets/src/commands/commands/move-rows-cols.command.ts
index ea152acf55..98279ac9f8 100644
--- a/packages/sheets/src/commands/commands/move-rows-cols.command.ts
+++ b/packages/sheets/src/commands/commands/move-rows-cols.command.ts
@@ -8,6 +8,7 @@ import {
RANGE_TYPE,
Rectangle,
sequenceExecute,
+ SheetInterceptorService,
Tools,
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
@@ -59,6 +60,7 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {
return false;
}
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUniverSheetInstance();
if (!workbook) {
@@ -165,32 +167,33 @@ export const MoveRowsCommand: ICommand<IMoveRowsCommandParams> = {
};
const commandService = accessor.get(ICommandService);
- const result = sequenceExecute(
- [
- { id: MoveRowsMutation.id, params: moveRowsParams },
- { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },
- { id: AddWorksheetMergeMutation.id, params: addMergeParams },
- { id: SetSelectionsOperation.id, params: setSelectionsParam },
- ],
- commandService
- );
+
+ const interceptorCommands = sheetInterceptorService.onCommandExecute({ id: MoveRowsCommand.id, params });
+
+ const redos = [
+ { id: MoveRowsMutation.id, params: moveRowsParams },
+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },
+ { id: AddWorksheetMergeMutation.id, params: addMergeParams },
+ { id: SetSelectionsOperation.id, params: setSelectionsParam },
+ ...interceptorCommands.redos,
+ ];
+
+ const undos = [
+ { id: MoveRowsMutation.id, params: undoMoveRowsParams },
+ { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams },
+ { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },
+ { id: SetSelectionsOperation.id, params: undoSetSelectionsParam },
+ ...interceptorCommands.undos,
+ ];
+
+ const result = sequenceExecute(redos, commandService);
if (result.result) {
const undoRedoService = accessor.get(IUndoRedoService);
undoRedoService.pushUndoRedo({
unitID: workbookId,
- undoMutations: [
- { id: MoveRowsMutation.id, params: undoMoveRowsParams },
- { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams },
- { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },
- { id: SetSelectionsOperation.id, params: undoSetSelectionsParam },
- ],
- redoMutations: [
- { id: MoveRowsMutation.id, params: moveRowsParams },
- { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },
- { id: AddWorksheetMergeMutation.id, params: addMergeParams },
- { id: SetSelectionsOperation.id, params: setSelectionsParam },
- ],
+ undoMutations: undos,
+ redoMutations: redos,
});
return true;
}
@@ -221,6 +224,7 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {
return false;
}
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUniverSheetInstance();
if (!workbook) {
@@ -329,32 +333,33 @@ export const MoveColsCommand: ICommand<IMoveColsCommandParams> = {
};
const commandService = accessor.get(ICommandService);
- const result = sequenceExecute(
- [
- { id: MoveColsMutation.id, params: moveColsParams },
- { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },
- { id: AddWorksheetMergeMutation.id, params: addMergeParams },
- { id: SetSelectionsOperation.id, params: setSelectionsParam },
- ],
- commandService
- );
+
+ const interceptorCommands = sheetInterceptorService.onCommandExecute({ id: MoveColsCommand.id, params });
+
+ const redos = [
+ { id: MoveColsMutation.id, params: moveColsParams },
+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },
+ { id: AddWorksheetMergeMutation.id, params: addMergeParams },
+ { id: SetSelectionsOperation.id, params: setSelectionsParam },
+ ...interceptorCommands.redos,
+ ];
+
+ const undos = [
+ { id: MoveColsMutation.id, params: undoMoveColsParams },
+ { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams },
+ { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },
+ { id: SetSelectionsOperation.id, params: undoSetSelectionsParam },
+ ...interceptorCommands.undos,
+ ];
+
+ const result = sequenceExecute(redos, commandService);
if (result.result) {
const undoRedoService = accessor.get(IUndoRedoService);
undoRedoService.pushUndoRedo({
unitID: workbookId,
- undoMutations: [
- { id: MoveColsMutation.id, params: undoMoveColsParams },
- { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeParams },
- { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },
- { id: SetSelectionsOperation.id, params: undoSetSelectionsParam },
- ],
- redoMutations: [
- { id: MoveColsMutation.id, params: moveColsParams },
- { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },
- { id: AddWorksheetMergeMutation.id, params: addMergeParams },
- { id: SetSelectionsOperation.id, params: setSelectionsParam },
- ],
+ undoMutations: undos,
+ redoMutations: redos,
});
return true;
}
diff --git a/packages/sheets/src/commands/commands/remove-row-col.command.ts b/packages/sheets/src/commands/commands/remove-row-col.command.ts
index d3a74aa9bf..7e91ddc5a5 100644
--- a/packages/sheets/src/commands/commands/remove-row-col.command.ts
+++ b/packages/sheets/src/commands/commands/remove-row-col.command.ts
@@ -30,7 +30,7 @@ import {
RemoveRowsUndoMutationFactory,
} from '../mutations/remove-row-col.mutation';
-export interface RemoveRowColCommandParams {
+export interface IRemoveRowColCommandParams {
ranges: IRange[];
}
export const RemoveRowCommandId = 'sheet.command.remove-row';
@@ -40,7 +40,7 @@ export const RemoveRowCommandId = 'sheet.command.remove-row';
export const RemoveRowCommand: ICommand = {
type: CommandType.COMMAND,
id: RemoveRowCommandId,
- handler: async (accessor: IAccessor, params?: RemoveRowColCommandParams) => {
+ handler: async (accessor: IAccessor, params?: IRemoveRowColCommandParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
@@ -92,7 +92,7 @@ export const RemoveRowCommand: ICommand = {
const intercepted = sheetInterceptorService.onCommandExecute({
id: RemoveRowCommand.id,
- params: { ranges } as RemoveRowColCommandParams,
+ params: { ranges } as IRemoveRowColCommandParams,
});
const commandService = accessor.get(ICommandService);
@@ -133,7 +133,7 @@ export const RemoveColCommand: ICommand = {
type: CommandType.COMMAND,
id: RemoveColCommandId,
// eslint-disable-next-line max-lines-per-function
- handler: async (accessor: IAccessor, params?: RemoveRowColCommandParams) => {
+ handler: async (accessor: IAccessor, params?: IRemoveRowColCommandParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
let ranges = params?.ranges;
@@ -182,7 +182,7 @@ export const RemoveColCommand: ICommand = {
const intercepted = sheetInterceptorService.onCommandExecute({
id: RemoveColCommand.id,
- params: { ranges } as RemoveRowColCommandParams,
+ params: { ranges } as IRemoveRowColCommandParams,
});
const commandService = accessor.get(ICommandService);
const result = sequenceExecute(
diff --git a/packages/sheets/src/commands/commands/set-range-formatted-value.command.ts b/packages/sheets/src/commands/commands/set-range-formatted-value.command.ts
deleted file mode 100644
index 296daa4256..0000000000
--- a/packages/sheets/src/commands/commands/set-range-formatted-value.command.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import type { ICellV, ICommand } from '@univerjs/core';
-import {
- CommandType,
- ICommandService,
- IUndoRedoService,
- IUniverInstanceService,
- ObjectMatrix,
- Tools,
-} from '@univerjs/core';
-import type { IAccessor } from '@wendellhu/redi';
-
-import { SelectionManagerService } from '../../services/selection-manager.service';
-import type { ISetRangeFormattedValueMutationParams } from '../mutations/set-range-formatted-value.mutation';
-import {
- SetRangeFormattedValueMutation,
- SetRangeFormattedValueUndoMutationFactory,
-} from '../mutations/set-range-formatted-value.mutation';
-
-export interface ISetRangeFormattedValueParams {
- value: ICellV | ICellV[][] | ObjectMatrix<ICellV>;
-}
-
-/**
- * The command to set range formatted value.
- */
-export const SetRangeFormattedValueCommand: ICommand = {
- type: CommandType.COMMAND,
- id: 'sheet.command.set-range-formatted-value',
-
- handler: async (accessor: IAccessor, params: ISetRangeFormattedValueParams) => {
- const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const selectionManagerService = accessor.get(SelectionManagerService);
-
- const ranges = selectionManagerService.getSelectionRanges();
- if (!ranges?.length) {
- return false;
- }
-
- const workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = univerInstanceService
- .getCurrentUniverSheetInstance()
-
- .getActiveSheet()
- .getSheetId();
-
- const workbook = univerInstanceService.getUniverSheetInstance(workbookId);
- if (!workbook) return false;
- const worksheet = workbook.getSheetBySheetId(worksheetId);
- if (!worksheet) return false;
-
- let cellValue = new ObjectMatrix<ICellV>();
- const value = params.value;
- for (let i = 0; i < ranges.length; i++) {
- const range = ranges[i];
- const { startRow, startColumn, endRow, endColumn } = range;
- if (Tools.isArray(value)) {
- for (let r = 0; r <= endRow - startRow; r++) {
- for (let c = 0; c <= endColumn - startColumn; c++) {
- cellValue.setValue(r + startRow, c + startColumn, value[r][c]);
- }
- }
- } else if (Tools.isAssignableFrom(value, ObjectMatrix)) {
- cellValue = value;
- } else {
- for (let r = startRow; r <= endRow; r++) {
- for (let c = startColumn; c <= endColumn; c++) {
- cellValue.setValue(r, c, value as ICellV);
- }
- }
- }
- }
-
- const setRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams = {
- range: ranges,
- worksheetId,
- workbookId,
- value: cellValue.getData(),
- };
-
- const undoSetRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams =
- SetRangeFormattedValueUndoMutationFactory(accessor, setRangeFormattedValueMutationParams);
-
- // execute do mutations and add undo mutations to undo stack if completed
- const result = commandService.syncExecuteCommand(
- SetRangeFormattedValueMutation.id,
- setRangeFormattedValueMutationParams
- );
- if (result) {
- undoRedoService.pushUndoRedo({
- unitID: workbookId,
- undoMutations: [
- { id: SetRangeFormattedValueMutation.id, params: undoSetRangeFormattedValueMutationParams },
- ],
- redoMutations: [
- { id: SetRangeFormattedValueMutation.id, params: setRangeFormattedValueMutationParams },
- ],
- });
-
- return true;
- }
-
- return false;
- },
- // all subsequent mutations should succeed inorder to make the whole process succeed
- // Promise.all([]).then(() => true),
-};
diff --git a/packages/sheets/src/commands/commands/trim-whitespace.command.ts b/packages/sheets/src/commands/commands/trim-whitespace.command.ts
deleted file mode 100644
index 62f5c73e45..0000000000
--- a/packages/sheets/src/commands/commands/trim-whitespace.command.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import type { ICellV, ICommand } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
-import type { IAccessor } from '@wendellhu/redi';
-
-import { SelectionManagerService } from '../../services/selection-manager.service';
-import type { ISetRangeFormattedValueMutationParams } from '../mutations/set-range-formatted-value.mutation';
-import {
- SetRangeFormattedValueMutation,
- SetRangeFormattedValueUndoMutationFactory,
-} from '../mutations/set-range-formatted-value.mutation';
-
-/**
- * The command to trim whitespace.
- */
-export const TrimWhitespaceCommand: ICommand = {
- type: CommandType.COMMAND,
- id: 'sheet.command.trim-whitespace',
-
- handler: async (accessor: IAccessor) => {
- const selectionManagerService = accessor.get(SelectionManagerService);
- const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
-
- const selections = selectionManagerService.getSelectionRanges();
- if (!selections?.length) return false;
-
- const workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = univerInstanceService
- .getCurrentUniverSheetInstance()
-
- .getActiveSheet()
- .getSheetId();
-
- const worksheet = univerInstanceService.getUniverSheetInstance(workbookId)?.getSheetBySheetId(worksheetId);
- if (!worksheet) return false;
- const sheetMatrix = worksheet.getCellMatrix();
- const cellValue = new ObjectMatrix<ICellV>();
-
- for (let i = 0; i < selections.length; i++) {
- const { startRow, endRow, startColumn, endColumn } = selections[i];
- const regx = /\s+/g;
- for (let r = startRow; r <= endRow; r++) {
- for (let c = startColumn; c <= endColumn; c++) {
- const value = sheetMatrix.getValue(r, c)!.m?.replace(regx, '');
- cellValue.setValue(r, c, value || '');
- }
- }
- }
-
- const setRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams = {
- range: selections,
- worksheetId,
- workbookId,
- value: cellValue.getData(),
- };
-
- const undoSetRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams =
- SetRangeFormattedValueUndoMutationFactory(accessor, setRangeFormattedValueMutationParams);
-
- // execute do mutations and add undo mutations to undo stack if completed
- const result = commandService.syncExecuteCommand(
- SetRangeFormattedValueMutation.id,
- setRangeFormattedValueMutationParams
- );
- if (result) {
- undoRedoService.pushUndoRedo({
- unitID: workbookId,
- undoMutations: [
- { id: SetRangeFormattedValueMutation.id, params: undoSetRangeFormattedValueMutationParams },
- ],
- redoMutations: [
- { id: SetRangeFormattedValueMutation.id, params: setRangeFormattedValueMutationParams },
- ],
- });
-
- return true;
- }
-
- return false;
- },
- // all subsequent mutations should succeed inorder to make the whole process succeed
- // Promise.all([]).then(() => true),
-};
diff --git a/packages/sheets/src/commands/mutations/delete-range.mutation.ts b/packages/sheets/src/commands/mutations/delete-range.mutation.ts
index 7a59f362ea..389d0c36e5 100644
--- a/packages/sheets/src/commands/mutations/delete-range.mutation.ts
+++ b/packages/sheets/src/commands/mutations/delete-range.mutation.ts
@@ -1,4 +1,4 @@
-import type { ICellData, IMutation, Nullable } from '@univerjs/core';
+import type { ICellData, IMutation, IRange, Nullable } from '@univerjs/core';
import { CommandType, Dimension, IUniverInstanceService, ObjectMatrix, Tools } from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
@@ -72,44 +72,63 @@ export const DeleteRangeMutation: IMutation<IDeleteRangeMutationParams, boolean>
id: 'sheet.mutation.delete-range',
type: CommandType.MUTATION,
handler: (accessor, params) => {
+ const { workbookId, worksheetId, ranges, shiftDimension } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
- const workbook = univerInstanceService.getUniverSheetInstance(params.workbookId);
+ const workbook = univerInstanceService.getUniverSheetInstance(workbookId);
if (!workbook) return false;
- const worksheet = workbook.getSheetBySheetId(params.worksheetId);
+ const worksheet = workbook.getSheetBySheetId(worksheetId);
if (!worksheet) return false;
const cellMatrix = worksheet.getCellMatrix();
const lastEndRow = worksheet.getLastRowWithContent();
const lastEndColumn = worksheet.getLastColumnWithContent();
- for (let i = 0; i < params.ranges.length; i++) {
- const { startRow, endRow, startColumn, endColumn } = params.ranges[i];
+ handleDeleteRangeMutation(cellMatrix, ranges, lastEndRow, lastEndColumn, shiftDimension);
- const rows = endRow - startRow + 1;
- const columns = endColumn - startColumn + 1;
+ return true;
+ },
+};
+
+export function handleDeleteRangeMutation<T>(
+ cellMatrix: ObjectMatrix<T>,
+ ranges: IRange[],
+ lastEndRow: number,
+ lastEndColumn: number,
+ shiftDimension: Dimension
+) {
+ for (let i = 0; i < ranges.length; i++) {
+ const { startRow, endRow, startColumn, endColumn } = ranges[i];
+
+ const rows = endRow - startRow + 1;
+ const columns = endColumn - startColumn + 1;
- if (params.shiftDimension === Dimension.ROWS) {
- // build new data
- for (let r = startRow; r <= lastEndRow; r++) {
- for (let c = startColumn; c <= endColumn; c++) {
- // get value blow current range
- const value = cellMatrix.getValue(r + rows, c);
- cellMatrix.setValue(r, c, value || {});
+ if (shiftDimension === Dimension.ROWS) {
+ // build new data
+ for (let r = startRow; r <= lastEndRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ // get value blow current range
+ const value = cellMatrix.getValue(r + rows, c);
+ if (value == null) {
+ cellMatrix.realDeleteValue(r, c);
+ } else {
+ cellMatrix.setValue(r, c, value);
}
}
- } else if (params.shiftDimension === Dimension.COLUMNS) {
- // build new data
- for (let r = startRow; r <= endRow; r++) {
- for (let c = startColumn; c <= lastEndColumn; c++) {
- // get value blow current range
+ }
+ } else if (shiftDimension === Dimension.COLUMNS) {
+ // build new data
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= lastEndColumn; c++) {
+ // get value blow current range
- const value = cellMatrix.getValue(r, c + columns);
- cellMatrix.setValue(r, c, value || {});
+ const value = cellMatrix.getValue(r, c + columns);
+ if (value == null) {
+ cellMatrix.realDeleteValue(r, c);
+ } else {
+ cellMatrix.setValue(r, c, value);
}
}
}
}
-
- return true;
- },
-};
+ }
+}
diff --git a/packages/sheets/src/commands/mutations/insert-range.mutation.ts b/packages/sheets/src/commands/mutations/insert-range.mutation.ts
index 02cba83397..09ead4cdb0 100644
--- a/packages/sheets/src/commands/mutations/insert-range.mutation.ts
+++ b/packages/sheets/src/commands/mutations/insert-range.mutation.ts
@@ -1,4 +1,4 @@
-import type { ICellData, IMutation } from '@univerjs/core';
+import type { IMutation, IRange, ObjectMatrix, ObjectMatrixPrimitiveType } from '@univerjs/core';
import { CommandType, Dimension, IUniverInstanceService } from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
@@ -28,55 +28,82 @@ export const InsertRangeMutation: IMutation<IInsertRangeMutationParams, boolean>
id: 'sheet.mutation.insert-range',
type: CommandType.MUTATION,
handler: (accessor, params) => {
+ const { workbookId, worksheetId, ranges, cellValue, shiftDimension } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
- const workbook = univerInstanceService.getUniverSheetInstance(params.workbookId);
+ const workbook = univerInstanceService.getUniverSheetInstance(workbookId);
if (!workbook) return false;
- const worksheet = workbook.getSheetBySheetId(params.worksheetId);
+ const worksheet = workbook.getSheetBySheetId(worksheetId);
if (!worksheet) return false;
const cellMatrix = worksheet.getCellMatrix();
const lastEndRow = worksheet.getLastRowWithContent();
const lastEndColumn = worksheet.getLastColumnWithContent();
- for (let i = 0; i < params.ranges.length; i++) {
- const { startRow, endRow, startColumn, endColumn } = params.ranges[i];
- const rows = endRow - startRow + 1;
- const columns = endColumn - startColumn + 1;
+ handleInsertRangeMutation(cellMatrix, ranges, lastEndRow, lastEndColumn, shiftDimension, cellValue);
+
+ return true;
+ },
+};
- if (params.shiftDimension === Dimension.ROWS) {
- // build new data
- for (let r = lastEndRow; r >= startRow; r--) {
- for (let c = startColumn; c <= endColumn; c++) {
- // get value blow current range
+export function handleInsertRangeMutation<T>(
+ cellMatrix: ObjectMatrix<T>,
+ ranges: IRange[],
+ lastEndRow: number,
+ lastEndColumn: number,
+ shiftDimension: Dimension,
+ cellValue?: ObjectMatrixPrimitiveType<T>
+) {
+ for (let i = 0; i < ranges.length; i++) {
+ const { startRow, endRow, startColumn, endColumn } = ranges[i];
+ if (shiftDimension === Dimension.ROWS) {
+ const rows = endRow - startRow + 1;
+ // build new data
+ for (let r = lastEndRow; r >= startRow; r--) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ // get value blow current range
- const value = cellMatrix.getValue(r, c);
- cellMatrix.setValue(r + rows, c, value || {});
+ const value = cellMatrix.getValue(r, c);
+ if (value == null) {
+ cellMatrix.realDeleteValue(r + rows, c);
+ } else {
+ cellMatrix.setValue(r + rows, c, value);
}
}
- // insert cell value from user
- for (let r = endRow; r >= startRow; r--) {
- for (let c = startColumn; c <= endColumn; c++) {
- cellMatrix.setValue(r, c, params.cellValue[r][c]);
+ }
+ // insert cell value from user
+ for (let r = endRow; r >= startRow; r--) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ if (cellValue) {
+ cellMatrix.setValue(r, c, cellValue[r][c]);
+ } else {
+ cellMatrix.realDeleteValue(r, c);
}
}
- } else if (params.shiftDimension === Dimension.COLUMNS) {
- for (let r = startRow; r <= endRow; r++) {
- for (let c = lastEndColumn; c >= startColumn; c--) {
- // get value blow current range
- const value = cellMatrix.getValue(r, c);
+ }
+ } else if (shiftDimension === Dimension.COLUMNS) {
+ const columns = endColumn - startColumn + 1;
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = lastEndColumn; c >= startColumn; c--) {
+ // get value blow current range
+ const value = cellMatrix.getValue(r, c);
- cellMatrix.setValue(r, c + columns, value as ICellData);
+ if (value == null) {
+ cellMatrix.realDeleteValue(r, c + columns);
+ } else {
+ cellMatrix.setValue(r, c + columns, value);
}
}
- // insert cell value from user
- for (let r = startRow; r <= endRow; r++) {
- for (let c = endColumn; c >= startColumn; c--) {
- cellMatrix.setValue(r, c, params.cellValue[r][c]);
+ }
+ // insert cell value from user
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = endColumn; c >= startColumn; c--) {
+ if (cellValue) {
+ cellMatrix.setValue(r, c, cellValue[r][c]);
+ } else {
+ cellMatrix.realDeleteValue(r, c);
}
}
}
}
-
- return true;
- },
-};
+ }
+}
diff --git a/packages/sheets/src/commands/mutations/move-range.mutation.ts b/packages/sheets/src/commands/mutations/move-range.mutation.ts
index 38ea9ce065..9c23ee0f14 100644
--- a/packages/sheets/src/commands/mutations/move-range.mutation.ts
+++ b/packages/sheets/src/commands/mutations/move-range.mutation.ts
@@ -1,14 +1,14 @@
import type { ICellData, IMutation, ObjectMatrixPrimitiveType } from '@univerjs/core';
import { CommandType, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
-export interface MoveRangeMutationParams {
+export interface IMoveRangeMutationParams {
workbookId: string;
worksheetId: string;
from: ObjectMatrixPrimitiveType<ICellData | null>;
to: ObjectMatrixPrimitiveType<ICellData | null>;
}
-export const MoveRangeMutation: IMutation<MoveRangeMutationParams, boolean> = {
+export const MoveRangeMutation: IMutation<IMoveRangeMutationParams, boolean> = {
id: 'sheet.mutation.move-range',
type: CommandType.MUTATION,
handler: (accessor, params) => {
diff --git a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
index 25acd187c3..20521b2f16 100644
--- a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -153,7 +153,10 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
cellMatrix?.setValue(row, col, {});
} else {
const oldVal = cellMatrix.getValue(row, col) || {};
- const type = newVal.t ? newVal.t : checkCellValueType(newVal.v === undefined ? oldVal.v : newVal.v);
+ const type =
+ newVal.t === CellValueType.FORCE_STRING
+ ? newVal.t
+ : checkCellValueType(newVal.v === undefined ? oldVal.v : newVal.v);
if (newVal.f !== undefined) {
oldVal.f = newVal.f;
@@ -177,9 +180,7 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
oldVal.m = newVal.m;
}
- if (newVal.t !== undefined) {
- oldVal.t = newVal.t;
- } else if (oldVal.v !== undefined) {
+ if (oldVal.v !== undefined) {
oldVal.t = type;
}
diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.ts
index aaba19e085..0f2e3ced8c 100644
--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts
+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts
@@ -44,7 +44,6 @@ import {
} from '../commands/commands/set-col-visible.command';
import { SetFrozenCommand } from '../commands/commands/set-frozen.command';
import { SetFrozenCancelCommand } from '../commands/commands/set-frozen-cancel.command';
-import { SetRangeFormattedValueCommand } from '../commands/commands/set-range-formatted-value.command';
import { SetRangeValuesCommand } from '../commands/commands/set-range-values.command';
import {
SetRowHiddenCommand,
@@ -74,7 +73,6 @@ import {
SetWorksheetRowIsAutoHeightCommand,
} from '../commands/commands/set-worksheet-row-height.command';
import { SetWorksheetShowCommand } from '../commands/commands/set-worksheet-show.command';
-import { TrimWhitespaceCommand } from '../commands/commands/trim-whitespace.command';
import { AddWorksheetMergeMutation } from '../commands/mutations/add-worksheet-merge.mutation';
import { DeleteRangeMutation } from '../commands/mutations/delete-range.mutation';
import { InsertRangeMutation } from '../commands/mutations/insert-range.mutation';
@@ -178,7 +176,6 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetFrozenCommand,
SetFrozenMutation,
SetHorizontalTextAlignCommand,
- SetRangeFormattedValueCommand,
SetRangeFormattedValueMutation,
SetRangeValuesCommand,
SetRangeValuesMutation,
@@ -211,7 +208,6 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetWorksheetRowIsAutoHeightCommand,
SetWorksheetRowIsAutoHeightMutation,
SetWorksheetShowCommand,
- TrimWhitespaceCommand,
SetNumfmtMutation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
diff --git a/packages/sheets/src/controllers/merge-cell.controller.ts b/packages/sheets/src/controllers/merge-cell.controller.ts
index 4d88cd3f43..9e426d1920 100644
--- a/packages/sheets/src/controllers/merge-cell.controller.ts
+++ b/packages/sheets/src/controllers/merge-cell.controller.ts
@@ -21,9 +21,9 @@ import type {
import { getAddMergeMutationRangeByType } from '../commands/commands/add-worksheet-merge.command';
import { ClearSelectionAllCommand } from '../commands/commands/clear-selection-all.command';
import { ClearSelectionFormatCommand } from '../commands/commands/clear-selection-format.command';
-import type { DeleteRangeMoveLeftCommandParams } from '../commands/commands/delete-range-move-left.command';
+import type { IDeleteRangeMoveLeftCommandParams } from '../commands/commands/delete-range-move-left.command';
import { DeleteRangeMoveLeftCommand } from '../commands/commands/delete-range-move-left.command';
-import type { DeleteRangeMoveUpCommandParams } from '../commands/commands/delete-range-move-up.command';
+import type { IDeleteRangeMoveUpCommandParams } from '../commands/commands/delete-range-move-up.command';
import { DeleteRangeMoveUpCommand } from '../commands/commands/delete-range-move-up.command';
import type { InsertRangeMoveDownCommandParams } from '../commands/commands/insert-range-move-down.command';
import { InsertRangeMoveDownCommand } from '../commands/commands/insert-range-move-down.command';
@@ -155,11 +155,11 @@ export class MergeCellController extends Disposable {
return this._handleInsertRangeMoveDownCommand(params, workbookId, worksheetId);
}
case DeleteRangeMoveUpCommand.id: {
- const params = config.params as unknown as DeleteRangeMoveUpCommandParams;
+ const params = config.params as unknown as IDeleteRangeMoveUpCommandParams;
return this._handleDeleteRangeMoveUpCommand(params, workbookId, worksheetId);
}
case DeleteRangeMoveLeftCommand.id: {
- const params = config.params as unknown as DeleteRangeMoveLeftCommandParams;
+ const params = config.params as unknown as IDeleteRangeMoveLeftCommandParams;
return this._handleDeleteRangeMoveLeftCommand(params, workbookId, worksheetId);
}
}
@@ -695,7 +695,7 @@ export class MergeCellController extends Disposable {
}
private _handleDeleteRangeMoveUpCommand(
- config: DeleteRangeMoveUpCommandParams,
+ config: IDeleteRangeMoveUpCommandParams,
workbookId: string,
worksheetId: string
) {
@@ -770,7 +770,7 @@ export class MergeCellController extends Disposable {
}
private _handleDeleteRangeMoveLeftCommand(
- config: DeleteRangeMoveLeftCommandParams,
+ config: IDeleteRangeMoveLeftCommandParams,
workbookId: string,
worksheetId: string
) {
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index fb2e429ec9..5ece6992d7 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -54,10 +54,13 @@ export { ClearSelectionContentCommand } from './commands/commands/clear-selectio
export { ClearSelectionFormatCommand } from './commands/commands/clear-selection-format.command';
export { CopySheetCommand } from './commands/commands/copy-worksheet.command';
export { DeleteRangeMoveLeftCommand } from './commands/commands/delete-range-move-left.command';
-export { type DeleteRangeMoveLeftCommandParams } from './commands/commands/delete-range-move-left.command';
+export { type IDeleteRangeMoveLeftCommandParams } from './commands/commands/delete-range-move-left.command';
export { DeleteRangeMoveUpCommand } from './commands/commands/delete-range-move-up.command';
+export { type IDeleteRangeMoveUpCommandParams } from './commands/commands/delete-range-move-up.command';
export { InsertRangeMoveDownCommand } from './commands/commands/insert-range-move-down.command';
+export { type InsertRangeMoveDownCommandParams } from './commands/commands/insert-range-move-down.command';
export { InsertRangeMoveRightCommand } from './commands/commands/insert-range-move-right.command';
+export { type InsertRangeMoveRightCommandParams } from './commands/commands/insert-range-move-right.command';
export type { IInsertColCommandParams, IInsertRowCommandParams } from './commands/commands/insert-row-col.command';
export {
InsertColAfterCommand,
@@ -75,6 +78,7 @@ export {
MoveColsCommand,
MoveRowsCommand,
} from './commands/commands/move-rows-cols.command';
+export type { IRemoveRowColCommandParams } from './commands/commands/remove-row-col.command';
export { RemoveColCommand, RemoveRowCommand } from './commands/commands/remove-row-col.command';
export type { IRemoveSheetCommandParams } from './commands/commands/remove-sheet.command';
export { RemoveSheetCommand } from './commands/commands/remove-sheet.command';
@@ -152,7 +156,9 @@ export {
AddWorksheetMergeMutation,
} from './commands/mutations/add-worksheet-merge.mutation';
export { DeleteRangeMutation } from './commands/mutations/delete-range.mutation';
+export { handleDeleteRangeMutation } from './commands/mutations/delete-range.mutation';
export { InsertRangeMutation } from './commands/mutations/insert-range.mutation';
+export { handleInsertRangeMutation } from './commands/mutations/insert-range.mutation';
export {
InsertColMutation,
InsertColMutationUndoFactory,
@@ -161,7 +167,7 @@ export {
} from './commands/mutations/insert-row-col.mutation';
export { InsertSheetMutation, InsertSheetUndoMutationFactory } from './commands/mutations/insert-sheet.mutation';
export { MoveRangeMutation } from './commands/mutations/move-range.mutation';
-export { type MoveRangeMutationParams } from './commands/mutations/move-range.mutation';
+export { type IMoveRangeMutationParams } from './commands/mutations/move-range.mutation';
export { type IMoveColumnsMutationParams } from './commands/mutations/move-rows-cols.mutation';
export { type IMoveRowsMutationParams, MoveRowsMutation } from './commands/mutations/move-rows-cols.mutation';
export { MoveColsMutation } from './commands/mutations/move-rows-cols.mutation';
diff --git a/packages/sheets/src/services/ref-range/type.ts b/packages/sheets/src/services/ref-range/type.ts
index ad14d780aa..cfac8c5df1 100644
--- a/packages/sheets/src/services/ref-range/type.ts
+++ b/packages/sheets/src/services/ref-range/type.ts
@@ -1,8 +1,8 @@
import type { ICommandInfo, IRange } from '@univerjs/core';
-import type { DeleteRangeMoveLeftCommandParams } from '../../commands/commands/delete-range-move-left.command';
+import type { IDeleteRangeMoveLeftCommandParams } from '../../commands/commands/delete-range-move-left.command';
import { DeleteRangeMoveLeftCommandId } from '../../commands/commands/delete-range-move-left.command';
-import type { DeleteRangeMoveUpCommandParams } from '../../commands/commands/delete-range-move-up.command';
+import type { IDeleteRangeMoveUpCommandParams } from '../../commands/commands/delete-range-move-up.command';
import { DeleteRangeMoveUpCommandId } from '../../commands/commands/delete-range-move-up.command';
import type { InsertRangeMoveDownCommandParams } from '../../commands/commands/insert-range-move-down.command';
import { InsertRangeMoveDownCommandId } from '../../commands/commands/insert-range-move-down.command';
@@ -12,19 +12,19 @@ import type { IInsertColCommandParams, IInsertRowCommandParams } from '../../com
import { InsertColCommandId, InsertRowCommandId } from '../../commands/commands/insert-row-col.command';
import type { IMoveRangeCommandParams } from '../../commands/commands/move-range.command';
import { MoveRangeCommandId } from '../../commands/commands/move-range.command';
-import type { RemoveRowColCommandParams } from '../../commands/commands/remove-row-col.command';
+import type { IRemoveRowColCommandParams } from '../../commands/commands/remove-row-col.command';
import { RemoveColCommandId, RemoveRowCommandId } from '../../commands/commands/remove-row-col.command';
export type IMoveRangeCommand = ICommandInfo<IMoveRangeCommandParams> & { id: typeof MoveRangeCommandId };
export type IInsertRowCommand = ICommandInfo<IInsertRowCommandParams> & { id: typeof InsertRowCommandId };
export type IInsertColCommand = ICommandInfo<IInsertColCommandParams> & { id: typeof InsertColCommandId };
-export type IRemoveRowColCommand = ICommandInfo<RemoveRowColCommandParams> & {
+export type IRemoveRowColCommand = ICommandInfo<IRemoveRowColCommandParams> & {
id: typeof RemoveColCommandId | typeof RemoveRowCommandId;
};
-export type IDeleteRangeMoveLeftCommand = ICommandInfo<DeleteRangeMoveLeftCommandParams> & {
+export type IDeleteRangeMoveLeftCommand = ICommandInfo<IDeleteRangeMoveLeftCommandParams> & {
id: typeof DeleteRangeMoveLeftCommandId;
};
-export type IDeleteRangeMoveUpCommand = ICommandInfo<DeleteRangeMoveUpCommandParams> & {
+export type IDeleteRangeMoveUpCommand = ICommandInfo<IDeleteRangeMoveUpCommandParams> & {
id: typeof DeleteRangeMoveUpCommandId;
};
export type IInsertRangeMoveDownCommand = ICommandInfo<InsertRangeMoveDownCommandParams> & {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b569e1da29..c017a6cf9d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -610,6 +610,9 @@ importers:
'@wendellhu/redi':
specifier: ^0.12.11
version: 0.12.11
+ rxjs:
+ specifier: ^7.8.1
+ version: 7.8.1
devDependencies:
'@vitest/coverage-istanbul':
specifier: ^0.34.6
@@ -710,15 +713,30 @@ importers:
specifier: ^0.12.11
version: 0.12.11
devDependencies:
+ '@vitest/coverage-istanbul':
+ specifier: ^0.34.6
+ version: 0.34.6([email protected])
esbuild:
- specifier: ^0.19.5
+ specifier: ^0.19.8
version: 0.19.8
+ happy-dom:
+ specifier: ^12.10.3
+ version: 12.10.3
+ less:
+ specifier: ^4.2.0
+ version: 4.2.0
+ ts-node:
+ specifier: ^10.9.1
typedoc:
specifier: ^0.25.4
version: 0.25.4([email protected])
typescript:
specifier: ^5.3.2
version: 5.3.2
+ vitest:
+ specifier: ^0.34.6
packages/image:
dependencies:
@@ -916,6 +934,9 @@ importers:
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render
+ '@univerjs/formula':
+ specifier: workspace:*
+ version: link:../formula
'@univerjs/icons':
specifier: ^0.1.14
@@ -6791,12 +6812,6 @@ packages:
undici-types: 5.26.5
dev: true
- resolution: {integrity: sha512-D0WfRmU9TQ8I9PFx9Yc+EBHw+vSpIub4IDvQivcp26PtPrdMGAq5SDcpXEo/epqa/DXotVpekHiLNTg3iaKXBQ==}
- dependencies:
- undici-types: 5.26.5
- dev: true
-
resolution: {integrity: sha512-37MXfxkb0vuIlRKHNxwCkb60PNBpR94u4efQuN4JgIAm66zfCDXGSAFCef9XUWFovX2R1ok6Z7MHhtdVXXkkIw==}
dependencies:
@@ -17355,28 +17370,6 @@ packages:
unist-util-stringify-position: 4.0.0
vfile-message: 4.0.2
- resolution: {integrity: sha512-nlBMJ9x6n7/Amaz6F3zJ97EBwR2FkzhBRxF5e+jE6LA3yi6Wtc2lyTij1OnDMIr34v5g/tVQtsVAzhT0jc5ygA==}
- engines: {node: '>=v14.18.0'}
- hasBin: true
- dependencies:
- cac: 6.7.14
- debug: 4.3.4
- mlly: 1.4.2
- pathe: 1.1.1
- picocolors: 1.0.0
- vite: 5.0.2(@types/[email protected])
- transitivePeerDependencies:
- - '@types/node'
- - less
- - lightningcss
- - sass
- - stylus
- - sugarss
- - supports-color
- - terser
- dev: true
-
resolution: {integrity: sha512-nlBMJ9x6n7/Amaz6F3zJ97EBwR2FkzhBRxF5e+jE6LA3yi6Wtc2lyTij1OnDMIr34v5g/tVQtsVAzhT0jc5ygA==}
engines: {node: '>=v14.18.0'}
@@ -17435,42 +17428,6 @@ packages:
fsevents: 2.3.3
dev: true
- resolution: {integrity: sha512-6CCq1CAJCNM1ya2ZZA7+jS2KgnhbzvxakmlIjN24cF/PXhRMzpM/z8QgsVJA/Dm5fWUWnVEsmtBoMhmerPxT0g==}
- engines: {node: ^18.0.0 || >=20.0.0}
- hasBin: true
- peerDependencies:
- '@types/node': ^18.0.0 || >=20.0.0
- less: '*'
- lightningcss: ^1.21.0
- sass: '*'
- stylus: '*'
- sugarss: '*'
- terser: ^5.4.0
- peerDependenciesMeta:
- '@types/node':
- optional: true
- less:
- optional: true
- lightningcss:
- optional: true
- sass:
- optional: true
- stylus:
- optional: true
- sugarss:
- optional: true
- terser:
- optional: true
- dependencies:
- '@types/node': 20.10.0
- esbuild: 0.19.8
- postcss: 8.4.31
- rollup: 4.5.2
- optionalDependencies:
- fsevents: 2.3.3
- dev: true
-
resolution: {integrity: sha512-6CCq1CAJCNM1ya2ZZA7+jS2KgnhbzvxakmlIjN24cF/PXhRMzpM/z8QgsVJA/Dm5fWUWnVEsmtBoMhmerPxT0g==}
engines: {node: ^18.0.0 || >=20.0.0}
@@ -17541,7 +17498,7 @@ packages:
dependencies:
'@types/chai': 4.3.11
'@types/chai-subset': 1.3.5
- '@types/node': 20.10.0
+ '@types/node': 20.10.2
'@vitest/expect': 0.34.6
'@vitest/runner': 0.34.6
'@vitest/snapshot': 0.34.6
@@ -17560,8 +17517,8 @@ packages:
strip-literal: 1.3.0
tinybench: 2.5.1
tinypool: 0.7.0
- vite: 5.0.2(@types/[email protected])
- vite-node: 0.34.6(@types/[email protected])
+ vite: 5.0.2(@types/[email protected])([email protected])
+ vite-node: 0.34.6(@types/[email protected])([email protected])
why-is-node-running: 2.2.2
transitivePeerDependencies:
- less