Skip to content

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

feat(sheets): add workbook iterative calculation settings (#7855)

wpxp123456a57430fe76e1
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index de4fb6e6b3..7e062505a8 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -177,6 +177,8 @@ export {
export { awaitTime, delayAnimationFrame } from './shared/timer';
export { isNodeEnv } from './shared/tools';
export * from './sheets';
+export type { IWorkbookCalculationSettings } from './sheets/calculation-settings';
+export { MAX_ITERATION_COUNT, normalizeWorkbookCalculationSettings } from './sheets/calculation-settings';
export { Skeleton } from './skeleton';
export * from './types/const';
export { skipParseTagNames } from './types/const/clipboard';
diff --git a/packages/core/src/sheets/calculation-settings.ts b/packages/core/src/sheets/calculation-settings.ts
new file mode 100644
index 0000000000..1905510275
--- /dev/null
+++ b/packages/core/src/sheets/calculation-settings.ts
@@ -0,0 +1,61 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export interface IWorkbookCalculationSettings {
+ /**
+ * Whether circular references are evaluated iteratively. Defaults to false.
+ * When disabled, circular formulas retain their cached values, or use zero if no value is cached.
+ */
+ iterativeCalculation: boolean;
+ /**
+ * Maximum number of iterations for this workbook's formulas in a circular dependency group.
+ * Only used when iterative calculation is enabled.
+ * Must be an integer from 1 to 32767. Defaults to 100.
+ */
+ maxIterations: number;
+ /**
+ * Convergence threshold for the absolute change in numeric results between successive iterations.
+ * Iteration stops when every enabled cell in the group changes by at most this value.
+ * Must be a finite positive number. Defaults to 0.001; only used when iterative calculation is enabled.
+ */
+ maxChange: number;
+}
+
+export const MAX_ITERATION_COUNT = 32767;
+
+export const DEFAULT_WORKBOOK_CALCULATION_SETTINGS: Readonly<IWorkbookCalculationSettings> = Object.freeze({
+ iterativeCalculation: false,
+ maxIterations: 100,
+ maxChange: 0.001,
+});
+
+export function normalizeWorkbookCalculationSettings(
+ value?: Partial<IWorkbookCalculationSettings>
+): IWorkbookCalculationSettings {
+ const defaults = DEFAULT_WORKBOOK_CALCULATION_SETTINGS;
+ return {
+ iterativeCalculation: typeof value?.iterativeCalculation === 'boolean'
+ ? value.iterativeCalculation
+ : defaults.iterativeCalculation,
+ maxIterations: Number.isInteger(value?.maxIterations) && value!.maxIterations! >= 1 &&
+ value!.maxIterations! <= MAX_ITERATION_COUNT
+ ? value!.maxIterations!
+ : defaults.maxIterations,
+ maxChange: typeof value?.maxChange === 'number' && Number.isFinite(value.maxChange) && value.maxChange > 0
+ ? value.maxChange
+ : defaults.maxChange,
+ };
+}
diff --git a/packages/core/src/sheets/typedef.ts b/packages/core/src/sheets/typedef.ts
index cd88349fac..82fa7eed13 100644
--- a/packages/core/src/sheets/typedef.ts
+++ b/packages/core/src/sheets/typedef.ts
@@ -23,6 +23,7 @@ import type { LocaleType } from '../types/enum/locale-type';
import type { IDocumentData } from '../types/interfaces';
import type { ICellCustomRender } from '../types/interfaces/i-cell-custom-render';
import type { IStyleData } from '../types/interfaces/i-style-data';
+import type { IWorkbookCalculationSettings } from './calculation-settings';
import { CellValueType } from '../types/enum';
/**
@@ -58,6 +59,12 @@ export interface IWorkbookData {
/** Date serial system used by this workbook. Missing values mean Excel 1900. */
dateSystem?: DateSystem;
+ /**
+ * Calculation settings shared by all worksheets in this workbook and persisted in its snapshot.
+ * Optional for compatibility with older snapshots; omitted settings use the defaults with iterative calculation disabled.
+ */
+ calculationSettings?: IWorkbookCalculationSettings;
+
/**
* Style references.
*/
@@ -598,9 +605,6 @@ export type IColumnStartEndData = [startColumn: number, endColumn: number] | num
* row:[0,1],
* column:[0,1]
* }
- *todo
-
- true false 枚举
* means "A1:B2"
*/
export interface IRangeArrayData {
diff --git a/packages/core/src/sheets/workbook.ts b/packages/core/src/sheets/workbook.ts
index 47aab3d650..e36c648138 100644
--- a/packages/core/src/sheets/workbook.ts
+++ b/packages/core/src/sheets/workbook.ts
@@ -17,6 +17,7 @@
import type { Observable } from 'rxjs';
import type { Nullable } from '../shared';
import type { IStyleData } from '../types/interfaces';
+import type { IWorkbookCalculationSettings } from './calculation-settings';
import type { CustomData, IRangeType, IWorkbookData, IWorksheetData } from './typedef';
import { BehaviorSubject, Subject } from 'rxjs';
import { UnitModel, UniverInstanceType } from '../common/unit';
@@ -25,6 +26,7 @@ import { Tools } from '../shared';
import { generateRandomId } from '../shared/random-id';
import { BooleanNumber } from '../types/enum';
import { DateSystem } from '../types/enum/date-system';
+import { normalizeWorkbookCalculationSettings } from './calculation-settings';
import { getEmptySnapshot } from './empty-snapshot';
import { Styles } from './styles';
import { WorksheetHiddenState } from './typedef';
@@ -103,6 +105,8 @@ export class Workbook extends UnitModel<IWorkbookData, UniverInstanceType.UNIVER
}
}
+ this._snapshot.calculationSettings = normalizeWorkbookCalculationSettings(workbookData.calculationSettings);
+
const { styles } = this._snapshot;
if (this._snapshot.id == null || this._snapshot.id.length === 0) {
this._snapshot.id = generateRandomId(6);
@@ -152,6 +156,14 @@ export class Workbook extends UnitModel<IWorkbookData, UniverInstanceType.UNIVER
return this._snapshot;
}
+ getCalculationSettings(): IWorkbookCalculationSettings {
+ return normalizeWorkbookCalculationSettings(this._snapshot.calculationSettings);
+ }
+
+ setCalculationSettings(settings: IWorkbookCalculationSettings): void {
+ this._snapshot.calculationSettings = { ...settings };
+ }
+
setName(name: string): void {
this._name$.next(name);
this._snapshot.name = name;
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index 7cbfa5d98a..82e09d2c16 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -22,6 +22,7 @@ import type {
IRange,
IRowData,
IUnitRange,
+ IWorkbookCalculationSettings,
Nullable,
ObjectMatrix,
Styles,
@@ -267,7 +268,7 @@ export interface IFormulaDatasetConfig {
unitSheetNameMap?: IUnitSheetNameMap;
unitNameMap?: IFormulaUnitNameMap;
externalReferences?: IFormulaExternalReferences;
- maxIteration?: number;
+ calculationSettings?: Record<string, IWorkbookCalculationSettings>;
isCalculateTreeModel?: boolean;
rowData?: IUnitRowData; // Include rows hidden by filters
}
diff --git a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
index f35bc2fc1b..f989d9560a 100644
--- a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
@@ -28,7 +28,7 @@ import type {
IFormulaDependentsAndInRangeResults,
} from '../../engine/dependency/dependency-tree';
import type { IFormulaDirtyData } from '../../services/current-data.service';
-import type { FormulaExecutedStateType, IExecutionInProgressParams } from '../../services/runtime.service';
+import type { FormulaExecutedStateType, ICircularReference, IExecutionInProgressParams } from '../../services/runtime.service';
import { CommandType } from '@univerjs/core';
export interface ISetFormulaCalculationStartMutation extends IFormulaDirtyData {
@@ -117,6 +117,7 @@ export const SetFormulaCalculationStopMutation: IMutation<ISetFormulaCalculation
// TODO: this name lacks Params
export interface ISetFormulaCalculationNotificationMutation {
+ circularReferences?: ICircularReference[];
functionsExecutedState?: FormulaExecutedStateType;
stageInfo?: IExecutionInProgressParams;
}
diff --git a/packages/engine-formula/src/config/config.ts b/packages/engine-formula/src/config/config.ts
index bc391f8099..e4846d76f1 100644
--- a/packages/engine-formula/src/config/config.ts
+++ b/packages/engine-formula/src/config/config.ts
@@ -20,10 +20,6 @@ import type { BaseFunction } from '../functions/base-function';
export const ENGINE_FORMULA_PLUGIN_CONFIG_KEY = 'engine-formula.config';
-export const DEFAULT_CYCLE_REFERENCE_COUNT = 1;
-
-export const ENGINE_FORMULA_CYCLE_REFERENCE_COUNT = 'CYCLE_REFERENCE_COUNT';
-
export const ENGINE_FORMULA_RETURN_DEPENDENCY_TREE = 'RETURN_DEPENDENCY_TREE';
export const configSymbol = Symbol(ENGINE_FORMULA_PLUGIN_CONFIG_KEY);
diff --git a/packages/engine-formula/src/controllers/calculate.controller.ts b/packages/engine-formula/src/controllers/calculate.controller.ts
index 2bc8955695..b550cb8c4d 100644
--- a/packages/engine-formula/src/controllers/calculate.controller.ts
+++ b/packages/engine-formula/src/controllers/calculate.controller.ts
@@ -49,7 +49,6 @@ import {
SetQueryFormulaDependencyResultMutation,
} from '../commands/mutations/set-formula-calculation.mutation';
import { SetImageFormulaDataMutation } from '../commands/mutations/set-image-formula-data.mutation';
-import { DEFAULT_CYCLE_REFERENCE_COUNT } from '../config/config';
import { FormulaDataModel } from '../models/formula-data.model';
import { ICalculateFormulaService } from '../services/calculate-formula.service';
import { FormulaExecutedStateType } from '../services/runtime.service';
@@ -114,7 +113,7 @@ export class CalculateController extends Disposable {
dirtyUnitFeatureMap = {},
dirtyUnitOtherFormulaMap = {},
clearDependencyTreeCache = {},
- maxIteration = DEFAULT_CYCLE_REFERENCE_COUNT,
+ calculationSettings,
rowData,
externalReferences,
isCalculateTreeModel = false,
@@ -137,7 +136,7 @@ export class CalculateController extends Disposable {
dirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap,
clearDependencyTreeCache,
- maxIteration,
+ calculationSettings,
isCalculateTreeModel,
rowData,
externalReferences,
@@ -248,6 +247,7 @@ export class CalculateController extends Disposable {
SetFormulaCalculationNotificationMutation.id,
{
functionsExecutedState,
+ circularReferences: data.circularReferences,
},
{
onlyLocal: true,
diff --git a/packages/engine-formula/src/engine/dependency/dependency-groups.ts b/packages/engine-formula/src/engine/dependency/dependency-groups.ts
new file mode 100644
index 0000000000..02c6fa5ba5
--- /dev/null
+++ b/packages/engine-formula/src/engine/dependency/dependency-groups.ts
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Returns strongly connected components in dependency order: precedents before their dependents.
+ * Mutually dependent nodes stay together so only their group needs iterative calculation.
+ * Uses iterative Kosaraju traversal to avoid overflowing the call stack on large dependency graphs.
+ */
+export function getDependencyGroups<T>(nodes: T[], getId: (node: T) => number, getDependents: (node: T) => Iterable<number>): T[][] {
+ const byId = new Map(nodes.map((node) => [getId(node), node]));
+ const edges = new Map<number, number[]>();
+ const reverse = new Map<number, number[]>();
+ for (const node of nodes) {
+ const id = getId(node);
+ const dependents = Array.from(getDependents(node)).filter((dependent) => byId.has(dependent));
+ edges.set(id, dependents);
+ for (const dependent of dependents) {
+ const incoming = reverse.get(dependent) ?? [];
+ incoming.push(id);
+ reverse.set(dependent, incoming);
+ }
+ }
+ const visited = new Set<number>();
+ const order: number[] = [];
+ for (const id of byId.keys()) {
+ if (visited.has(id)) {
+ continue;
+ }
+ visited.add(id);
+ const stack = [{ id, next: 0 }];
+ while (stack.length) {
+ const frame = stack[stack.length - 1];
+ const children = edges.get(frame.id)!;
+ if (frame.next === children.length) {
+ order.push(frame.id);
+ stack.pop();
+ continue;
+ }
+ const child = children[frame.next++];
+ if (!visited.has(child)) {
+ visited.add(child);
+ stack.push({ id: child, next: 0 });
+ }
+ }
+ }
+ visited.clear();
+ const groups: T[][] = [];
+ for (let i = order.length - 1; i >= 0; i--) {
+ const id = order[i];
+ if (visited.has(id)) {
+ continue;
+ }
+ const group: T[] = [];
+ const stack = [id];
+ visited.add(id);
+ while (stack.length) {
+ const current = stack.pop()!;
+ group.push(byId.get(current)!);
+ for (const parent of reverse.get(current) ?? []) {
+ if (!visited.has(parent)) {
+ visited.add(parent);
+ stack.push(parent);
+ }
+ }
+ }
+ groups.push(group);
+ }
+ return groups;
+}
diff --git a/packages/engine-formula/src/engine/dependency/dependency-tree.ts b/packages/engine-formula/src/engine/dependency/dependency-tree.ts
index 483579e695..0dfb92393e 100644
--- a/packages/engine-formula/src/engine/dependency/dependency-tree.ts
+++ b/packages/engine-formula/src/engine/dependency/dependency-tree.ts
@@ -69,6 +69,8 @@ class FormulaDependencyTreeCalculator {
return this._state === FDtreeStateType.SKIP;
}
+ cycleGroup?: string;
+
treeId: number;
children: Set<number> = new Set();
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index c362abcc2e..3fad4633cb 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -55,6 +55,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { prefixToken, suffixToken } from '../../basics/token';
+import { FUNCTION_NAMES_LOOKUP } from '../../functions/lookup/function-names';
import { IFormulaCurrentConfigService } from '../../services/current-data.service';
import { IDependencyManagerService } from '../../services/dependency-manager.service';
import {
@@ -69,6 +70,7 @@ import { NodeType } from '../ast-node/node-type';
import { Interpreter } from '../interpreter/interpreter';
import { BaseReferenceObject } from '../reference-object/base-reference-object';
import { FORMULA_AST_CACHE, generateAstNode, includeDefinedName } from '../utils/generate-ast-node';
+import { getDependencyGroups } from './dependency-groups';
import {
FormulaDependencyTree,
FormulaDependencyTreeModel,
@@ -177,7 +179,34 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
const updateTreeList = this._getUpdateTreeListAndMakeDependency();
- const finalTreeList = this._calculateRunList(updateTreeList);
+ const runList = this._calculateRunList(updateTreeList);
+ const selfReferences = new Set<number>();
+ const groups = getDependencyGroups(runList, (tree) => tree.treeId, (tree) => {
+ const dependents = this._dependencyManagerService.searchDependency(tree.toRTreeItem());
+ const addressDependents = this._dependencyRTreeCacheForAddressFunction.bulkSearch(tree.toRTreeItem()) as Set<number>;
+ for (const dependent of addressDependents) {
+ dependents.add(dependent);
+ }
+ if (dependents.has(tree.treeId)) {
+ selfReferences.add(tree.treeId);
+ }
+ return dependents;
+ });
+ this._runtimeService.clearCircularReferenceCells(runList);
+ for (const group of groups) {
+ const cyclic = group.length > 1 || selfReferences.has(group[0].treeId);
+ const groupId = cyclic ? group.map((tree) => tree.treeId).sort((a, b) => a - b).join(',') : undefined;
+ for (const tree of group) {
+ tree.cycleGroup = groupId;
+ if (cyclic) {
+ // Address discovery can evaluate cells provisionally. Cycles must start
+ // from the workbook cache, without spending iterations during discovery.
+ this._runtimeService.getUnitData()[tree.unitId]?.[tree.subUnitId]
+ ?.realDeleteValue(tree.row, tree.column);
+ }
+ }
+ }
+ const finalTreeList = groups.flat().reverse();
const isCycleDependency = this._checkIsCycleDependency(finalTreeList);
@@ -202,57 +231,8 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
return Promise.resolve(finalTreeList);
}
- private _isCyclicUtilMap(treeId: number, colorMap: Map<number, number>): boolean {
- const WHITE = 0;
- const GRAY = 1;
- const BLACK = 2;
- const stack: number[] = [treeId];
-
- while (stack.length > 0) {
- const currentTreeId = stack[stack.length - 1];
- const color = colorMap.get(currentTreeId) || WHITE;
-
- if (color === WHITE) {
- colorMap.set(currentTreeId, GRAY);
- const node = this._dependencyTreeCache.get(currentTreeId);
- if (node == null) {
- colorMap.set(currentTreeId, BLACK);
- stack.pop();
- continue;
- }
-
- const parents = this._dependencyManagerService.searchDependency(node.toRTreeItem());
- for (const parentTreeId of parents) {
- const parentColor = colorMap.get(parentTreeId) || WHITE;
- if (parentColor === GRAY) {
- return true; // 发现环
- } else if (parentColor === WHITE) {
- stack.push(parentTreeId);
- }
- }
- } else {
- colorMap.set(currentTreeId, BLACK);
- stack.pop();
- }
- }
-
- return false;
- }
-
protected _checkIsCycleDependency(treeList: IFormulaDependencyTree[]): boolean {
- const colorMap = new Map<number, number>();
-
- for (const tree of treeList) {
- if (!colorMap.has(tree.treeId)) {
- if (this._isCyclicUtilMap(tree.treeId, colorMap)) {
- return true;
- }
- }
- }
-
- colorMap.clear();
-
- return false;
+ return treeList.some((tree) => tree.cycleGroup != null);
}
protected _getFeatureFormulaTree(featureId: string, treeId: Nullable<number>, params: IFeatureCalculationManagerParam) {
@@ -910,11 +890,27 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
return false;
}
+ private _isStaticReference(node: BaseAstNode): boolean {
+ return node.nodeType === NodeType.REFERENCE || (
+ node.nodeType === NodeType.UNION && node.getChildren().every((child) => this._isStaticReference(child))
+ );
+ }
+
private _nodeTraversalRef(node: BaseAstNode, result: PreCalculateNodeType[]) {
const children = node.getChildren();
const childrenCount = children.length;
+ const token = node.getToken();
+ const readsReferenceMetadata = node.nodeType === NodeType.FUNCTION && (
+ token === FUNCTION_NAMES_LOOKUP.ROW || token === FUNCTION_NAMES_LOOKUP.ROWS ||
+ token === FUNCTION_NAMES_LOOKUP.COLUMN || token === FUNCTION_NAMES_LOOKUP.COLUMNS
+ );
for (let i = 0; i < childrenCount; i++) {
const item = children[i];
+ // Static references only supply coordinates or dimensions to these functions.
+ // Expressions and dynamic references can still read cell values while evaluating their arguments.
+ if (readsReferenceMetadata && this._isStaticReference(item)) {
+ continue;
+ }
if (this._isPreCalculateNode(item)) {
result.push(item as PreCalculateNodeType);
if (item.nodeType === NodeType.UNION) {
diff --git a/packages/engine-formula/src/facade/__tests__/f-formula.spec.ts b/packages/engine-formula/src/facade/__tests__/f-formula.spec.ts
index aa78173734..eb07a4989e 100644
--- a/packages/engine-formula/src/facade/__tests__/f-formula.spec.ts
+++ b/packages/engine-formula/src/facade/__tests__/f-formula.spec.ts
@@ -32,7 +32,7 @@ import {
SetQueryFormulaDependencyResultMutation,
SetTriggerFormulaCalculationStartMutation,
} from '../../commands/mutations/set-formula-calculation.mutation';
-import { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_RETURN_DEPENDENCY_TREE } from '../../config/config';
+import { ENGINE_FORMULA_RETURN_DEPENDENCY_TREE } from '../../config/config';
import { FFormula } from '../f-formula';
interface ICommandServiceMock {
@@ -158,10 +158,8 @@ describe('FFormula', () => {
it('should set formula configs', () => {
const { formula, configService } = createFFormula();
- formula.setMaxIteration(12);
formula.setFormulaReturnDependencyTree(true);
- expect(configService.setConfig).toHaveBeenCalledWith(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, 12);
expect(configService.setConfig).toHaveBeenCalledWith(ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, true);
});
diff --git a/packages/engine-formula/src/facade/f-formula.ts b/packages/engine-formula/src/facade/f-formula.ts
index eede063305..aba74cbd0c 100644
--- a/packages/engine-formula/src/facade/f-formula.ts
+++ b/packages/engine-formula/src/facade/f-formula.ts
@@ -36,7 +36,6 @@ import type {
import { ICommandService, IConfigService, Inject, Injector } from '@univerjs/core';
import { FBase } from '@univerjs/core/facade';
import {
- ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,
ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,
FormulaCalculationSessionService,
IDefinedNamesService,
@@ -262,22 +261,6 @@ export class FFormula extends FBase {
});
}
- /**
- * When a formula contains a circular reference, set the maximum number of iterations for the formula calculation.
- * @param {number} maxIteration The maximum number of iterations. The default value is 1.
- *
- * @example
- * ```ts
- * // Set the maximum number of iterations for the formula calculation to 5.
- * // The default value is 1.
- * const formulaEngine = univerAPI.getFormula();
- * formulaEngine.setMaxIteration(5);
- * ```
- */
- setMaxIteration(maxIteration: number): void {
- this._configService.setConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, maxIteration);
- }
-
/**
* Execute a batch of formulas asynchronously and receive computed results.
*
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 72721e5091..494011e67f 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -134,8 +134,6 @@ export type {
ISetSuperTableMutationSearchParam,
} from './commands/mutations/set-super-table.mutation';
export {
- DEFAULT_CYCLE_REFERENCE_COUNT,
- ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,
ENGINE_FORMULA_PLUGIN_CONFIG_KEY,
ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,
} from './config/config';
@@ -360,6 +358,7 @@ export {
IFormulaRuntimeService,
} from './services/runtime.service';
export type { IAllRuntimeData, IExecutionInProgressParams } from './services/runtime.service';
+export type { ICircularReference } from './services/runtime.service';
export { ISheetRowFilteredService, SheetRowFilteredService } from './services/sheet-row-filtered.service';
export { ISuperTableService } from './services/super-table.service';
export { SuperTableService } from './services/super-table.service';
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index f6b2046868..03f69289e2 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -32,6 +32,7 @@ import type {
IUnitStylesData,
} from '../basics/common';
import type { IImageFormulaInfo } from '../engine/value-object/primitive-object';
+import type { ICircularReference } from '../services/runtime.service';
import { BooleanNumber, CellValueType, createBaseFormulaTableNameMap, Disposable, getBaseFormulaTableName, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, Styles, UniverInstanceType } from '@univerjs/core';
import { copyUnitData } from '../basics/runtime';
import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';
@@ -44,6 +45,8 @@ export interface IRangeChange {
}
export class FormulaDataModel extends Disposable {
+ private _circularReferences = new Map<string, ICircularReference>();
+
private _formulaIdMapData: IFormulaIdMapData = Object.create(null);
private _arrayFormulaRange: IArrayFormulaRangeType = Object.create(null);
@@ -57,16 +60,44 @@ export class FormulaDataModel extends Disposable {
@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder
) {
super();
+
+ this.disposeWithMe(
+ this._univerInstanceService.getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {
+ for (const [key, cell] of this._circularReferences) {
+ if (cell.unitId === workbook.getUnitId()) {
+ this._circularReferences.delete(key);
+ }
+ }
+ })
+ );
}
override dispose() {
super.dispose();
+ this._circularReferences.clear();
this._formulaIdMapData = Object.create(null);
this._arrayFormulaRange = Object.create(null);
this._arrayFormulaCellData = Object.create(null);
this._unitImageFormulaData = Object.create(null);
}
+ setCircularReferences(cells: ICircularReference[]): void {
+ this._circularReferences.clear();
+ for (const cell of cells) {
+ this._circularReferences.set(JSON.stringify([cell.unitId, cell.sheetId, cell.row, cell.column]), { ...cell });
+ }
+ }
+
+ getCircularReferences(unitId: string): ICircularReference[] {
+ return Array.from(this._circularReferences.values())
+ .filter((cell) => cell.unitId === unitId)
+ .map((cell) => ({ ...cell }));
+ }
+
+ isCircularReference(unitId: string, sheetId: string, row: number, column: number): boolean {
+ return this._circularReferences.has(JSON.stringify([unitId, sheetId, row, column]));
+ }
+
clearPreviousArrayFormulaCellData(clearArrayFormulaCellData: IRuntimeUnitDataType) {
Object.keys(clearArrayFormulaCellData).forEach((unitId) => {
const clearSheetData = clearArrayFormulaCellData[unitId];
diff --git a/packages/engine-formula/src/services/__tests__/calculate-formula.service.calculation-settings.spec.ts b/packages/engine-formula/src/services/__tests__/calculate-formula.service.calculation-settings.spec.ts
new file mode 100644
index 0000000000..4a27624477
--- /dev/null
+++ b/packages/engine-formula/src/services/__tests__/calculate-formula.service.calculation-settings.spec.ts
@@ -0,0 +1,454 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Ctor } from '@univerjs/core';
+import type { IFormulaDatasetConfig } from '../../basics/common';
+import type { IFunctionNames } from '../../basics/function';
+import type { BaseFunction } from '../../functions/base-function';
+import type { IAllRuntimeData } from '../runtime.service';
+import { CellValueType, ObjectMatrix } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { ErrorType } from '../../basics/error-type';
+import { createFunctionTestBed } from '../../functions/__tests__/create-function-test-bed';
+import { ALL_IMPLEMENTED_FUNCTIONS } from '../../functions/index';
+
+import { ICalculateFormulaService } from '../calculate-formula.service';
+import { DependencyManagerService, IDependencyManagerService } from '../dependency-manager.service';
+import { FeatureCalculationManagerService, IFeatureCalculationManagerService } from '../feature-calculation-manager.service';
+import { IFunctionService } from '../function.service';
+import { IFormulaRuntimeService } from '../runtime.service';
+
+function createBed() {
+ const bed = createFunctionTestBed(undefined, [
+ [IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }],
+ [IDependencyManagerService, { useClass: DependencyManagerService }],
+ ]);
+ bed.get(IFunctionService).registerExecutors(...ALL_IMPLEMENTED_FUNCTIONS.map(([Fn, name]) =>
+ new (Fn as Ctor<BaseFunction>)(name as IFunctionNames)));
+ return bed;
+}
+
+describe('Persisted calculation settings', () => {
+ async function calculate(
+ bed: ReturnType<typeof createFunctionTestBed>,
+ formulas: Record<number, Record<number, { f: string }>>,
+ enabled: boolean,
+ count = 100,
+ maxChange = 0.001,
+ extra: Partial<IFormulaDatasetConfig> = {}
+ ): Promise<IAllRuntimeData> {
+ const config: IFormulaDatasetConfig = {
+ formulaData: { [bed.unitId]: { [bed.sheetId]: formulas } },
+ allUnitData: { [bed.unitId]: bed.sheetData },
+ unitStylesData: {},
+ unitSheetNameMap: { [bed.unitId]: { Sheet1: bed.sheetId } },
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: true,
+ clearDependencyTreeCache: { [bed.unitId]: { [bed.sheetId]: 'Sheet1' } },
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ calculationSettings: { [bed.unitId]: { iterativeCalculation: enabled, maxIterations: count, maxChange } },
+ ...extra,
+ };
+ const service = bed.get(ICalculateFormulaService);
+ let result: IAllRuntimeData | undefined;
+ const subscription = service.executionCompleteListener$.subscribe((data) => {
+ result = data;
+ });
+ try {
+ await service.execute(config);
+ return result!;
+ } finally {
+ subscription.unsubscribe();
+ }
+ }
+
+ it.each([
+ { label: 'range-comparison', formula: '=SUM(--(A1:A2<2))+1', cached: 0, a2: { v: 10 }, enabled: true, count: 3, expected: 2, expectedIterations: 3, expectedConverged: false },
+ { label: 'sumif', formula: '=SUMIF(A1:A2,"<2",A1:A2)+1', cached: 0, a2: { v: 10 }, enabled: true, count: 3, expected: 1, expectedIterations: 3, expectedConverged: false },
+ { label: 'dynamic-enabled', formula: '=INDIRECT(A2)+1', cached: 7, a2: { f: '="A1"', v: 'B1', t: CellValueType.STRING }, enabled: true, count: 1, expected: 8, expectedIterations: 1, expectedConverged: false },
+ { label: 'dynamic-disabled', formula: '=INDIRECT(A2)+1', cached: 7, a2: { f: '="A1"', v: 'B1', t: CellValueType.STRING }, enabled: false, count: 1, expected: 7, expectedIterations: 0, expectedConverged: undefined },
+ { label: 'range-numeric', formula: '=SUM(A1:A2)+1', cached: 0, a2: { v: 0 }, enabled: true, count: 3, expected: 3, expectedIterations: 3, expectedConverged: false },
+ ])('$label', async ({ formula, cached, a2, enabled, count, expected, expectedIterations, expectedConverged }) => {
+ const bed = createBed();
+ try {
+ const cells = bed.sheetData[bed.sheetId]!.cellData;
+ cells.setValue(0, 0, { f: formula, v: cached, t: CellValueType.NUMBER });
+ cells.setValue(0, 1, { v: 100, t: CellValueType.NUMBER });
+ cells.setValue(1, 0, a2);
+ const formulas: Record<number, Record<number, { f: string }>> = { 0: { 0: { f: formula } } };
+ if ('f' in a2) {
+ formulas[1] = { 0: { f: a2.f! } };
+ }
+ const result = await calculate(bed, formulas, enabled, count);
+ const actual = result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v ?? cached;
+ expect(actual).toBe(expected);
+ expect(result.circularReferences?.[0]).toMatchObject({ iterations: expectedIterations, converged: expectedConverged });
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it.each([
+ { formula: '=ROW(A1)', expected: 1 },
+ { formula: '=COLUMN(A1)', expected: 1 },
+ { formula: '=ROWS(A1:A3)', expected: 3 },
+ { formula: '=COLUMNS(A1:C1)', expected: 3 },
+ ])('does not treat reference metadata in $formula as a circular value dependency', async ({ formula, expected }) => {
+ const bed = createBed();
+ try {
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: formula, v: 7, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: formula } } }, false);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(expected);
+ expect(result.circularReferences).toEqual([]);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it.each(['=ROWS(A1+1)', '=COLUMNS(A1+1)', '=ROWS(A1:A3)+A1'])(
+ 'retains circular value dependencies in %s',
+ async (formula) => {
+ const bed = createBed();
+ try {
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: formula, v: 7, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: formula } } }, false);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v ?? 7).toBe(7);
+ expect(result.circularReferences).toHaveLength(1);
+ } finally {
+ bed.univer.dispose();
+ }
+ }
+ );
+
+ it('updates value dependencies beside a metadata-only self-reference', async () => {
+ const bed = createBed();
+ try {
+ const cells = bed.sheetData[bed.sheetId]!.cellData;
+ const firstFormula = '=ROWS(A1:A3)+B1';
+ const secondFormula = '=C1+1';
+ const formulas = { 0: { 0: { f: firstFormula }, 1: { f: secondFormula } } };
+ cells.setValue(0, 0, { f: firstFormula, v: 7, t: CellValueType.NUMBER });
+ cells.setValue(0, 1, { f: secondFormula, v: 0, t: CellValueType.NUMBER });
+ cells.setValue(0, 2, { v: 2, t: CellValueType.NUMBER });
+ const first = await calculate(bed, formulas, false);
+ expect(first.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(6);
+ expect(first.circularReferences).toEqual([]);
+
+ cells.setValue(0, 0, { f: firstFormula, v: 6, t: CellValueType.NUMBER });
+ cells.setValue(0, 1, { f: secondFormula, v: 3, t: CellValueType.NUMBER });
+ cells.setValue(0, 2, { v: 3, t: CellValueType.NUMBER });
+ const second = await calculate(bed, formulas, false, 100, 0.001, {
+ forceCalculate: false,
+ clearDependencyTreeCache: {},
+ dirtyRanges: [{ unitId: bed.unitId, sheetId: bed.sheetId, range: { startRow: 0, endRow: 0, startColumn: 2, endColumn: 2 } }],
+ });
+ expect(second.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(7);
+ expect(second.circularReferences).toEqual([]);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('retains unrelated cycle diagnostics on incremental recalculation', async () => {
+ const bed = createBed();
+ try {
+ const cells = bed.sheetData[bed.sheetId]!.cellData;
+ cells.setValue(0, 0, { f: '=A1+1', v: 7, t: CellValueType.NUMBER });
+ cells.setValue(0, 3, { v: 10, t: CellValueType.NUMBER });
+ cells.setValue(1, 3, { f: '=D1+1', v: 0, t: CellValueType.NUMBER });
+ const formulas = { 0: { 0: { f: '=A1+1' } }, 1: { 3: { f: '=D1+1' } } };
+ const first = await calculate(bed, formulas, false);
+ expect(first.circularReferences).toHaveLength(1);
+ cells.setValue(1, 3, { f: '=D1+1', v: 11, t: CellValueType.NUMBER });
+ cells.setValue(0, 3, { v: 20, t: CellValueType.NUMBER });
+ const second = await calculate(bed, formulas, false, 100, 0.001, {
+ forceCalculate: false,
+ clearDependencyTreeCache: {},
+ dirtyRanges: [{ unitId: bed.unitId, sheetId: bed.sheetId, range: { startRow: 0, endRow: 0, startColumn: 3, endColumn: 3 } }],
+ });
+ expect(second.unitData[bed.unitId]?.[bed.sheetId]?.getValue(1, 3)?.v).toBe(21);
+ expect(second.circularReferences).toHaveLength(1);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('uses separate iteration budgets in a cross-workbook cycle', async () => {
+ const bed = createBed();
+ try {
+ const otherUnitId = 'other-workbook';
+ const firstFormula = '=[other-workbook]Sheet1!A1+1';
+ const secondFormula = `=[${bed.unitId}]Sheet1!A1+1`;
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: firstFormula, v: 0, t: CellValueType.NUMBER });
+ const otherCells = new ObjectMatrix({ 0: { 0: { f: secondFormula, v: 0, t: CellValueType.NUMBER } } });
+ const result = await calculate(bed, {}, true, 1, 0.001, {
+ formulaData: {
+ [bed.unitId]: { [bed.sheetId]: { 0: { 0: { f: firstFormula } } } },
+ [otherUnitId]: { [bed.sheetId]: { 0: { 0: { f: secondFormula } } } },
+ },
+ allUnitData: { [bed.unitId]: bed.sheetData, [otherUnitId]: { [bed.sheetId]: { ...bed.sheetData[bed.sheetId]!, cellData: otherCells } } },
+ unitSheetNameMap: { [bed.unitId]: { Sheet1: bed.sheetId }, [otherUnitId]: { Sheet1: bed.sheetId } },
+ calculationSettings: {
+ [bed.unitId]: { iterativeCalculation: true, maxIterations: 1, maxChange: 0.001 },
+ [otherUnitId]: { iterativeCalculation: true, maxIterations: 3, maxChange: 0.001 },
+ },
+ });
+ expect(result.circularReferences).toHaveLength(2);
+ expect(result.circularReferences?.find((cell) => cell.unitId === bed.unitId)?.iterations).toBe(1);
+ expect(result.circularReferences?.find((cell) => cell.unitId === otherUnitId)?.iterations).toBeGreaterThan(1);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it.each([false, true])('literal dynamic self-reference enabled=%s', async (enabled) => {
+ const bed = createBed();
+ try {
+ const formula = '=INDIRECT("A1")+1';
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: formula, v: 7, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: formula } } }, enabled, 1);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v ?? 7).toBe(enabled ? 8 : 7);
+ expect(result.circularReferences).toHaveLength(1);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('boolean results use equality despite a large numeric threshold', async () => {
+ const bed = createBed();
+ try {
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: '=NOT(A1)', v: 0, t: CellValueType.BOOLEAN });
+ const result = await calculate(bed, { 0: { 0: { f: '=NOT(A1)' } } }, true, 4, 2);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(0);
+ expect(result.circularReferences?.[0]).toMatchObject({ iterations: 4, converged: false });
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('refreshes a shared range between members of the same iteration', async () => {
+ const bed = createBed();
+ try {
+ const cells = bed.sheetData[bed.sheetId]!.cellData;
+ cells.setValue(0, 0, { f: '=SUM(A1:B1)+1', v: 0, t: CellValueType.NUMBER });
+ cells.setValue(0, 1, { f: '=SUM(A1:B1)+2', v: 0, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: '=SUM(A1:B1)+1' }, 1: { f: '=SUM(A1:B1)+2' } } }, true, 1);
+ const runtime = result.unitData[bed.unitId]?.[bed.sheetId];
+ const values = [runtime?.getValue(0, 0)?.v, runtime?.getValue(0, 1)?.v];
+ // Both traversal orders are valid; the second member must see the first result.
+ expect([[1, 3], [3, 2]]).toContainEqual(values);
+ expect(result.circularReferences).toHaveLength(2);
+ expect(result.circularReferences?.every((cell) => cell.iterations === 1)).toBe(true);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+ it('dynamic DAG reads recalculated precedents', async () => {
+ const bed = createBed();
+ try {
+ const cells = bed.sheetData[bed.sheetId]!.cellData;
+ cells.setValue(0, 0, { f: '=INDIRECT("B1")+1', v: 0, t: CellValueType.NUMBER });
+ cells.setValue(0, 1, { f: '=C1+1', v: 10, t: CellValueType.NUMBER });
+ cells.setValue(0, 2, { f: '=D1+1', v: 20, t: CellValueType.NUMBER });
+ cells.setValue(0, 3, { v: 1, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: '=INDIRECT("B1")+1' }, 1: { f: '=C1+1' }, 2: { f: '=D1+1' } } }, false);
+ const runtime = result.unitData[bed.unitId]?.[bed.sheetId];
+ expect([0, 1, 2].map((column) => runtime?.getValue(0, column)?.v)).toEqual([4, 3, 2]);
+ expect(result.circularReferences).toEqual([]);
+ for (const [column, value] of [[0, 4], [1, 3], [2, 2]]) {
+ cells.setValue(0, column, { ...cells.getValue(0, column), v: value });
+ }
+ cells.setValue(0, 3, { v: 2, t: CellValueType.NUMBER });
+ const updated = await calculate(bed, { 0: { 0: { f: '=INDIRECT("B1")+1' }, 1: { f: '=C1+1' }, 2: { f: '=D1+1' } } }, false, 100, 0.001, {
+ forceCalculate: false,
+ clearDependencyTreeCache: {},
+ dirtyRanges: [{ unitId: bed.unitId, sheetId: bed.sheetId, range: { startRow: 0, endRow: 0, startColumn: 3, endColumn: 3 } }],
+ });
+ const updatedRuntime = updated.unitData[bed.unitId]?.[bed.sheetId];
+ expect([0, 1, 2].map((column) => updatedRuntime?.getValue(0, column)?.v)).toEqual([5, 4, 3]);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+ it.each([false, true])('distinguishes disabled and one enabled self-reference iteration: %s', async (enabled) => {
+ const bed = createBed();
+ try {
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: '=A1+1', v: 7, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: '=A1+1' }, 1: { f: '=A1*2' } } }, enabled, 1);
+ const runtime = result.unitData[bed.unitId]?.[bed.sheetId];
+ expect(runtime?.getValue(0, 0)?.v ?? 7).toBe(enabled ? 8 : 7);
+ expect(runtime?.getValue(0, 1)?.v).toBe(enabled ? 16 : 14);
+ expect(result.circularReferences).toEqual([expect.objectContaining({
+ unitId: bed.unitId,
+ sheetId: bed.sheetId,
+ row: 0,
+ column: 0,
+ iterations: enabled ? 1 : 0,
+ })]);
+ expect(bed.get(IFormulaRuntimeService).getRuntimeState().circularReferences).toEqual(result.circularReferences);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('preserves both cells of a disabled mutual cycle and still calculates its dependent', async () => {
+ const bed = createBed();
+ try {
+ const cells = bed.sheetData[bed.sheetId]!.cellData;
+ cells.setValue(0, 0, { f: '=B1+1', v: 7, t: CellValueType.NUMBER });
+ cells.setValue(0, 1, { f: '=A1+1', v: 9, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: '=B1+1' }, 1: { f: '=A1+1' }, 2: { f: '=A1+B1' } } }, false);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 2)?.v).toBe(16);
+ expect(result.circularReferences).toHaveLength(2);
+ expect(result.circularReferences?.map((cell) => cell.groupId)).toEqual([
+ result.circularReferences?.[0].groupId,
+ result.circularReferences?.[0].groupId,
+ ]);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('stops a convergent group early and clears diagnostics after the cycle is removed', async () => {
+ const bed = createBed();
+ try {
+ const cells = bed.sheetData[bed.sheetId]!.cellData;
+ cells.setValue(0, 0, { f: '=(A1+1)/2', v: 0, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: '=(A1+1)/2' } } }, true);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBeCloseTo(1, 2);
+ expect(result.circularReferences?.[0].converged).toBe(true);
+ expect(result.circularReferences?.[0].iterations).toBeLessThan(100);
+ cells.setValue(0, 0, { f: '=1', v: 0, t: CellValueType.NUMBER });
+ const updated = await calculate(bed, { 0: { 0: { f: '=1' } } }, true);
+ expect(updated.circularReferences).toEqual([]);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('applies one workbook setting to a cycle across sheets', async () => {
+ const bed = createBed();
+ try {
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: '=Sheet2!A1+1', v: 7, t: CellValueType.NUMBER });
+ bed.sheetData.sheet2 = { ...bed.sheetData[bed.sheetId]!, cellData: new ObjectMatrix({ 0: { 0: { f: '=Sheet1!A1+1', v: 9, t: CellValueType.NUMBER } } }) };
+ const result = await calculate(bed, {}, false, 1, 0.001, {
+ formulaData: { [bed.unitId]: {
+ [bed.sheetId]: { 0: { 0: { f: '=Sheet2!A1+1' }, 1: { f: '=Sheet2!A1*2' } } },
+ sheet2: { 0: { 0: { f: '=Sheet1!A1+1' } } },
+ } },
+ unitSheetNameMap: { [bed.unitId]: { Sheet1: bed.sheetId, Sheet2: 'sheet2' } },
+ });
+ expect(result.circularReferences).toHaveLength(2);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 1)?.v).toBe(18);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('keeps settings independent for multiple workbooks in one task', async () => {
+ const bed = createBed();
+ try {
+ const otherUnitId = 'other-workbook';
+ const otherCells = new ObjectMatrix({ 0: { 0: { f: '=A1+1', v: 9, t: CellValueType.NUMBER } } });
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: '=A1+1', v: 7, t: CellValueType.NUMBER });
+ const result = await calculate(bed, {}, false, 1, 0.001, {
+ formulaData: {
+ [bed.unitId]: { [bed.sheetId]: { 0: { 0: { f: '=A1+1' }, 1: { f: '=A1*2' } } } },
+ [otherUnitId]: { [bed.sheetId]: { 0: { 0: { f: '=A1+1' }, 1: { f: '=A1*2' } } } },
+ },
+ allUnitData: { [bed.unitId]: bed.sheetData, [otherUnitId]: { [bed.sheetId]: { ...bed.sheetData[bed.sheetId]!, cellData: otherCells } } },
+ unitSheetNameMap: { [bed.unitId]: { Sheet1: bed.sheetId }, [otherUnitId]: { Sheet1: bed.sheetId } },
+ calculationSettings: {
+ [bed.unitId]: { iterativeCalculation: false, maxIterations: 100, maxChange: 0.001 },
+ [otherUnitId]: { iterativeCalculation: true, maxIterations: 1, maxChange: 0.001 },
+ },
+ });
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 1)?.v).toBe(14);
+ expect(result.unitData[otherUnitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(10);
+ expect(result.unitData[otherUnitId]?.[bed.sheetId]?.getValue(0, 1)?.v).toBe(20);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it.each([
+ { formula: '=NOT(A1)', cached: { v: 0, t: CellValueType.BOOLEAN }, expected: 1, iterations: 5, converged: false },
+ { formula: '=IF(A1="a","b","a")', cached: { v: 'a', t: CellValueType.STRING }, expected: 'b', iterations: 5, converged: false },
+ { formula: '=IF(A1=0,1/0,A1)', cached: { v: 0, t: CellValueType.NUMBER }, expected: ErrorType.DIV_BY_ZERO, iterations: 2, converged: true },
+ ])('preserves convergence when result types change: $formula', async ({ formula, cached, expected, iterations, converged }) => {
+ const bed = createBed();
+ try {
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: formula, ...cached });
+ const result = await calculate(bed, { 0: { 0: { f: formula } } }, true, 5);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(expected);
+ expect(result.circularReferences?.[0]).toMatchObject({ iterations, converged });
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('reloads settings for consecutive tasks on the same workbook', async () => {
+ const bed = createBed();
+ try {
+ for (const count of [1, 3]) {
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: '=A1+1', v: 7, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: '=A1+1' } } }, true, count);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(7 + count);
+ expect(result.circularReferences?.[0].iterations).toBe(count);
+ }
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: '=A1+1', v: 7, t: CellValueType.NUMBER });
+ const disabled = await calculate(bed, { 0: { 0: { f: '=A1+1' } } }, false);
+ expect(disabled.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v ?? 7).toBe(7);
+ expect(disabled.circularReferences?.[0].iterations).toBe(0);
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('uses an inclusive convergence threshold and reloads it between tasks', async () => {
+ const bed = createBed();
+ try {
+ for (const [maxChange, iterations] of [[0.125, 1], [0.0625, 5]]) {
+ bed.sheetData[bed.sheetId]!.cellData.setValue(0, 0, { f: '=A1+0.125', v: 0, t: CellValueType.NUMBER });
+ const result = await calculate(bed, { 0: { 0: { f: '=A1+0.125' } } }, true, 5, maxChange);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(iterations * 0.125);
+ expect(result.circularReferences?.[0]).toMatchObject({ iterations, converged: iterations === 1 });
+ }
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('writes zero for uncached disabled cycles and reports non-convergence at the limit', async () => {
+ const bed = createBed();
+ try {
+ const cells = bed.sheetData[bed.sheetId]!.cellData;
+ cells.setValue(0, 0, { f: '=A1+1' });
+ const disabled = await calculate(bed, { 0: { 0: { f: '=A1+1' } } }, false);
+ expect(disabled.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(0);
+ const result = await calculate(bed, { 0: { 0: { f: '=A1+1' } } }, true, 3);
+ expect(result.unitData[bed.unitId]?.[bed.sheetId]?.getValue(0, 0)?.v).toBe(3);
+ expect(result.circularReferences?.[0]).toMatchObject({ converged: false, iterations: 3 });
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+});
diff --git a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts
index e8c34e6a56..dadf2f2168 100644
--- a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts
@@ -65,6 +65,10 @@ function createService() {
setFormulaExecuteStage: vi.fn(),
getRuntimeState: vi.fn(() => ({ stage: FormulaExecuteStageType.IDLE })),
reset: vi.fn(),
+ beginCircularReferences: vi.fn(),
+ completeCircularReferences: vi.fn(),
+ clearCircularReferenceCells: vi.fn(),
+ recordCircularReferences: vi.fn(),
setFormulaCycleIndex: vi.fn(),
isCycleDependency: vi.fn(() => false),
setRuntimeFeatureCellData: vi.fn(),
@@ -137,6 +141,10 @@ function createService() {
setFormulaExecuteStage = runtimeService.setFormulaExecuteStage;
getRuntimeState = runtimeService.getRuntimeState;
reset = runtimeService.reset;
+ beginCircularReferences = runtimeService.beginCircularReferences;
+ completeCircularReferences = runtimeService.completeCircularReferences;
+ clearCircularReferenceCells = runtimeService.clearCircularReferenceCells;
+ recordCircularReferences = runtimeService.recordCircularReferences;
setFormulaCycleIndex = runtimeService.setFormulaCycleIndex;
isCycleDependency = runtimeService.isCycleDependency;
setRuntimeFeatureCellData = runtimeService.setRuntimeFeatureCellData;
@@ -391,14 +399,12 @@ describe('CalculateFormulaService', () => {
dirtyDefinedNameMap: {},
dirtyUnitFeatureMap: {},
dirtyUnitOtherFormulaMap: {},
- maxIteration: 3,
+ calculationSettings: { unit: { iterativeCalculation: true, maxIterations: 3, maxChange: 0.001 } },
} as never);
await completedPromise;
- expect(executeStepSpy).toHaveBeenCalledTimes(2);
+ expect(executeStepSpy).toHaveBeenCalledTimes(1);
expect(mocks.currentConfigService.load).toHaveBeenCalledTimes(1);
- expect(mocks.runtimeService.setFormulaCycleIndex).toHaveBeenCalledWith(0);
- expect(mocks.runtimeService.setFormulaCycleIndex).toHaveBeenCalledWith(1);
expect(mocks.runtimeService.setFormulaExecuteStage).toHaveBeenCalledWith(FormulaExecuteStageType.CALCULATION_COMPLETED);
expect(progress.length).toBeGreaterThanOrEqual(2);
expect(complete.length).toBe(1);
@@ -658,7 +664,7 @@ describe('CalculateFormulaService', () => {
const completed: unknown[] = [];
service.executionCompleteListener$.subscribe((item) => completed.push(item));
- await service.execute({ maxIteration: 3 } as never);
+ await service.execute({} as never);
await vi.waitFor(() => expect(mocks.runtimeService.reset).toHaveBeenCalledTimes(2));
expect(completed).toHaveLength(1);
diff --git a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
index 5e3b1df4eb..5022398be9 100644
--- a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
@@ -189,6 +189,7 @@ describe('FormulaRuntimeService', () => {
totalArrayFormulasToCalculate: 4,
completedArrayFormulasCount: 1,
stage: FormulaExecuteStageType.IDLE,
+ circularReferences: [],
formulaCycleIndex: 2,
});
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
index f4c1949bff..ba25fd61b7 100644
--- a/packages/engine-formula/src/services/calculate-formula.service.ts
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IUnitRange } from '@univerjs/core';
+import type { ICellData, IUnitRange, IWorkbookCalculationSettings } from '@univerjs/core';
import type { Observable } from 'rxjs';
import type {
IArrayFormulaRangeType,
@@ -40,17 +40,19 @@ import type { BaseValueObject } from '../engine/value-object/base-value-object';
import type { IAllRuntimeData, IExecutionInProgressParams } from './runtime.service';
import {
AsyncLock,
+ CellValueType,
createIdentifier,
Disposable,
IConfigService,
Inject,
+ normalizeWorkbookCalculationSettings,
ObjectMatrix,
requestImmediateMacroTask,
} from '@univerjs/core';
import { Subject } from 'rxjs';
import { ErrorType } from '../basics/error-type';
import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';
-import { DEFAULT_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../config/config';
+import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../config/config';
import { Lexer } from '../engine/analysis/lexer';
import { AstTreeBuilder } from '../engine/analysis/parser';
import { IFormulaDependencyGenerator } from '../engine/dependency/formula-dependency';
@@ -64,8 +66,6 @@ import { FormulaExecuteStageType, IFormulaRuntimeService } from './runtime.servi
export const DEFAULT_INTERVAL_COUNT = 500;
-export const CYCLE_REFERENCE_COUNT = 'cycleReferenceCount';
-
export const EVERY_N_FUNCTION_EXECUTION_PAUSE = 100;
export interface ICalculateFormulaService {
@@ -96,6 +96,98 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
protected _executeLock = new AsyncLock();
protected _isCalculateTreeModel: boolean = false;
+ protected _workbookCalculationSettings: Record<string, IWorkbookCalculationSettings> = {};
+ private readonly _normalizedCalculationSettings = new Map<string, IWorkbookCalculationSettings>();
+
+ protected _loadCalculationSettings(settings?: Record<string, IWorkbookCalculationSettings>): void {
+ this._workbookCalculationSettings = settings ?? {};
+ this._normalizedCalculationSettings.clear();
+ }
+
+ protected _getCalculationSettings(unitId: string): IWorkbookCalculationSettings {
+ let settings = this._normalizedCalculationSettings.get(unitId);
+ if (settings == null) {
+ settings = normalizeWorkbookCalculationSettings(this._workbookCalculationSettings[unitId]);
+ this._normalizedCalculationSettings.set(unitId, settings);
+ }
+ return settings;
+ }
+
+ protected _getIterationCell(tree: { unitId: string; subUnitId: string; row: number; column: number }): Pick<ICellData, 'v' | 't'> {
+ const cell = this._runtimeService.getUnitData()[tree.unitId]?.[tree.subUnitId]?.getValue(tree.row, tree.column) ??
+ this._currentConfigService.getUnitData()[tree.unitId]?.[tree.subUnitId]?.cellData.getValue(tree.row, tree.column) ??
+ { v: 0 };
+ return cell.v == null ? { v: 0, t: CellValueType.NUMBER } : cell;
+ }
+
+ protected async* _iterateCalculationGroup<T extends { unitId: string; subUnitId: string; row: number; column: number }>(
+ group: T[],
+ groupId: string
+ ) {
+ const settings = group.map((item) => this._getCalculationSettings(item.unitId));
+ const limit = settings.reduce((limit, setting) => Math.max(limit, setting.iterativeCalculation ? setting.maxIterations : 0), 1);
+ let converged = false;
+ let iterations = 0;
+ const beforeValues: ICellData['v'][] = [];
+ const beforeTypes: ICellData['t'][] = [];
+ for (let iteration = 0; iteration < limit; iteration++) {
+ for (let i = 0; i < group.length; i++) {
+ if (settings[i].iterativeCalculation) {
+ const before = this._getIterationCell(group[i]);
+ beforeValues[i] = before.v;
+ beforeTypes[i] = before.t;
+ }
+ }
+ for (let i = 0; i < group.length; i++) {
+ if (iteration < (settings[i].iterativeCalculation ? settings[i].maxIterations : 1)) {
+ // Each member can change a range read by the next member in this round.
+ FORMULA_REF_TO_ARRAY_CACHE.clear();
+ yield { tree: group[i], preserve: !settings[i].iterativeCalculation, iteration };
+ }
+ }
+ iterations = iteration + 1;
+ converged = group.every((item, i) => {
+ if (!settings[i].iterativeCalculation) {
+ return true;
+ }
+ const after = this._getIterationCell(item);
+ const previousValue = beforeValues[i];
+ return typeof after.v === 'number' && typeof previousValue === 'number' &&
+ (after.t == null || after.t === CellValueType.NUMBER) &&
+ (beforeTypes[i] == null || beforeTypes[i] === CellValueType.NUMBER)
+ ? Number.isFinite(after.v) && Math.abs(after.v - previousValue) <= settings[i].maxChange
+ : after.t === beforeTypes[i] && after.v === previousValue;
+ });
+ if (converged) {
+ break;
+ }
+ }
+ FORMULA_REF_TO_ARRAY_CACHE.clear();
+ this._runtimeService.recordCircularReferences(group.map((item, i) => ({
+ unitId: item.unitId,
+ sheetId: item.subUnitId,
+ row: item.row,
+ column: item.column,
+ groupId,
+ iterations: settings[i].iterativeCalculation ? Math.min(iterations, settings[i].maxIterations) : 0,
+ converged: settings[i].iterativeCalculation ? converged : undefined,
+ })));
+ }
+
+ protected async* _getCalculationSteps<T extends { cycleGroup?: string; unitId: string; subUnitId: string; row: number; column: number }>(trees: T[]) {
+ while (trees.length) {
+ const tree = trees.pop()!;
+ if (tree.cycleGroup == null) {
+ yield { tree, preserve: false, iteration: 0 };
+ continue;
+ }
+ const group = [tree];
+ while (trees.length && trees[trees.length - 1].cycleGroup === tree.cycleGroup) {
+ group.push(trees.pop()!);
+ }
+ yield* this._iterateCalculationGroup(group, tree.cycleGroup);
+ }
+ }
constructor(
@IConfigService protected readonly _configService: IConfigService,
@@ -151,22 +243,11 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
this._runtimeService.reset();
- const cycleReferenceCount = (formulaDatasetConfig.maxIteration || DEFAULT_CYCLE_REFERENCE_COUNT) as number;
-
+ this._loadCalculationSettings(formulaDatasetConfig.calculationSettings);
+ this._runtimeService.beginCircularReferences();
this._isCalculateTreeModel = formulaDatasetConfig.isCalculateTreeModel || false;
-
- for (let i = 0; i < cycleReferenceCount; i++) {
- this._runtimeService.setFormulaCycleIndex(i);
- const executed = await this._executeStep();
-
- FORMULA_REF_TO_ARRAY_CACHE.clear();
-
- const isCycleDependency = this._runtimeService.isCycleDependency();
- if (!executed || !isCycleDependency) {
- break;
- }
- }
-
+ await this._executeStep();
+ this._runtimeService.completeCircularReferences();
this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CALCULATION_COMPLETED);
this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());
@@ -295,8 +376,8 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
const intervalCount = config?.intervalCount || DEFAULT_INTERVAL_COUNT;
let i = 0;
const treeCount = treeList.length;
- while (treeList.length > 0) {
- const tree = treeList.pop()!;
+ for await (const { tree, preserve, iteration } of this._getCalculationSteps(treeList)) {
+ this._runtimeService.setFormulaCycleIndex(iteration);
this._runtimeService.setCurrent(
tree.row,
@@ -307,21 +388,6 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
tree.unitId
);
- const node = generateAstNode(
- tree.unitId,
- tree.formula,
- this._lexer,
- this._astTreeBuilder,
- this._currentConfigService,
- tree.subUnitId,
- tree.column,
- tree.row
- );
- const nodeData = {
- node,
- refOffsetX: tree.refOffsetX,
- refOffsetY: tree.refOffsetY,
- };
const getDirtyData = tree.getDirtyData;
// Execute the await every 100 iterations
@@ -348,13 +414,34 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor
this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());
- if (this._runtimeService.isStopExecution() || (nodeData == null && getDirtyData == null)) {
+ if (this._runtimeService.isStopExecution()) {
this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.IDLE);
this._runtimeService.markedAsStopFunctionsExecuted();
return;
}
}
+ if (preserve) {
+ this._runtimeService.preserveCurrentCellData();
+ i++;
+ continue;
+ }
+
+ const node = generateAstNode(
+ tree.unitId,
+ tree.formula,
+ this._lexer,
+ this._astTreeBuilder,
+ this._currentConfigService,
+ tree.subUnitId,
+ tree.column,
+ tree.row
+ );
+ const nodeData = {
+ node,
+ refOffsetX: tree.refOffsetX,
+ refOffsetY: tree.refOffsetY,
+ };
let value: FunctionVariantType;
if (getDirtyData != null && tree.featureId != null) {
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index c0fc653252..31ca13dcee 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { BaseDataModel, ITableSnapshot, IUnitRange, LocaleType, Nullable, Workbook } from '@univerjs/core';
+import type { BaseDataModel, ITableSnapshot, IUnitRange, IWorkbookCalculationSettings, LocaleType, Nullable, Workbook } from '@univerjs/core';
import type {
IArrayFormulaRangeType,
IDirtyUnitDefinedNameMap,
@@ -57,7 +57,7 @@ export interface IFormulaDirtyData {
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap;
clearDependencyTreeCache: IDirtyUnitSheetNameMap; // unitId -> sheetId
- maxIteration?: number;
+ calculationSettings?: Record<string, IWorkbookCalculationSettings>;
isCalculateTreeModel?: boolean; // whether to calculate the dependency tree model
rowData?: IUnitRowData; // Include rows hidden by filters
externalReferences?: IFormulaExternalReferences;
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index 8eb71aad3c..b9431bf6da 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, IRange, Nullable } from '@univerjs/core';
+import type { ICellData, IRange, Nullable, Workbook } from '@univerjs/core';
import type {
IArrayFormulaEmbeddedMap,
IArrayFormulaRangeType,
@@ -31,7 +31,7 @@ import type { BaseReferenceObject, FunctionVariantType } from '../engine/referen
import type { ArrayValueObject } from '../engine/value-object/array-value-object';
import type { BaseValueObject } from '../engine/value-object/base-value-object';
import type { StringValueObject } from '../engine/value-object/primitive-object';
-import { CellValueType, createIdentifier, Disposable, isNullCell, isRealNum, ObjectMatrix } from '@univerjs/core';
+import { CellValueType, createIdentifier, Disposable, isNullCell, isRealNum, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';
import { isInDirtyRange } from '../basics/dirty';
import { ErrorType } from '../basics/error-type';
import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';
@@ -68,7 +68,18 @@ export enum FormulaExecutedStateType {
SUCCESS,
}
+export interface ICircularReference {
+ unitId: string;
+ sheetId: string;
+ row: number;
+ column: number;
+ groupId: string;
+ iterations: number;
+ converged?: boolean;
+}
+
export interface IAllRuntimeData {
+ circularReferences?: ICircularReference[];
unitData: IRuntimeUnitDataType;
sourceFormulaData?: IFormulaData;
arrayFormulaRange: IArrayFormulaRangeType;
@@ -92,6 +103,7 @@ export interface IExecutionInProgressParams {
totalArrayFormulasToCalculate: number;
completedArrayFormulasCount: number;
+ circularReferences?: ICircularReference[];
formulaCycleIndex: number;
stage: FormulaExecuteStageType;
@@ -113,6 +125,11 @@ export interface IFormulaRuntimeService {
dispose(): void;
reset(): void;
+ beginCircularReferences(): void;
+ clearCircularReferenceCells(cells: { unitId: string; subUnitId: string; row: number; column: number }[]): void;
+ recordCircularReferences(cells: ICircularReference[]): void;
+ completeCircularReferences(): void;
+ preserveCurrentCellData(): void;
setCurrent(
row: number,
@@ -215,6 +232,9 @@ export interface IFormulaRuntimeService {
export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeService {
private _formulaExecuteStage: FormulaExecuteStageType = FormulaExecuteStageType.IDLE;
+ private _circularReferences = new Map<string, ICircularReference>();
+ private _pendingCircularReferences = new Map<string, ICircularReference>();
+
private _stopState = false;
private _externalReferenceUnavailable = false;
@@ -270,9 +290,22 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
constructor(
@IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService,
- @IHyperlinkEngineFormulaService private readonly _hyperlinkEngineFormulaService: IHyperlinkEngineFormulaService
+ @IHyperlinkEngineFormulaService private readonly _hyperlinkEngineFormulaService: IHyperlinkEngineFormulaService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
) {
super();
+
+ this.disposeWithMe(
+ this._univerInstanceService.getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {
+ for (const references of [this._circularReferences, this._pendingCircularReferences]) {
+ for (const [key, cell] of references) {
+ if (cell.unitId === workbook.getUnitId()) {
+ references.delete(key);
+ }
+ }
+ }
+ })
+ );
}
get currentRow() {
@@ -305,6 +338,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
super.dispose();
this.reset();
+ this._circularReferences.clear();
+ this._pendingCircularReferences.clear();
this._runtimeFeatureCellData = Object.create(null);
this._runtimeFeatureRange = Object.create(null);
this.clearReferenceAndNumberformatCache();
@@ -428,6 +463,65 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
clearReferenceToRangeCache();
}
+ beginCircularReferences(): void {
+ this._pendingCircularReferences = new Map(this._circularReferences);
+ const formulaData = this._currentConfigService.getFormulaData();
+ for (const [key, cell] of this._pendingCircularReferences) {
+ if (!formulaData[cell.unitId]?.[cell.sheetId]?.[cell.row]?.[cell.column]) {
+ this._pendingCircularReferences.delete(key);
+ }
+ }
+ }
+
+ clearCircularReferenceCells(cells: { unitId: string; subUnitId: string; row: number; column: number }[]): void {
+ if (this._pendingCircularReferences.size === 0) {
+ return;
+ }
+ for (const cell of cells) {
+ this._pendingCircularReferences.delete(JSON.stringify([cell.unitId, cell.subUnitId, cell.row, cell.column]));
+ if (this._pendingCircularReferences.size === 0) {
+ return;
+ }
+ }
+ }
+
+ recordCircularReferences(cells: ICircularReference[]): void {
+ for (const cell of cells) {
+ if (cell.row < 0 || cell.column < 0) {
+ continue;
+ }
+ this._pendingCircularReferences.set(JSON.stringify([cell.unitId, cell.sheetId, cell.row, cell.column]), { ...cell });
+ }
+ }
+
+ completeCircularReferences(): void {
+ if (!this.isStopExecution()) {
+ this._circularReferences = new Map(this._pendingCircularReferences);
+ }
+ }
+
+ preserveCurrentCellData(): void {
+ const unitId = this.currentUnitId;
+ const sheetId = this.currentSubUnitId;
+ const cell = this._currentConfigService.getUnitData()[unitId]?.[sheetId]?.cellData
+ .getValue(this.currentRow, this.currentColumn);
+ if (cell?.v != null) {
+ return;
+ }
+ const sheets = this._runtimeData[unitId] ??= {};
+ const matrix = sheets[sheetId] ??= new ObjectMatrix<ICellData>();
+ matrix.setValue(this.currentRow, this.currentColumn, {
+ v: cell?.v ?? 0,
+ t: cell?.v == null ? CellValueType.NUMBER : cell.t,
+ });
+ if (this._currentSourceFormula) {
+ const formulas = this._sourceFormulaData[unitId] ??= {};
+ const sheet = formulas[sheetId] ??= {};
+ const row = sheet[this.currentRow] ??= {};
+ row[this.currentColumn] = { ...this._currentSourceFormula };
+ }
+ }
+
setCurrent(
row: number,
column: number,
@@ -876,6 +970,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
getAllRuntimeData(): IAllRuntimeData {
return {
unitData: this.getUnitData(),
+ circularReferences: Array.from(this._circularReferences.values(), (cell) => ({ ...cell })),
sourceFormulaData: this._sourceFormulaData,
arrayFormulaRange: this.getUnitArrayFormula(),
arrayFormulaEmbedded: this.getUnitArrayFormulaEmbeddedMap(),
@@ -904,6 +999,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
stage: this.getFormulaExecuteStage(),
+ circularReferences: Array.from(this._circularReferences.values(), (cell) => ({ ...cell })),
formulaCycleIndex: this.getFormulaCycleIndex(),
};
}
diff --git a/packages/sheets-formula-ui/src/commands/operations/calculation-options.operation.ts b/packages/sheets-formula-ui/src/commands/operations/calculation-options.operation.ts
new file mode 100644
index 0000000000..9e31f79e33
--- /dev/null
+++ b/packages/sheets-formula-ui/src/commands/operations/calculation-options.operation.ts
@@ -0,0 +1,49 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, Workbook } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { IDialogService } from '@univerjs/ui';
+import { CALCULATION_OPTIONS_COMPONENT, CALCULATION_OPTIONS_DIALOG } from '../../views/calculation-options/interface';
+
+export const CalculationOptionsOperation: ICommand<{ unitId?: string }> = {
+ id: 'sheets-formula-ui.operation.calculation-options',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ const instanceService = accessor.get(IUniverInstanceService);
+ const workbook = params?.unitId
+ ? instanceService.getUnit<Workbook>(params.unitId, UniverInstanceType.UNIVER_SHEET)
+ : instanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ if (!workbook) {
+ return false;
+ }
+ const dialogService = accessor.get(IDialogService);
+ dialogService.close(CALCULATION_OPTIONS_DIALOG);
+ dialogService.open({
+ id: CALCULATION_OPTIONS_DIALOG,
+ title: { title: 'sheets-formula-ui.calculation.title' },
+ children: {
+ label: {
+ name: CALCULATION_OPTIONS_COMPONENT,
+ props: { unitId: workbook.getUnitId() },
+ },
+ },
+ width: 420,
+ onClose: () => dialogService.close(CALCULATION_OPTIONS_DIALOG),
+ });
+ return true;
+ },
+};
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-alert-render.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-alert-render.controller.spec.ts
index 9d44a874be..892c49b20a 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-alert-render.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-alert-render.controller.spec.ts
@@ -14,109 +14,175 @@
* limitations under the License.
*/
-import { ErrorType, extractFormulaError } from '@univerjs/engine-formula';
+import type { ICellData, IWorkbookData, Workbook } from '@univerjs/core';
+import type { ISetFormulaCalculationNotificationMutation } from '@univerjs/engine-formula';
+import type { ICellAlert } from '@univerjs/sheets-ui';
+import { CellValueType, ICommandService, LocaleService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
+import { FormulaDataModel, LexerTreeBuilder, SetFormulaCalculationNotificationMutation } from '@univerjs/engine-formula';
+import { getPrimaryForRange, SetWorkbookCalculationSettingsMutation, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
+import { CellAlertManagerService, CellAlertType, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { IDialogService } from '@univerjs/ui';
import { Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { CalculationOptionsOperation } from '../../commands/operations/calculation-options.operation';
+import enUS from '../../locale/en-US';
+import { CALCULATION_OPTIONS_COMPONENT } from '../../views/calculation-options/interface';
import { FormulaAlertRenderController } from '../formula-alert-render.controller';
-vi.mock('@univerjs/engine-formula', async (importActual) => {
- const actual = await importActual<typeof import('@univerjs/engine-formula')>();
+function createController() {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ id: 'u',
+ name: 'Test',
+ appVersion: 'test',
+ locale: LocaleType.EN_US,
+ sheetOrder: ['s'],
+ styles: {},
+ sheets: { s: { id: 's', name: 'Sheet1', rowCount: 20, columnCount: 20, cellData: { 0: { 0: { f: '=1/0', v: '#DIV/0!', t: CellValueType.STRING } } } } },
+ });
+ const worksheet = workbook.getActiveSheet();
+ const getCell = vi.spyOn(worksheet, 'getCell');
+ const alerts = new Map<string, { alert: ICellAlert }>();
+ const showAlert = vi.fn((alert: ICellAlert) => alerts.set(alert.key, { alert }));
+ const editor$ = new Subject<void>();
+ let editing = false;
+ const openDialog = vi.fn();
+ const resetCache = vi.fn();
+ const reCalculate = vi.fn();
+ // These providers represent the renderer and editor, unavailable in this model test.
+ injector.add([CellAlertManagerService, { useValue: {
+ currentAlert: alerts,
+ showAlert,
+ removeAlert: (key: string) => alerts.delete(key),
+ } as never }]);
+ injector.add([IEditorBridgeService, { useValue: {
+ visible$: editor$,
+ isVisible: () => ({ visible: editing }),
+ } as never }]);
+ injector.add([IDialogService, { useValue: { open: openDialog, close: vi.fn() } as never }]);
+ injector.add([SheetsSelectionsService]);
+ injector.add([SheetSkeletonService, { useValue: { getSkeletonsByUnitId: () => [{ resetCache }] } as never }]);
+ injector.add([SheetSkeletonManagerService, { useValue: { reCalculate } as never }]);
+ injector.add([LexerTreeBuilder]);
+ injector.add([FormulaDataModel]);
+ injector.add([FormulaAlertRenderController, {
+ useFactory: () => injector.createInstance(FormulaAlertRenderController, { unit: workbook } as never),
+ }]);
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ const commands = injector.get(ICommandService);
+ commands.registerCommand(SetFormulaCalculationNotificationMutation);
+ commands.registerCommand(CalculationOptionsOperation);
+ commands.registerCommand(SetWorkbookCalculationSettingsMutation);
+ const controller = injector.get(FormulaAlertRenderController);
+ getCell.mockClear();
+ function notify(params: ISetFormulaCalculationNotificationMutation) {
+ commands.syncExecuteCommand(SetFormulaCalculationNotificationMutation.id, params);
+ }
return {
- ...actual,
- extractFormulaError: vi.fn(() => actual.ErrorType.DIV_BY_ZERO),
+ controller,
+ injector,
+ univer,
+ showAlert,
+ alerts,
+ worksheet,
+ openDialog,
+ resetCache,
+ reCalculate,
+ focus(row = 0) {
+ const range = { startRow: row, endRow: row, startColumn: 0, endColumn: 0 };
+ injector.get(SheetsSelectionsService).setSelections('u', 's', [{
+ range,
+ primary: getPrimaryForRange(range, worksheet),
+ style: null,
+ }]);
+ },
+ setCell(next: ICellData) {
+ worksheet.getCellMatrix().setValue(0, 0, next);
+ notify({ circularReferences: [] });
+ },
+ setEditing(value: boolean) {
+ editing = value;
+ editor$.next();
+ },
+ setEnabled(value: boolean) {
+ commands.syncExecuteCommand(SetWorkbookCalculationSettingsMutation.id, {
+ unitId: 'u',
+ settings: { ...workbook.getCalculationSettings(), iterativeCalculation: value },
+ });
+ },
+ notify,
};
-});
-
-afterEach(() => {
- vi.useRealTimers();
-});
+}
describe('FormulaAlertRenderController', () => {
- it('shows formula alerts for hovered cells and hides them for repeated hovers', async () => {
- vi.useFakeTimers();
- const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();
- const currentAlert = new Map<string, { alert: { location: { unitId: string; subUnitId: string; row: number; col: number } } }>();
- const showAlert = vi.fn((alert) => currentAlert.set('SHEET_FORMULA_ALERT', { alert }));
- const removeAlert = vi.fn((key: string) => currentAlert.delete(key));
- const worksheet = { getCell: vi.fn(() => ({ v: '#DIV/0!' })) };
-
- const controller = new FormulaAlertRenderController(
- { unit: { getActiveSheet: vi.fn(() => worksheet) } } as never,
- { currentCell$ } as never,
- { currentAlert, removeAlert, showAlert } as never,
- { t: (key: string) => key } as never,
- { getArrayFormulaCellData: vi.fn(() => null) } as never
- );
-
- expect(controller).toBeTruthy();
-
- const location = { unitId: 'book-1', subUnitId: 'sheet-1', row: 2, col: 1 };
- currentCell$.next({ location });
- await vi.advanceTimersByTimeAsync(120);
-
- expect(showAlert).toHaveBeenCalledWith(expect.objectContaining({
- key: 'SHEET_FORMULA_ALERT',
- title: 'sheets-formula-ui.error.title',
- message: 'sheets-formula-ui.error.divByZero',
- location,
+ const disposables: Array<() => void> = [];
+ afterEach(() => disposables.splice(0).forEach((dispose) => dispose()));
+ function setup() {
+ const bed = createController();
+ disposables.push(() => {
+ bed.controller.dispose();
+ bed.univer.dispose();
+ });
+ return bed;
+ }
+
+ it('checks the focused cell and retains the same alert on repeated focus', () => {
+ const bed = setup();
+ expect(bed.worksheet.getCell).not.toHaveBeenCalled();
+ bed.focus();
+ expect(bed.showAlert).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'Error',
+ message: 'Divide by zero error',
+ location: { unitId: 'u', subUnitId: 's', row: 0, col: 0 },
}));
-
- currentCell$.next({ location });
- await vi.advanceTimersByTimeAsync(120);
- expect(removeAlert).toHaveBeenCalledWith('SHEET_FORMULA_ALERT');
+ bed.focus();
+ expect(bed.showAlert).toHaveBeenCalledTimes(1);
+ bed.focus(1);
+ expect(bed.alerts.size).toBe(0);
+ bed.focus();
+ expect(bed.showAlert).toHaveBeenCalledTimes(2);
});
- it('hides alerts when there is no extractable formula error', async () => {
- vi.useFakeTimers();
- vi.mocked(extractFormulaError).mockReturnValueOnce(null as never);
- const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();
- const removeAlert = vi.fn();
-
- const controller = new FormulaAlertRenderController(
- { unit: { getActiveSheet: vi.fn(() => ({ getCell: vi.fn(() => ({ v: 'plain-text' })) })) } } as never,
- { currentCell$ } as never,
- { currentAlert: new Map(), removeAlert, showAlert: vi.fn() } as never,
- { t: (key: string) => key } as never,
- { getArrayFormulaCellData: vi.fn(() => null) } as never
- );
-
- expect(controller).toBeTruthy();
-
- currentCell$.next({ location: { unitId: 'book-1', subUnitId: 'sheet-1', row: 0, col: 0 } });
- await vi.advanceTimersByTimeAsync(120);
-
- expect(removeAlert).toHaveBeenCalledWith('SHEET_FORMULA_ALERT');
- expect(vi.mocked(extractFormulaError)).toHaveBeenCalledWith({ v: 'plain-text' }, false);
- expect(ErrorType.DIV_BY_ZERO).toBeTruthy();
+ it('refreshes an unchanged focus after calculation and opens the shared settings operation', () => {
+ const bed = setup();
+ bed.setCell({ f: '=A1', v: 0, t: CellValueType.NUMBER });
+ bed.focus();
+ expect(bed.alerts.size).toBe(0);
+ bed.notify({ circularReferences: [{ unitId: 'u', sheetId: 's', row: 0, column: 0, groupId: 'g', iterations: 0 }] });
+ const alert = bed.alerts.get('SHEET_FORMULA_ALERT:u')!.alert;
+ expect(alert.type).toBe(CellAlertType.ERROR);
+ expect(bed.resetCache).toHaveBeenCalledTimes(1);
+ expect(bed.reCalculate).toHaveBeenCalledTimes(1);
+ expect(alert.action?.label).toBe('Iterative Calculation');
+ alert.action!.onSelect();
+ expect(bed.openDialog).toHaveBeenCalledWith(expect.objectContaining({
+ children: { label: { name: CALCULATION_OPTIONS_COMPONENT, props: { unitId: 'u' } } },
+ }));
+ bed.setEnabled(true);
+ expect(bed.alerts.size).toBe(0);
+ expect(bed.resetCache).toHaveBeenCalledTimes(2);
+ bed.setEnabled(false);
+ expect(bed.alerts.size).toBe(1);
+ expect(bed.resetCache).toHaveBeenCalledTimes(3);
+ bed.notify({ circularReferences: [] });
+ expect(bed.alerts.size).toBe(0);
+ expect(bed.resetCache).toHaveBeenCalledTimes(4);
});
- it('hides alerts when the workbook has no active worksheet for the hovered cell', async () => {
- vi.useFakeTimers();
- const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();
- const removedAlerts: string[] = [];
- const shownAlerts: unknown[] = [];
- const controller = new FormulaAlertRenderController(
- { unit: { getActiveSheet: () => null } } as never,
- { currentCell$ } as never,
- {
- currentAlert: new Map(),
- removeAlert: (key: string) => {
- removedAlerts.push(key);
- },
- showAlert: (alert: unknown) => {
- shownAlerts.push(alert);
- },
- } as never,
- { t: (key: string) => key } as never,
- { getArrayFormulaCellData: () => null } as never
- );
-
- currentCell$.next({ location: { unitId: 'book-1', subUnitId: 'sheet-1', row: 3, col: 4 } });
- await vi.advanceTimersByTimeAsync(120);
-
- expect(removedAlerts).toEqual(['SHEET_FORMULA_ALERT']);
- expect(shownAlerts).toEqual([]);
-
- controller.dispose();
+ it('closes during editing and when the error or cycle disappears', () => {
+ const bed = setup();
+ bed.focus();
+ bed.setEditing(true);
+ expect(bed.alerts.size).toBe(0);
+ bed.setEditing(false);
+ expect(bed.alerts.size).toBe(1);
+ bed.setCell({ f: '=1', v: 1, t: CellValueType.NUMBER });
+ expect(bed.alerts.size).toBe(0);
+ bed.notify({ circularReferences: [] });
+ expect(bed.alerts.size).toBe(0);
});
});
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-render-manager.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-render-manager.controller.spec.ts
index aabfd525e2..bdb950747f 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-render-manager.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-render-manager.controller.spec.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import { CellValueType } from '@univerjs/core';
import { ErrorType, extractFormulaError } from '@univerjs/engine-formula';
import { INTERCEPTOR_POINT } from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
@@ -99,4 +100,43 @@ describe('FormulaRenderManagerController', () => {
controller.dispose();
});
+
+ it('marks disabled circular formulas with numeric caches and clears the mark when enabled or resolved', () => {
+ let interceptor: any;
+ const circular = vi.fn(() => true);
+ const controller = new FormulaRenderManagerController({
+ intercept: vi.fn((_point, config) => {
+ interceptor = config;
+ return { dispose: vi.fn() };
+ }),
+ } as any, {
+ getArrayFormulaCellData: () => null,
+ isCircularReference: circular,
+ } as any);
+ const settings = { iterativeCalculation: false };
+ const rawCell = { f: '=SUM(A1:B1)', v: 0, t: CellValueType.NUMBER };
+ const position = {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ row: 0,
+ col: 0,
+ rawData: rawCell,
+ workbook: { getCalculationSettings: () => settings },
+ };
+ vi.mocked(extractFormulaError).mockReturnValue(null as never);
+ const render = (cell: unknown = rawCell) => interceptor.handler(cell, position, (next: unknown) => next);
+
+ expect(render().markers?.tl).toEqual({ size: 6, color: '#409f11' });
+ expect(rawCell).not.toHaveProperty('markers');
+ expect(circular).toHaveBeenCalledWith('unit', 'sheet', 0, 0);
+
+ settings.iterativeCalculation = true;
+ expect(render()).toBe(rawCell);
+ settings.iterativeCalculation = false;
+ circular.mockReturnValue(false);
+ expect(render()).toBe(rawCell);
+ circular.mockReturnValue(true);
+ expect(render({ v: 0, t: CellValueType.NUMBER })).not.toHaveProperty('markers');
+ controller.dispose();
+ });
});
diff --git a/packages/sheets-formula-ui/src/controllers/components.controller.ts b/packages/sheets-formula-ui/src/controllers/components.controller.ts
index 873d9031a6..0827e4d7d5 100644
--- a/packages/sheets-formula-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/components.controller.ts
@@ -30,6 +30,8 @@ import {
} from '@univerjs/icons';
import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '@univerjs/sheets-ui';
import { ComponentManager, IconManager } from '@univerjs/ui';
+import { CalculationOptions } from '../views/calculation-options/CalculationOptions';
+import { CALCULATION_OPTIONS_COMPONENT } from '../views/calculation-options/interface';
import { FormulaEditor } from '../views/formula-editor/index';
import { MORE_FUNCTIONS_COMPONENT } from '../views/more-functions/interface';
import { MoreFunctions } from '../views/more-functions/MoreFunctions';
@@ -68,5 +70,7 @@ export class ComponentsController extends Disposable {
this.disposeWithMe(this._componentManager.register(RANGE_SELECTOR_COMPONENT_KEY, RangeSelector));
this.disposeWithMe(this._componentManager.register(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, FormulaEditor));
+
+ this.disposeWithMe(this._componentManager.register(CALCULATION_OPTIONS_COMPONENT, CalculationOptions));
}
}
diff --git a/packages/sheets-formula-ui/src/controllers/formula-alert-render.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-alert-render.controller.ts
index 3de43371d6..9ef26b65bb 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-alert-render.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-alert-render.controller.ts
@@ -15,12 +15,14 @@
*/
import type { Workbook } from '@univerjs/core';
+import type { ISetFormulaCalculationNotificationMutation } from '@univerjs/engine-formula';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import type { LocaleKey } from '../locale/types';
-import { Disposable, Inject, isICellData, LocaleService } from '@univerjs/core';
-import { ErrorType, extractFormulaError, FormulaDataModel } from '@univerjs/engine-formula';
-import { CellAlertManagerService, CellAlertType, HoverManagerService } from '@univerjs/sheets-ui';
-import { debounceTime } from 'rxjs';
+import { Disposable, ICommandService, Inject, isICellData, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
+import { ErrorType, extractFormulaError, FormulaDataModel, SetFormulaCalculationNotificationMutation } from '@univerjs/engine-formula';
+import { SetRangeValuesMutation, SetWorkbookCalculationSettingsMutation, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
+import { CellAlertManagerService, CellAlertType, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { CalculationOptionsOperation } from '../commands/operations/calculation-options.operation';
const ALERT_KEY = 'SHEET_FORMULA_ALERT';
@@ -40,78 +42,127 @@ const ErrorTypeToMessageMap = {
};
export class FormulaAlertRenderController extends Disposable implements IRenderModule {
+ private _circularLocations = new Set<string>();
+
constructor(
private readonly _context: IRenderContext<Workbook>,
- @Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,
+ @Inject(SheetsSelectionsService) private readonly _selectionsService: SheetsSelectionsService,
@Inject(CellAlertManagerService) private readonly _cellAlertManagerService: CellAlertManagerService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(SheetSkeletonService) private readonly _sheetSkeletonService: SheetSkeletonService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _instanceService: IUniverInstanceService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService
) {
super();
- this._init();
- }
-
- private _init() {
- this._initCellAlertPopup();
- }
-
- private _initCellAlertPopup() {
- this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(debounceTime(100)).subscribe((cellPos) => {
- if (cellPos) {
- const workbook = this._context.unit;
- const worksheet = workbook.getActiveSheet();
-
- if (!worksheet) return this._hideAlert();
- const cellData = worksheet.getCell(cellPos.location.row, cellPos.location.col);
-
- const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData()?.
- [cellPos.location.unitId]?.
- [cellPos.location.subUnitId]?.
- [cellPos.location.row]?.
- [cellPos.location.col];
-
- // Preventing blank object
- if (isICellData(cellData)) {
- const errorType = extractFormulaError(cellData, !!arrayFormulaCellData);
-
- if (!errorType) {
- // fix #4002
- this._hideAlert();
- return;
+ this.disposeWithMe(this._selectionsService.selectionChanged$.subscribe(() => this._updateAlert()));
+ this.disposeWithMe(this._context.unit.activeSheet$.subscribe(() => this._updateAlert()));
+ this.disposeWithMe(this._instanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET)
+ .subscribe(() => this._updateAlert()));
+ this.disposeWithMe(this._editorBridgeService.visible$.subscribe(() => this._updateAlert()));
+ this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
+ if (command.id === SetFormulaCalculationNotificationMutation.id) {
+ const params = command.params as ISetFormulaCalculationNotificationMutation;
+ if (params.circularReferences) {
+ const locations = new Set(params.circularReferences
+ .filter((cell) => cell.unitId === this._context.unit.getUnitId())
+ .map((cell) => JSON.stringify([cell.sheetId, cell.row, cell.column])));
+ const changed = locations.size !== this._circularLocations.size ||
+ Array.from(locations).some((location) => !this._circularLocations.has(location));
+ this._circularLocations = locations;
+ this._formulaDataModel.setCircularReferences(params.circularReferences);
+ if (changed) {
+ this._refreshMarkers();
}
-
- const currentAlert = this._cellAlertManagerService.currentAlert.get(ALERT_KEY);
- const currentLoc = currentAlert?.alert?.location;
- if (
- currentLoc &&
- currentLoc.row === cellPos.location.row &&
- currentLoc.col === cellPos.location.col &&
- currentLoc.subUnitId === cellPos.location.subUnitId &&
- currentLoc.unitId === cellPos.location.unitId
- ) {
- this._hideAlert();
- return;
- }
-
- this._cellAlertManagerService.showAlert({
- type: CellAlertType.ERROR,
- title: this._localeService.t<LocaleKey>('sheets-formula-ui.error.title'),
- message: this._localeService.t(`sheets-formula-ui.error.${ErrorTypeToMessageMap[errorType]}`),
- location: cellPos.location,
- width: 200,
- height: 74,
- key: ALERT_KEY,
- });
- return;
+ this._updateAlert();
}
+ } else if (command.id === SetRangeValuesMutation.id || command.id === SetWorkbookCalculationSettingsMutation.id) {
+ if (command.id === SetWorkbookCalculationSettingsMutation.id &&
+ (command.params as { unitId: string }).unitId === this._context.unit.getUnitId()) {
+ this._refreshMarkers();
+ }
+ this._updateAlert();
}
+ }));
+ this.disposeWithMe(() => this._hideAlert());
+ }
+ private _updateAlert(): void {
+ const workbook = this._context.unit;
+ const worksheet = workbook.getActiveSheet();
+ const selection = this._selectionsService.currentSelectionParam;
+ const currentWorkbook = this._instanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ if (!worksheet || selection?.unitId !== workbook.getUnitId() || selection.sheetId !== worksheet.getSheetId() ||
+ currentWorkbook?.getUnitId() !== workbook.getUnitId() || this._editorBridgeService.isVisible().visible) {
this._hideAlert();
- }));
+ return;
+ }
+ const selections = this._selectionsService.getCurrentSelections();
+ const primary = selections?.[selections.length - 1]?.primary;
+ if (!primary) {
+ this._hideAlert();
+ return;
+ }
+ const row = primary.actualRow;
+ const col = primary.actualColumn;
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ const cell = worksheet.getCell(row, col);
+ const circular = !workbook.getCalculationSettings().iterativeCalculation && Boolean(cell?.f || cell?.si) &&
+ this._formulaDataModel.isCircularReference(unitId, subUnitId, row, col);
+ const arrayCell = this._formulaDataModel.getArrayFormulaCellData()?.[unitId]?.[subUnitId]?.[row]?.[col];
+ const error = isICellData(cell) ? extractFormulaError(cell, !!arrayCell) : undefined;
+ if (!circular && !error) {
+ this._hideAlert();
+ return;
+ }
+ const message = circular
+ ? this._localeService.t<LocaleKey>('sheets-formula-ui.calculation.circular')
+ : this._localeService.t(
+ (`sheets-formula-ui.error.${ErrorTypeToMessageMap[error!]}`) as LocaleKey
+ );
+ const previous = this._cellAlertManagerService.currentAlert.get(this._alertKey)?.alert;
+ if (previous?.location.row === row && previous.location.col === col &&
+ previous.location.subUnitId === subUnitId && previous.message === message && Boolean(previous.action) === circular) {
+ return;
+ }
+ this._cellAlertManagerService.showAlert({
+ type: CellAlertType.ERROR,
+ title: this._localeService.t<LocaleKey>(circular
+ ? 'sheets-formula-ui.calculation.circularTitle'
+ : 'sheets-formula-ui.error.title'),
+ message,
+ location: { unitId, subUnitId, row, col },
+ width: 240,
+ height: circular ? 124 : 74,
+ key: this._alertKey,
+ action: circular
+ ? {
+ label: this._localeService.t<LocaleKey>('sheets-formula-ui.calculation.action'),
+ onSelect: () => {
+ this._commandService.syncExecuteCommand(CalculationOptionsOperation.id, { unitId });
+ },
+ }
+ : undefined,
+ });
+ }
+
+ private get _alertKey(): string {
+ return `${ALERT_KEY}:${this._context.unit.getUnitId()}`;
+ }
+
+ private _refreshMarkers(): void {
+ // Circular diagnostics can change while cached cell values remain identical.
+ this._sheetSkeletonService.getSkeletonsByUnitId(this._context.unit.getUnitId())
+ .forEach((skeleton) => skeleton.resetCache());
+ this._sheetSkeletonManagerService.reCalculate();
+ this._context.mainComponent?.makeDirty();
}
- private _hideAlert() {
- this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ private _hideAlert(): void {
+ this._cellAlertManagerService.removeAlert(this._alertKey);
}
}
diff --git a/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts
index 2323055d4d..1f8d9b1fa8 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts
@@ -44,7 +44,10 @@ export class FormulaRenderManagerController extends RxDisposable {
[pos.col];
const errorType = extractFormulaError(cell, !!arrayFormulaCellData);
- if (!errorType) {
+ const circular = Boolean(cell?.f || cell?.si) &&
+ !pos.workbook.getCalculationSettings().iterativeCalculation &&
+ this._formulaDataModel.isCircularReference(pos.unitId, pos.subUnitId, pos.row, pos.col);
+ if (!errorType && !circular) {
return next(cell);
}
diff --git a/packages/sheets-formula-ui/src/controllers/ui.controller.ts b/packages/sheets-formula-ui/src/controllers/ui.controller.ts
index 061239b4e8..2a1614d2c8 100644
--- a/packages/sheets-formula-ui/src/controllers/ui.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/ui.controller.ts
@@ -20,6 +20,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';
import { SheetsUIPart } from '@univerjs/sheets-ui';
import { connectInjector, IShortcutService, IUIPartsService } from '@univerjs/ui';
import { SheetCopyFormulaOnlyCommand, SheetOnlyPasteFormulaCommand } from '../commands/commands/formula-clipboard.command';
+import { CalculationOptionsOperation } from '../commands/operations/calculation-options.operation';
import { HelpFunctionOperation } from '../commands/operations/help-function.operation';
import { InsertFunctionOperation } from '../commands/operations/insert-function.operation';
import { MoreFunctionsOperation } from '../commands/operations/more-functions.operation';
@@ -56,6 +57,7 @@ export class FormulaUIController extends Disposable {
SheetOnlyPasteFormulaCommand,
InsertFunctionOperation,
MoreFunctionsOperation,
+ CalculationOptionsOperation,
SearchFunctionOperation,
HelpFunctionOperation,
ReferenceAbsoluteOperation,
diff --git a/packages/sheets-formula-ui/src/locale/ar-SA.ts b/packages/sheets-formula-ui/src/locale/ar-SA.ts
index 5ce353a015..6627f01e3f 100644
--- a/packages/sheets-formula-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-formula-ui/src/locale/ar-SA.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'مرجع دائري',
+ title: 'خيارات الحساب',
+ enable: 'تمكين الحساب التكراري',
+ iterations: 'الحد الأقصى للتكرارات (1–{0})',
+ change: 'الحد الأقصى للتغيير',
+ workbook: 'تنطبق هذه الإعدادات على المصنف الحالي.',
+ invalidIterations: 'يجب أن يكون الحد الأقصى للتكرارات عددًا صحيحًا من 1 إلى {0}.',
+ invalidChange: 'يجب أن يكون الحد الأقصى للتغيير عددًا موجبًا ومحدودًا.',
+ cancel: 'إلغاء',
+ confirm: 'موافق',
+ circular: 'تحتوي هذه الصيغة على مرجع دائري. افتح خيارات الحساب لتمكين الحساب التكراري.',
+ action: 'الحساب التكراري',
+ },
+
shortcut: {
'quick-sum': 'مجموع سريع',
},
diff --git a/packages/sheets-formula-ui/src/locale/ca-ES.ts b/packages/sheets-formula-ui/src/locale/ca-ES.ts
index 5e8a89b108..098987cbd3 100644
--- a/packages/sheets-formula-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-formula-ui/src/locale/ca-ES.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Referència circular',
+ title: 'Opcions de càlcul',
+ enable: 'Activa el càlcul iteratiu',
+ iterations: 'Iteracions màximes (1–{0})',
+ change: 'Canvi màxim',
+ workbook: 'Aquesta configuració s’aplica al llibre actual.',
+ invalidIterations: 'El nombre màxim d’iteracions ha de ser un enter d’1 a {0}.',
+ invalidChange: 'El canvi màxim ha de ser un nombre positiu i finit.',
+ cancel: 'Cancel·la',
+ confirm: 'D’acord',
+ circular: 'Aquesta fórmula conté una referència circular. Obriu les opcions de càlcul per activar el càlcul iteratiu.',
+ action: 'Càlcul iteratiu',
+ },
+
shortcut: {
'quick-sum': 'Suma ràpida',
},
diff --git a/packages/sheets-formula-ui/src/locale/de-DE.ts b/packages/sheets-formula-ui/src/locale/de-DE.ts
index 53cd8896bf..6526cefa5d 100644
--- a/packages/sheets-formula-ui/src/locale/de-DE.ts
+++ b/packages/sheets-formula-ui/src/locale/de-DE.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Zirkelbezug',
+ title: 'Berechnungsoptionen',
+ enable: 'Iterative Berechnung aktivieren',
+ iterations: 'Maximale Iterationen (1–{0})',
+ change: 'Maximale Änderung',
+ workbook: 'Diese Einstellungen gelten für die aktuelle Arbeitsmappe.',
+ invalidIterations: 'Die maximale Iterationszahl muss eine ganze Zahl von 1 bis {0} sein.',
+ invalidChange: 'Die maximale Änderung muss eine endliche positive Zahl sein.',
+ cancel: 'Abbrechen',
+ confirm: 'OK',
+ circular: 'Diese Formel enthält einen Zirkelbezug. Öffnen Sie die Berechnungsoptionen, um die iterative Berechnung zu aktivieren.',
+ action: 'Iterative Berechnung',
+ },
+
shortcut: {
'quick-sum': 'Schnelle Summe',
},
diff --git a/packages/sheets-formula-ui/src/locale/en-US.ts b/packages/sheets-formula-ui/src/locale/en-US.ts
index 7ee9c7716a..1c79f43774 100644
--- a/packages/sheets-formula-ui/src/locale/en-US.ts
+++ b/packages/sheets-formula-ui/src/locale/en-US.ts
@@ -16,6 +16,21 @@
const locale = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Circular Reference',
+ title: 'Calculation Options',
+ enable: 'Enable iterative calculation',
+ iterations: 'Maximum iterations (1–{0})',
+ change: 'Maximum change',
+ workbook: 'These settings apply to the current workbook.',
+ invalidIterations: 'Maximum iterations must be an integer from 1 to {0}.',
+ invalidChange: 'Maximum change must be a finite positive number.',
+ cancel: 'Cancel',
+ confirm: 'OK',
+ circular: 'This formula contains a circular reference. Open Calculation Options to enable iterative calculation.',
+ action: 'Iterative Calculation',
+ },
+
shortcut: {
'quick-sum': 'Quick Sum',
},
diff --git a/packages/sheets-formula-ui/src/locale/es-ES.ts b/packages/sheets-formula-ui/src/locale/es-ES.ts
index 9181851830..0c20e3495b 100644
--- a/packages/sheets-formula-ui/src/locale/es-ES.ts
+++ b/packages/sheets-formula-ui/src/locale/es-ES.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Referencia circular',
+ title: 'Opciones de cálculo',
+ enable: 'Habilitar cálculo iterativo',
+ iterations: 'Iteraciones máximas (1–{0})',
+ change: 'Cambio máximo',
+ workbook: 'Esta configuración se aplica al libro actual.',
+ invalidIterations: 'Las iteraciones máximas deben ser un número entero de 1 a {0}.',
+ invalidChange: 'El cambio máximo debe ser un número positivo y finito.',
+ cancel: 'Cancelar',
+ confirm: 'Aceptar',
+ circular: 'Esta fórmula contiene una referencia circular. Abra las opciones de cálculo para habilitar el cálculo iterativo.',
+ action: 'Cálculo iterativo',
+ },
+
shortcut: {
'quick-sum': 'Suma rápida',
},
diff --git a/packages/sheets-formula-ui/src/locale/fa-IR.ts b/packages/sheets-formula-ui/src/locale/fa-IR.ts
index d36bab5ead..742e36233c 100644
--- a/packages/sheets-formula-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-formula-ui/src/locale/fa-IR.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'ارجاع دوری',
+ title: 'گزینه‌های محاسبه',
+ enable: 'فعال‌سازی محاسبه تکراری',
+ iterations: 'حداکثر تکرار (1–{0})',
+ change: 'حداکثر تغییر',
+ workbook: 'این تنظیمات برای کارپوشه فعلی اعمال می‌شوند.',
+ invalidIterations: 'حداکثر تکرار باید عددی صحیح از 1 تا {0} باشد.',
+ invalidChange: 'حداکثر تغییر باید عددی مثبت و متناهی باشد.',
+ cancel: 'لغو',
+ confirm: 'تأیید',
+ circular: 'این فرمول ارجاع دوری دارد. برای فعال‌سازی محاسبه تکراری گزینه‌های محاسبه را باز کنید.',
+ action: 'محاسبه تکراری',
+ },
+
shortcut: {
'quick-sum': 'جمع سریع',
},
diff --git a/packages/sheets-formula-ui/src/locale/fr-FR.ts b/packages/sheets-formula-ui/src/locale/fr-FR.ts
index 1c5667712e..11105d0a58 100644
--- a/packages/sheets-formula-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-formula-ui/src/locale/fr-FR.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Référence circulaire',
+ title: 'Options de calcul',
+ enable: 'Activer le calcul itératif',
+ iterations: 'Nombre maximal d’itérations (1–{0})',
+ change: 'Écart maximal',
+ workbook: 'Ces paramètres s’appliquent au classeur actuel.',
+ invalidIterations: 'Le nombre maximal d’itérations doit être un entier de 1 à {0}.',
+ invalidChange: 'L’écart maximal doit être un nombre positif et fini.',
+ cancel: 'Annuler',
+ confirm: 'OK',
+ circular: 'Cette formule contient une référence circulaire. Ouvrez les options de calcul pour activer le calcul itératif.',
+ action: 'Calcul itératif',
+ },
+
shortcut: {
'quick-sum': 'Somme rapide',
},
diff --git a/packages/sheets-formula-ui/src/locale/id-ID.ts b/packages/sheets-formula-ui/src/locale/id-ID.ts
index 3bd0fb119b..0379791e04 100644
--- a/packages/sheets-formula-ui/src/locale/id-ID.ts
+++ b/packages/sheets-formula-ui/src/locale/id-ID.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Referensi Sirkular',
+ title: 'Opsi Perhitungan',
+ enable: 'Aktifkan perhitungan iteratif',
+ iterations: 'Iterasi maksimum (1–{0})',
+ change: 'Perubahan maksimum',
+ workbook: 'Pengaturan ini berlaku untuk buku kerja saat ini.',
+ invalidIterations: 'Iterasi maksimum harus berupa bilangan bulat dari 1 hingga {0}.',
+ invalidChange: 'Perubahan maksimum harus berupa bilangan positif yang terbatas.',
+ cancel: 'Batal',
+ confirm: 'OK',
+ circular: 'Rumus ini berisi referensi melingkar. Buka Opsi Perhitungan untuk mengaktifkan perhitungan iteratif.',
+ action: 'Perhitungan Iteratif',
+ },
+
shortcut: {
'quick-sum': 'Jumlah Cepat',
},
diff --git a/packages/sheets-formula-ui/src/locale/it-IT.ts b/packages/sheets-formula-ui/src/locale/it-IT.ts
index 773ae545ce..37a57b8daf 100644
--- a/packages/sheets-formula-ui/src/locale/it-IT.ts
+++ b/packages/sheets-formula-ui/src/locale/it-IT.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Riferimento circolare',
+ title: 'Opzioni di calcolo',
+ enable: 'Abilita calcolo iterativo',
+ iterations: 'Iterazioni massime (1–{0})',
+ change: 'Variazione massima',
+ workbook: 'Queste impostazioni si applicano alla cartella di lavoro corrente.',
+ invalidIterations: 'Il numero massimo di iterazioni deve essere un intero da 1 a {0}.',
+ invalidChange: 'La variazione massima deve essere un numero positivo e finito.',
+ cancel: 'Annulla',
+ confirm: 'OK',
+ circular: 'La formula contiene un riferimento circolare. Aprire le opzioni di calcolo per abilitare il calcolo iterativo.',
+ action: 'Calcolo iterativo',
+ },
+
shortcut: {
'quick-sum': 'Somma rapida',
},
diff --git a/packages/sheets-formula-ui/src/locale/ja-JP.ts b/packages/sheets-formula-ui/src/locale/ja-JP.ts
index a1eeec4a9f..6abb119de9 100644
--- a/packages/sheets-formula-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-formula-ui/src/locale/ja-JP.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: '循環参照',
+ title: '計算オプション',
+ enable: '反復計算を有効にする',
+ iterations: '最大反復回数(1~{0})',
+ change: '最大変化量',
+ workbook: 'この設定は現在のブックに適用されます。',
+ invalidIterations: '最大反復回数は 1~{0} の整数である必要があります。',
+ invalidChange: '最大変化量は有限の正の数である必要があります。',
+ cancel: 'キャンセル',
+ confirm: 'OK',
+ circular: 'この数式には循環参照があります。計算オプションで反復計算を有効にしてください。',
+ action: '反復計算',
+ },
+
shortcut: {
'quick-sum': 'クイック合計',
},
diff --git a/packages/sheets-formula-ui/src/locale/ko-KR.ts b/packages/sheets-formula-ui/src/locale/ko-KR.ts
index 72c2267c8b..9d0d5500c4 100644
--- a/packages/sheets-formula-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-formula-ui/src/locale/ko-KR.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: '순환 참조',
+ title: '계산 옵션',
+ enable: '반복 계산 사용',
+ iterations: '최대 반복 횟수 (1–{0})',
+ change: '최대 변화값',
+ workbook: '현재 통합 문서에 적용됩니다.',
+ invalidIterations: '최대 반복 횟수는 1에서 {0} 사이의 정수여야 합니다.',
+ invalidChange: '최대 변화값은 유한한 양수여야 합니다.',
+ cancel: '취소',
+ confirm: '확인',
+ circular: '이 수식에 순환 참조가 있습니다. 계산 옵션에서 반복 계산을 사용하세요.',
+ action: '반복 계산',
+ },
+
shortcut: {
'quick-sum': '빠른 합계',
},
diff --git a/packages/sheets-formula-ui/src/locale/pl-PL.ts b/packages/sheets-formula-ui/src/locale/pl-PL.ts
index 99567c91e6..1e131e519c 100644
--- a/packages/sheets-formula-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-formula-ui/src/locale/pl-PL.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Odwołanie cykliczne',
+ title: 'Opcje obliczeń',
+ enable: 'Włącz obliczenia iteracyjne',
+ iterations: 'Maksymalna liczba iteracji (1–{0})',
+ change: 'Maksymalna zmiana',
+ workbook: 'Ustawienia dotyczą bieżącego skoroszytu.',
+ invalidIterations: 'Maksymalna liczba iteracji musi być liczbą całkowitą od 1 do {0}.',
+ invalidChange: 'Maksymalna zmiana musi być skończoną liczbą dodatnią.',
+ cancel: 'Anuluj',
+ confirm: 'OK',
+ circular: 'Formuła zawiera odwołanie cykliczne. Otwórz opcje obliczeń, aby włączyć obliczenia iteracyjne.',
+ action: 'Obliczenia iteracyjne',
+ },
+
shortcut: {
'quick-sum': 'Szybka suma',
},
diff --git a/packages/sheets-formula-ui/src/locale/pt-BR.ts b/packages/sheets-formula-ui/src/locale/pt-BR.ts
index 9cb29c653b..cb668108ef 100644
--- a/packages/sheets-formula-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-formula-ui/src/locale/pt-BR.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Referência circular',
+ title: 'Opções de cálculo',
+ enable: 'Habilitar cálculo iterativo',
+ iterations: 'Iterações máximas (1–{0})',
+ change: 'Alteração máxima',
+ workbook: 'As configurações se aplicam à pasta de trabalho atual.',
+ invalidIterations: 'O número máximo de iterações deve ser um inteiro de 1 a {0}.',
+ invalidChange: 'A alteração máxima deve ser um número positivo e finito.',
+ cancel: 'Cancelar',
+ confirm: 'OK',
+ circular: 'Esta fórmula contém uma referência circular. Abra as opções de cálculo para habilitar o cálculo iterativo.',
+ action: 'Cálculo iterativo',
+ },
+
shortcut: {
'quick-sum': 'Soma Rápida',
},
diff --git a/packages/sheets-formula-ui/src/locale/ru-RU.ts b/packages/sheets-formula-ui/src/locale/ru-RU.ts
index 0839c2e554..d289bdadd0 100644
--- a/packages/sheets-formula-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-formula-ui/src/locale/ru-RU.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Циклическая ссылка',
+ title: 'Параметры вычислений',
+ enable: 'Включить итеративные вычисления',
+ iterations: 'Максимум итераций (1–{0})',
+ change: 'Максимальное изменение',
+ workbook: 'Настройки применяются к текущей книге.',
+ invalidIterations: 'Максимальное число итераций должно быть целым числом от 1 до {0}.',
+ invalidChange: 'Максимальное изменение должно быть конечным положительным числом.',
+ cancel: 'Отмена',
+ confirm: 'ОК',
+ circular: 'Формула содержит циклическую ссылку. Откройте параметры вычислений, чтобы включить итерации.',
+ action: 'Итеративные вычисления',
+ },
+
shortcut: {
'quick-sum': 'Быстрая сумма',
},
diff --git a/packages/sheets-formula-ui/src/locale/sk-SK.ts b/packages/sheets-formula-ui/src/locale/sk-SK.ts
index 43fea66d33..2c3b9eb2dc 100644
--- a/packages/sheets-formula-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-formula-ui/src/locale/sk-SK.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Kruhový odkaz',
+ title: 'Možnosti výpočtu',
+ enable: 'Povoliť iteratívny výpočet',
+ iterations: 'Maximálny počet iterácií (1–{0})',
+ change: 'Maximálna zmena',
+ workbook: 'Nastavenia platia pre aktuálny zošit.',
+ invalidIterations: 'Maximálny počet iterácií musí byť celé číslo od 1 do {0}.',
+ invalidChange: 'Maximálna zmena musí byť konečné kladné číslo.',
+ cancel: 'Zrušiť',
+ confirm: 'OK',
+ circular: 'Vzorec obsahuje kruhový odkaz. Otvorte možnosti výpočtu a povoľte iteratívny výpočet.',
+ action: 'Iteratívny výpočet',
+ },
+
shortcut: {
'quick-sum': 'Rýchly súčet',
},
diff --git a/packages/sheets-formula-ui/src/locale/vi-VN.ts b/packages/sheets-formula-ui/src/locale/vi-VN.ts
index a734328e86..f0aac32d3f 100644
--- a/packages/sheets-formula-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-formula-ui/src/locale/vi-VN.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: 'Tham chiếu vòng',
+ title: 'Tùy chọn tính toán',
+ enable: 'Bật tính toán lặp',
+ iterations: 'Số lần lặp tối đa (1–{0})',
+ change: 'Mức thay đổi tối đa',
+ workbook: 'Các thiết lập áp dụng cho sổ làm việc hiện tại.',
+ invalidIterations: 'Số lần lặp tối đa phải là số nguyên từ 1 đến {0}.',
+ invalidChange: 'Mức thay đổi tối đa phải là số dương hữu hạn.',
+ cancel: 'Hủy',
+ confirm: 'OK',
+ circular: 'Công thức chứa tham chiếu vòng. Mở tùy chọn tính toán để bật tính toán lặp.',
+ action: 'Tính toán lặp',
+ },
+
shortcut: {
'quick-sum': 'Tổng nhanh',
},
diff --git a/packages/sheets-formula-ui/src/locale/zh-CN.ts b/packages/sheets-formula-ui/src/locale/zh-CN.ts
index a590cf7bea..fe9ce55fc9 100644
--- a/packages/sheets-formula-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-formula-ui/src/locale/zh-CN.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: '循环引用',
+ title: '计算选项',
+ enable: '启用迭代计算',
+ iterations: '最大迭代次数(1~{0})',
+ change: '最大误差',
+ workbook: '设置应用于当前工作簿。',
+ invalidIterations: '最大迭代次数必须是 1~{0} 的整数。',
+ invalidChange: '最大误差必须是有限正数。',
+ cancel: '取消',
+ confirm: '确定',
+ circular: '此公式存在循环引用。如需使用迭代计算,请打开计算选项。',
+ action: '迭代计算',
+ },
+
shortcut: {
'quick-sum': '快速求和',
},
diff --git a/packages/sheets-formula-ui/src/locale/zh-HK.ts b/packages/sheets-formula-ui/src/locale/zh-HK.ts
index 5efb7fcd9b..dab53812f1 100644
--- a/packages/sheets-formula-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-formula-ui/src/locale/zh-HK.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: '循環參照',
+ title: '計算選項',
+ enable: '啟用反覆運算',
+ iterations: '反覆運算次數上限(1~{0})',
+ change: '最大誤差',
+ workbook: '設定套用於目前的活頁簿。',
+ invalidIterations: '反覆運算次數上限必須是 1~{0} 的整數。',
+ invalidChange: '最大誤差必須是有限正數。',
+ cancel: '取消',
+ confirm: '確定',
+ circular: '此公式存在循環參照。請開啟計算選項以啟用反覆運算。',
+ action: '反覆運算',
+ },
+
shortcut: {
'quick-sum': '快速求和',
},
diff --git a/packages/sheets-formula-ui/src/locale/zh-TW.ts b/packages/sheets-formula-ui/src/locale/zh-TW.ts
index 66d31ec1ab..6ebe59c8c2 100644
--- a/packages/sheets-formula-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-formula-ui/src/locale/zh-TW.ts
@@ -18,6 +18,21 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-formula-ui': {
+ calculation: {
+ circularTitle: '循環參照',
+ title: '計算選項',
+ enable: '啟用反覆運算',
+ iterations: '反覆運算次數上限(1~{0})',
+ change: '最大誤差',
+ workbook: '設定套用於目前的活頁簿。',
+ invalidIterations: '反覆運算次數上限必須是 1~{0} 的整數。',
+ invalidChange: '最大誤差必須是有限正數。',
+ cancel: '取消',
+ confirm: '確定',
+ circular: '此公式存在循環參照。請開啟計算選項以啟用反覆運算。',
+ action: '反覆運算',
+ },
+
shortcut: {
'quick-sum': '快速求和',
},
diff --git a/packages/sheets-formula-ui/src/menu/menu.ts b/packages/sheets-formula-ui/src/menu/menu.ts
index 30c753bbd9..adbfc1a7ab 100644
--- a/packages/sheets-formula-ui/src/menu/menu.ts
+++ b/packages/sheets-formula-ui/src/menu/menu.ts
@@ -35,6 +35,7 @@ import {
SheetCopyFormulaOnlyCommand,
SheetOnlyPasteFormulaCommand,
} from '../commands/commands/formula-clipboard.command';
+import { CalculationOptionsOperation } from '../commands/operations/calculation-options.operation';
import { InsertFunctionOperation } from '../commands/operations/insert-function.operation';
import { MoreFunctionsOperation } from '../commands/operations/more-functions.operation';
@@ -186,3 +187,13 @@ export function PasteFormulaMenuItemFactory(accessor: IAccessor): IMenuItem<Loca
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
};
}
+
+export function CalculationOptionsMenuItemFactory(accessor: IAccessor): IMenuItem<LocaleKey> {
+ return {
+ id: CalculationOptionsOperation.id,
+ type: MenuItemType.BUTTON,
+ title: 'sheets-formula-ui.calculation.title',
+ tooltip: 'sheets-formula-ui.calculation.title',
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ };
+}
diff --git a/packages/sheets-formula-ui/src/menu/schema.ts b/packages/sheets-formula-ui/src/menu/schema.ts
index a5ac5b0d31..d90b72b252 100644
--- a/packages/sheets-formula-ui/src/menu/schema.ts
+++ b/packages/sheets-formula-ui/src/menu/schema.ts
@@ -18,10 +18,12 @@ import type { MenuSchemaType } from '@univerjs/ui';
import { COPY_SPECIAL_MENU_ID, PASTE_SPECIAL_MENU_ID } from '@univerjs/sheets-ui';
import { RibbonFormulasGroup } from '@univerjs/ui';
import { SheetCopyFormulaOnlyCommand, SheetOnlyPasteFormulaCommand } from '../commands/commands/formula-clipboard.command';
+import { CalculationOptionsOperation } from '../commands/operations/calculation-options.operation';
import { InsertFunctionOperation } from '../commands/operations/insert-function.operation';
import { MoreFunctionsOperation } from '../commands/operations/more-functions.operation';
import {
AllFunctionsMenuItemFactory,
+ CalculationOptionsMenuItemFactory,
CopyFormulaOnlyMenuItemFactory,
InsertCommonFunctionMenuItemFactory,
InsertDatabaseFunctionMenuItemFactory,
@@ -89,6 +91,12 @@ export const menuSchema: MenuSchemaType = {
menuItemFactory: InsertDatabaseFunctionMenuItemFactory,
},
},
+ [RibbonFormulasGroup.OTHERS]: {
+ [CalculationOptionsOperation.id]: {
+ order: 0,
+ menuItemFactory: CalculationOptionsMenuItemFactory,
+ },
+ },
[COPY_SPECIAL_MENU_ID]: {
[SheetCopyFormulaOnlyCommand.id]: {
order: 0,
diff --git a/packages/sheets-formula-ui/src/views/calculation-options/CalculationOptions.tsx b/packages/sheets-formula-ui/src/views/calculation-options/CalculationOptions.tsx
new file mode 100644
index 0000000000..4cb2b2896e
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/calculation-options/CalculationOptions.tsx
@@ -0,0 +1,136 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Workbook } from '@univerjs/core';
+import type { LocaleKey } from '../../locale/types';
+import {
+ ICommandService,
+ IPermissionService,
+ IUniverInstanceService,
+ LocaleService,
+ MAX_ITERATION_COUNT,
+ normalizeWorkbookCalculationSettings,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { Button, Checkbox, Input } from '@univerjs/design';
+import { SetWorkbookCalculationSettingsCommand, WorkbookEditablePermission } from '@univerjs/sheets';
+import { IDialogService, useDependency, useObservable } from '@univerjs/ui';
+import { useState } from 'react';
+import { CALCULATION_OPTIONS_DIALOG } from './interface';
+
+export interface ICalculationOptionsProps {
+ unitId: string;
+}
+
+export function CalculationOptions({ unitId }: ICalculationOptionsProps) {
+ const instanceService = useDependency(IUniverInstanceService);
+ const commandService = useDependency(ICommandService);
+ const permissionService = useDependency(IPermissionService);
+ const dialogService = useDependency(IDialogService);
+ const localeService = useDependency(LocaleService);
+ const workbook = instanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const permissionId = new WorkbookEditablePermission(unitId).id;
+ const permission = useObservable(permissionService.getPermissionPoint$(permissionId), undefined, false);
+ const readOnly = !workbook || (permission?.value ?? permissionService.getPermissionPoint(permissionId)?.value) === false;
+ const [draft, setDraft] = useState(() => {
+ const settings = normalizeWorkbookCalculationSettings(workbook?.getCalculationSettings());
+ return {
+ enabled: settings.iterativeCalculation,
+ count: String(settings.maxIterations),
+ change: String(settings.maxChange),
+ };
+ });
+ const [submitted, setSubmitted] = useState(false);
+ const settings = {
+ iterativeCalculation: draft.enabled,
+ maxIterations: draft.count.trim() ? Number(draft.count) : NaN,
+ maxChange: draft.change.trim() ? Number(draft.change) : NaN,
+ };
+ const validCount = Number.isInteger(settings.maxIterations) && settings.maxIterations >= 1 &&
+ settings.maxIterations <= MAX_ITERATION_COUNT;
+ const validChange = Number.isFinite(settings.maxChange) && settings.maxChange > 0;
+ const showCountError = submitted && draft.enabled && !validCount;
+ const showChangeError = submitted && draft.enabled && !validChange;
+
+ function close() {
+ dialogService.close(CALCULATION_OPTIONS_DIALOG);
+ }
+
+ function submit() {
+ if (readOnly) {
+ return;
+ }
+ setSubmitted(true);
+ if (draft.enabled && (!validCount || !validChange)) {
+ return;
+ }
+ const nextSettings = draft.enabled
+ ? settings
+ : { ...workbook!.getCalculationSettings(), iterativeCalculation: false };
+ if (commandService.syncExecuteCommand(SetWorkbookCalculationSettingsCommand.id, { unitId, settings: nextSettings })) {
+ close();
+ }
+ }
+
+ return (
+ <div className="univer-flex univer-flex-col univer-gap-4 univer-p-4">
+ <p className="univer-m-0 univer-text-sm">
+ {localeService.t<LocaleKey>('sheets-formula-ui.calculation.workbook')}
+ </p>
+ <Checkbox
+ checked={draft.enabled}
+ disabled={readOnly}
+ onChange={(enabled) => setDraft((previous) => ({ ...previous, enabled: Boolean(enabled) }))}
+ >
+ {localeService.t<LocaleKey>('sheets-formula-ui.calculation.enable')}
+ </Checkbox>
+ <label className="univer-flex univer-flex-col univer-gap-2 univer-text-sm">
+ {localeService.t<LocaleKey>('sheets-formula-ui.calculation.iterations', String(MAX_ITERATION_COUNT))}
+ <Input
+ value={draft.count}
+ inputClass={showCountError ? 'univer-border-red-500' : undefined}
+ disabled={readOnly || !draft.enabled}
+ onChange={(count) => setDraft((previous) => ({ ...previous, count }))}
+ />
+ {showCountError && (
+ <span role="alert" className="univer-text-red-500">
+ {localeService.t<LocaleKey>('sheets-formula-ui.calculation.invalidIterations', String(MAX_ITERATION_COUNT))}
+ </span>
+ )}
+ </label>
+ <label className="univer-flex univer-flex-col univer-gap-2 univer-text-sm">
+ {localeService.t<LocaleKey>('sheets-formula-ui.calculation.change')}
+ <Input
+ value={draft.change}
+ inputClass={showChangeError ? 'univer-border-red-500' : undefined}
+ disabled={readOnly || !draft.enabled}
+ onChange={(change) => setDraft((previous) => ({ ...previous, change }))}
+ />
+ {showChangeError && (
+ <span role="alert" className="univer-text-red-500">
+ {localeService.t<LocaleKey>('sheets-formula-ui.calculation.invalidChange')}
+ </span>
+ )}
+ </label>
+ <div className="univer-flex univer-justify-end univer-gap-2">
+ <Button onClick={close}>{localeService.t<LocaleKey>('sheets-formula-ui.calculation.cancel')}</Button>
+ <Button variant="primary" disabled={readOnly} onClick={submit}>
+ {localeService.t<LocaleKey>('sheets-formula-ui.calculation.confirm')}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/sheets-formula-ui/src/views/calculation-options/__tests__/CalculationOptions.spec.tsx b/packages/sheets-formula-ui/src/views/calculation-options/__tests__/CalculationOptions.spec.tsx
new file mode 100644
index 0000000000..b1061b1927
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/calculation-options/__tests__/CalculationOptions.spec.tsx
@@ -0,0 +1,177 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IWorkbookCalculationSettings } from '@univerjs/core';
+import type { Root } from 'react-dom/client';
+import {
+ ICommandService,
+ Injector,
+ IPermissionService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ MAX_ITERATION_COUNT,
+} from '@univerjs/core';
+import { SetWorkbookCalculationSettingsCommand } from '@univerjs/sheets';
+import { IDialogService, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { of } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { CalculationOptions } from '../CalculationOptions';
+import { CALCULATION_OPTIONS_DIALOG } from '../interface';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('CalculationOptions', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let injector: Injector;
+ let settings: IWorkbookCalculationSettings;
+ const execute = vi.fn();
+ const close = vi.fn();
+
+ beforeEach(() => {
+ execute.mockReset().mockReturnValue(true);
+ close.mockReset();
+ settings = { iterativeCalculation: true, maxIterations: 100, maxChange: 0.001 };
+ injector = new Injector();
+ injector.add([LocaleService]);
+ const locale = injector.get(LocaleService);
+ locale.load({ [LocaleType.EN_US]: enUS });
+ locale.setLocale(LocaleType.EN_US);
+ locale.setDirection('ltr');
+ injector.add([IUniverInstanceService, { useValue: {
+ getUnit: () => ({ getCalculationSettings: () => settings }),
+ } as never }]);
+ injector.add([ICommandService, { useValue: { syncExecuteCommand: execute } as never }]);
+ const editablePermission$ = of({ value: true });
+ injector.add([IPermissionService, { useValue: {
+ getPermissionPoint$: () => editablePermission$,
+ getPermissionPoint: () => ({ value: true }),
+ } as never }]);
+ injector.add([IDialogService, { useValue: { close } as never }]);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => root.render(
+ <RediContext.Provider value={{ injector }}>
+ <CalculationOptions unitId="u" />
+ </RediContext.Provider>
+ ));
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ injector.dispose();
+ });
+
+ function edit(index: number, value: string) {
+ const input = container.querySelectorAll<HTMLInputElement>('input[type="text"]')[index];
+ act(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ }
+
+ function confirm() {
+ const button = Array.from(container.querySelectorAll('button')).find((node) => node.textContent === 'OK')!;
+ act(() => button.click());
+ }
+
+ it.each(['', ' ', '0', '-1', '1.5', String(MAX_ITERATION_COUNT + 1), 'Infinity', 'abc'])(
+ 'keeps invalid iteration count %j open without updating settings',
+ (value) => {
+ edit(0, value);
+ confirm();
+ expect(execute).not.toHaveBeenCalled();
+ expect(close).not.toHaveBeenCalled();
+ const alerts = container.querySelectorAll('[role="alert"]');
+ expect(alerts).toHaveLength(1);
+ expect(alerts[0].textContent).toContain('Maximum iterations');
+ expect(alerts[0].textContent).toContain(String(MAX_ITERATION_COUNT));
+ expect(alerts[0].closest('label')?.querySelector('input')?.value).toBe(value);
+ }
+ );
+
+ it.each(['', ' ', '0', '-0.1', 'Infinity', '1e309', 'abc'])(
+ 'keeps invalid maximum change %j open without updating settings',
+ (value) => {
+ edit(1, value);
+ confirm();
+ expect(execute).not.toHaveBeenCalled();
+ expect(close).not.toHaveBeenCalled();
+ const alerts = container.querySelectorAll('[role="alert"]');
+ expect(alerts).toHaveLength(1);
+ expect(alerts[0].textContent).toContain('Maximum change');
+ expect(alerts[0].closest('label')?.querySelector('input')?.value).toBe(value);
+ }
+ );
+
+ it.each([1, MAX_ITERATION_COUNT])('saves valid boundaries and closes only after success: %i', (count) => {
+ edit(0, String(count));
+ edit(1, '1e-6');
+ confirm();
+ expect(execute).toHaveBeenCalledWith(SetWorkbookCalculationSettingsCommand.id, {
+ unitId: 'u',
+ settings: { iterativeCalculation: true, maxIterations: count, maxChange: 0.000001 },
+ });
+ expect(close).toHaveBeenCalledWith(CALCULATION_OPTIONS_DIALOG);
+ });
+
+ it('allows correcting invalid input and does not close when the command fails', () => {
+ edit(0, '0');
+ confirm();
+ edit(0, '20');
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ execute.mockReturnValueOnce(false);
+ confirm();
+ expect(close).not.toHaveBeenCalled();
+ confirm();
+ expect(close).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows both field errors and removes only the corrected field error', () => {
+ edit(0, '1.5');
+ edit(1, '0');
+ confirm();
+ expect(container.querySelectorAll('[role="alert"]')).toHaveLength(2);
+ expect(execute).not.toHaveBeenCalled();
+ expect(close).not.toHaveBeenCalled();
+
+ edit(0, '100');
+ const alerts = container.querySelectorAll('[role="alert"]');
+ expect(alerts).toHaveLength(1);
+ expect(alerts[0].textContent).toContain('Maximum change');
+ edit(1, '0.001');
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ });
+
+ it('allows disabling iteration after an invalid draft while preserving saved numeric settings', () => {
+ edit(0, '0');
+ edit(1, '');
+ confirm();
+ act(() => container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click());
+ confirm();
+ expect(execute).toHaveBeenCalledWith(SetWorkbookCalculationSettingsCommand.id, {
+ unitId: 'u',
+ settings: { ...settings, iterativeCalculation: false },
+ });
+ expect(close).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/calculation-options/interface.ts b/packages/sheets-formula-ui/src/views/calculation-options/interface.ts
new file mode 100644
index 0000000000..f92571a57e
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/calculation-options/interface.ts
@@ -0,0 +1,18 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const CALCULATION_OPTIONS_COMPONENT = 'sheets-formula-ui.calculation-options';
+export const CALCULATION_OPTIONS_DIALOG = 'sheets-formula-ui.calculation-options-dialog';
diff --git a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
index f387196f44..88e61522b0 100644
--- a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts
@@ -14,17 +14,18 @@
* limitations under the License.
*/
-import type { Dependency, IWorkbookData } from '@univerjs/core';
+import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
import type { IExecutionInProgressParams } from '@univerjs/engine-formula';
import {
CommandType,
ICommandService,
IConfigService,
+ IUniverInstanceService,
LocaleType,
+ UniverInstanceType,
} from '@univerjs/core';
import {
ActiveDirtyManagerService,
- ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,
ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,
FormulaCalculationSessionController,
FormulaCalculationSessionService,
@@ -89,7 +90,7 @@ function createControllerTestBed(initialFormulaComputing = CalculationMode.WHEN_
configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { initialFormulaComputing }, { merge: true });
configService.setConfig(ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, true);
- configService.setConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, 7);
+ injector.get(IUniverInstanceService).getUnit<Workbook>('test', UniverInstanceType.UNIVER_SHEET)!.setCalculationSettings({ iterativeCalculation: true, maxIterations: 7, maxChange: 0.001 });
[
SetTriggerFormulaCalculationStartMutation,
@@ -171,14 +172,14 @@ describe('TriggerCalculationController', () => {
id: SetFormulaCalculationStartMutation.id,
params: expect.objectContaining({
isCalculateTreeModel: true,
- maxIteration: 7,
+ calculationSettings: { test: { iterativeCalculation: true, maxIterations: 7, maxChange: 0.001 } },
rowData: testBed.formulaDataModel.getHiddenRowsFiltered(),
}),
});
expect(testBed.executedCommands.find((command) => command.id === SetFormulaStringBatchCalculationMutation.id)).toMatchObject({
id: SetFormulaStringBatchCalculationMutation.id,
params: expect.objectContaining({
- maxIteration: 7,
+ calculationSettings: { test: { iterativeCalculation: true, maxIterations: 7, maxChange: 0.001 } },
rowData: testBed.formulaDataModel.getHiddenRowsFiltered(),
}),
});
diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
index 2f50db97f5..f85fdb6edd 100644
--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts
+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
@@ -56,6 +56,7 @@ import {
SetRowHiddenMutation,
SetRowVisibleMutation,
SetStyleCommand,
+ SetWorkbookCalculationSettingsMutation,
} from '@univerjs/sheets';
export class ActiveDirtyController extends Disposable {
@@ -91,6 +92,21 @@ export class ActiveDirtyController extends Disposable {
},
});
+ this._activeDirtyManagerService.register(SetWorkbookCalculationSettingsMutation.id, {
+ commandId: SetWorkbookCalculationSettingsMutation.id,
+ getDirtyData: (command: ICommandInfo) => {
+ const { unitId } = command.params as { unitId: string };
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ return {
+ dirtyRanges: workbook?.getSheets().map((sheet) => ({
+ unitId,
+ sheetId: sheet.getSheetId(),
+ range: { startRow: 0, startColumn: 0, endRow: sheet.getRowCount() - 1, endColumn: sheet.getColumnCount() - 1 },
+ })) ?? [],
+ };
+ },
+ });
+
this._initialMove();
this._initialRowAndColumn();
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index 2e2d81d889..88c1b1690d 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -29,7 +29,6 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import {
- ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,
ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,
FormulaDataModel,
FormulaExecutedStateType,
@@ -161,7 +160,10 @@ export class TriggerCalculationController extends Disposable {
params.isCalculateTreeModel = isCalculateTreeModel;
}
- params.maxIteration = this._configService.getConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT) as number | undefined;
+ params.calculationSettings = Object.fromEntries(
+ this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET)
+ .map((workbook) => [workbook.getUnitId(), workbook.getCalculationSettings()])
+ );
params.rowData = this._formulaDataModel.getHiddenRowsFiltered();
}
})
@@ -187,6 +189,9 @@ export class TriggerCalculationController extends Disposable {
}
const params = command.params as ISetFormulaCalculationNotificationMutation;
+ if (params.circularReferences) {
+ this._formulaDataModel.setCircularReferences(params.circularReferences);
+ }
if (params.stageInfo != null) {
const {
diff --git a/packages/sheets-formula/src/facade/f-workbook.ts b/packages/sheets-formula/src/facade/f-workbook.ts
index 8d7ad4187b..c2c3afd78b 100644
--- a/packages/sheets-formula/src/facade/f-workbook.ts
+++ b/packages/sheets-formula/src/facade/f-workbook.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ISheetFormulaError } from '@univerjs/engine-formula';
+import type { ICircularReference, ISheetFormulaError } from '@univerjs/engine-formula';
import { extractFormulaError, FormulaDataModel } from '@univerjs/engine-formula';
import { FWorkbook } from '@univerjs/sheets/facade';
@@ -33,6 +33,23 @@ export interface IFWorkbookEngineFormulaMixin {
* ```
*/
getAllFormulaError(): ISheetFormulaError[];
+
+ /**
+ * Get recorded circular-reference diagnostics for the workbook.
+ * Diagnostics are updated when formula calculation results are applied; this method does not trigger calculation.
+ * Row and column indices are zero-based. Convergence status is included when available.
+ * @returns {ICircularReference[]} Circular-reference cells with worksheet coordinates, group IDs and iteration counts.
+ * Returns an empty array if no circular references have been recorded.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const circularReferences = fWorkbook.getCircularReferences();
+ * circularReferences.forEach(({ sheetId, row, column, groupId, iterations, converged }) => {
+ * console.log({ sheetId, row, column, groupId, iterations, converged });
+ * });
+ * ```
+ */
+ getCircularReferences(): ICircularReference[];
}
export class FWorkbookEngineFormulaMixin extends FWorkbook implements IFWorkbookEngineFormulaMixin {
@@ -73,6 +90,10 @@ export class FWorkbookEngineFormulaMixin extends FWorkbook implements IFWorkbook
return errors;
}
+
+ override getCircularReferences(): ICircularReference[] {
+ return this._injector.get(FormulaDataModel).getCircularReferences(this._workbook.getUnitId());
+ }
}
FWorkbook.extend(FWorkbookEngineFormulaMixin);
diff --git a/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts
index 33ec6c007f..a5220bad81 100644
--- a/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts
@@ -14,8 +14,11 @@
* limitations under the License.
*/
-import { describe, expect, it, vi } from 'vitest';
+import { Injector } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CellAlertManagerService, CellAlertType } from '../cell-alert-manager.service';
+import { CellPopupManagerService } from '../cell-popup-manager.service';
function createAlert(key: string) {
return {
@@ -35,6 +38,15 @@ function createAlert(key: string) {
}
describe('CellAlertManagerService', () => {
+ let injector: Injector;
+
+ beforeEach(() => {
+ injector = new Injector();
+ injector.add([CellAlertManagerService]);
+ });
+
+ afterEach(() => injector.dispose());
+
it('adds/replaces/removes alerts and emits current list', () => {
const oldPopupDispose = { dispose: vi.fn() };
const newPopupDispose = { dispose: vi.fn() };
@@ -42,10 +54,9 @@ describe('CellAlertManagerService', () => {
.fn()
.mockReturnValueOnce(oldPopupDispose)
.mockReturnValueOnce(newPopupDispose);
- const service = new CellAlertManagerService(
- { getRenderUnitById: vi.fn(() => ({ id: 'render' })) } as never,
- { showPopup } as never
- );
+ injector.add([IRenderManagerService, { useValue: { getRenderUnitById: vi.fn(() => ({ id: 'render' })) } as never }]);
+ injector.add([CellPopupManagerService, { useValue: { showPopup } as never }]);
+ const service = injector.get(CellAlertManagerService);
const emitted: Array<Array<[string, unknown]>> = [];
service.currentAlert$.subscribe((value) => emitted.push(value));
@@ -65,9 +76,11 @@ describe('CellAlertManagerService', () => {
expect(service.currentAlert.size).toBe(1);
expect(emitted.at(-1)?.map(([key]) => key)).toEqual(['alert-1']);
- service.showAlert({ ...first, message: 'updated' } as never);
- expect(oldPopupDispose.dispose).toHaveBeenCalled();
- expect(service.currentAlert.get('alert-1')?.alert.message).toBe('message');
+ const updated = { ...first, message: 'updated' };
+ service.showAlert(updated);
+ expect(oldPopupDispose.dispose).toHaveBeenCalledTimes(1);
+ expect(service.currentAlert.get('alert-1')?.alert.message).toBe('updated');
+ expect(showPopup).toHaveBeenLastCalledWith(updated.location, expect.objectContaining({ extraProps: { alert: updated } }));
expect(emitted.at(-1)?.map(([key]) => key)).toEqual(['alert-1']);
service.removeAlert('alert-1');
@@ -84,7 +97,9 @@ describe('CellAlertManagerService', () => {
const renderManager = {
getRenderUnitById: vi.fn(() => currentRender),
};
- const service = new CellAlertManagerService(renderManager as never, { showPopup } as never);
+ injector.add([IRenderManagerService, { useValue: renderManager as never }]);
+ injector.add([CellPopupManagerService, { useValue: { showPopup } as never }]);
+ const service = injector.get(CellAlertManagerService);
service.showAlert(createAlert('a') as never);
service.showAlert(createAlert('b') as never);
@@ -105,10 +120,9 @@ describe('CellAlertManagerService', () => {
it('anchors actionable alerts to the left of the cell', () => {
const showPopup = vi.fn(() => ({ dispose: vi.fn() }));
- const service = new CellAlertManagerService(
- { getRenderUnitById: vi.fn(() => ({ id: 'render' })) } as never,
- { showPopup } as never
- );
+ injector.add([IRenderManagerService, { useValue: { getRenderUnitById: vi.fn(() => ({ id: 'render' })) } as never }]);
+ injector.add([CellPopupManagerService, { useValue: { showPopup } as never }]);
+ const service = injector.get(CellAlertManagerService);
const alert = {
...createAlert('action-alert'),
menu: [{ label: 'Text to Number', onSelect: vi.fn() }],
diff --git a/packages/sheets-ui/src/services/cell-alert-manager.service.ts b/packages/sheets-ui/src/services/cell-alert-manager.service.ts
index 3f9b70b2a1..76cd217374 100644
--- a/packages/sheets-ui/src/services/cell-alert-manager.service.ts
+++ b/packages/sheets-ui/src/services/cell-alert-manager.service.ts
@@ -44,6 +44,7 @@ export interface ICellAlert {
height: number;
key: string;
menu?: ICellAlertMenuItem[];
+ action?: ICellAlertMenuItem;
}
export class CellAlertManagerService extends Disposable {
@@ -63,6 +64,7 @@ export class CellAlertManagerService extends Disposable {
super();
this.disposeWithMe(() => {
+ this.clearAlert();
this._currentAlert$.complete();
});
}
@@ -71,9 +73,7 @@ export class CellAlertManagerService extends Disposable {
let lastPopup = this._currentAlert.get(alert.key);
if (lastPopup) {
lastPopup.dispose.dispose();
- };
- if (lastPopup) {
- lastPopup.dispose.dispose();
+ lastPopup.alert = alert;
} else {
lastPopup = {
alert,
@@ -113,9 +113,6 @@ export class CellAlertManagerService extends Disposable {
}
);
if (disposable) {
- if (lastPopup) {
- lastPopup.dispose?.dispose();
- }
lastPopup.dispose = disposable;
}
diff --git a/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx b/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
index c20033f7af..5940ef2900 100644
--- a/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
+++ b/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
@@ -16,7 +16,7 @@
import type { ICanvasPopup } from '../../services/canvas-pop-manager.service';
import type { ICellAlert } from '../../services/cell-alert-manager.service';
-import { DropdownMenu } from '@univerjs/design';
+import { Button, DropdownMenu } from '@univerjs/design';
import { ErrorIcon, InfoIcon, MoreDownIcon, WarningIcon } from '@univerjs/icons';
import { useState } from 'react';
import { CellAlertType } from '../../services/cell-alert-manager.service';
@@ -39,7 +39,7 @@ export function CellAlert({ popup, DropdownMenuComponent = DropdownMenu }: ICell
if (!alert) {
return null;
}
- const { type, title, message, menu } = alert as ICellAlert;
+ const { type, title, message, menu, action, width } = alert as ICellAlert;
if (menu?.length) {
const accessibleLabel = [title, message]
@@ -110,9 +110,10 @@ export function CellAlert({ popup, DropdownMenuComponent = DropdownMenu }: ICell
return (
<div
+ style={{ width }}
className={`
- univer-z-[100] univer-box-border univer-w-[156px] univer-rounded-lg univer-bg-gray-0 univer-px-2
- univer-py-1 univer-text-gray-900 univer-shadow
+ univer-z-[100] univer-box-border univer-rounded-lg univer-bg-gray-0 univer-px-2 univer-py-1
+ univer-text-gray-900 univer-shadow
dark:!univer-bg-gray-1000 dark:!univer-text-gray-0
`}
>
@@ -126,6 +127,11 @@ export function CellAlert({ popup, DropdownMenuComponent = DropdownMenu }: ICell
{title}
</div>
<div className="univer-text-sm">{message}</div>
+ {action && (
+ <Button className="univer-mt-2" disabled={action.disabled} onClick={action.onSelect}>
+ {action.label}
+ </Button>
+ )}
</div>
);
}
diff --git a/packages/sheets/src/commands/commands/set-workbook-calculation-settings.command.ts b/packages/sheets/src/commands/commands/set-workbook-calculation-settings.command.ts
new file mode 100644
index 0000000000..45bfd2cb16
--- /dev/null
+++ b/packages/sheets/src/commands/commands/set-workbook-calculation-settings.command.ts
@@ -0,0 +1,72 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import type { ISetWorkbookCalculationSettingsMutationParams } from '../mutations/set-workbook-calculation-settings.mutation';
+import {
+ CommandType,
+ ICommandService,
+ IPermissionService,
+ IUndoRedoService,
+ IUniverInstanceService,
+} from '@univerjs/core';
+import { WorkbookEditablePermission } from '../../services/permission/permission-point/workbook/editable';
+import { SetWorkbookCalculationSettingsMutation } from '../mutations/set-workbook-calculation-settings.mutation';
+import { getSheetCommandTargetWorkbook } from './utils/target-util';
+
+export const SetWorkbookCalculationSettingsCommand: ICommand<ISetWorkbookCalculationSettingsMutationParams> = {
+ id: 'sheet.command.set-workbook-calculation-settings',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const target = getSheetCommandTargetWorkbook(accessor.get(IUniverInstanceService), params);
+ if (!target) {
+ return false;
+ }
+
+ const permission = accessor.get(IPermissionService).getPermissionPoint(
+ new WorkbookEditablePermission(params.unitId).id
+ );
+ if (permission && !permission.value) {
+ return false;
+ }
+
+ const undoParams = {
+ unitId: params.unitId,
+ settings: target.workbook.getCalculationSettings(),
+ };
+ const redoParams = {
+ unitId: params.unitId,
+ settings: { ...params.settings },
+ };
+
+ const result = accessor.get(ICommandService).syncExecuteCommand<ISetWorkbookCalculationSettingsMutationParams>(SetWorkbookCalculationSettingsMutation.id, redoParams);
+
+ if (result) {
+ accessor.get(IUndoRedoService).pushUndoRedo({
+ unitID: params.unitId,
+ undoMutations: [{ id: SetWorkbookCalculationSettingsMutation.id, params: undoParams }],
+ redoMutations: [{ id: SetWorkbookCalculationSettingsMutation.id, params: redoParams }],
+ });
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets/src/commands/mutations/set-workbook-calculation-settings.mutation.ts b/packages/sheets/src/commands/mutations/set-workbook-calculation-settings.mutation.ts
new file mode 100644
index 0000000000..11a2ebf2c4
--- /dev/null
+++ b/packages/sheets/src/commands/mutations/set-workbook-calculation-settings.mutation.ts
@@ -0,0 +1,39 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IMutation, IWorkbookCalculationSettings, Workbook } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+
+export interface ISetWorkbookCalculationSettingsMutationParams {
+ unitId: string;
+ settings: IWorkbookCalculationSettings;
+}
+
+export const SetWorkbookCalculationSettingsMutation: IMutation<ISetWorkbookCalculationSettingsMutationParams> = {
+ id: 'sheet.mutation.set-workbook-calculation-settings',
+ type: CommandType.MUTATION,
+ handler: (accessor, params) => {
+ const workbook = accessor.get(IUniverInstanceService).getUnit<Workbook>(
+ params.unitId,
+ UniverInstanceType.UNIVER_SHEET
+ );
+ if (!workbook) {
+ return false;
+ }
+ workbook.setCalculationSettings(params.settings);
+ return true;
+ },
+};
diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.ts
index 5b7051bea4..b40acf3b7b 100644
--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts
+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts
@@ -97,6 +97,7 @@ import {
SetVerticalTextAlignCommand,
} from '../commands/commands/set-style.command';
import { SetTabColorCommand } from '../commands/commands/set-tab-color.command';
+import { SetWorkbookCalculationSettingsCommand } from '../commands/commands/set-workbook-calculation-settings.command';
import { SetWorkbookNameCommand } from '../commands/commands/set-workbook-name.command';
import { SetWorksheetActivateCommand } from '../commands/commands/set-worksheet-activate.command';
import { DeltaColumnWidthCommand, SetColWidthCommand } from '../commands/commands/set-worksheet-col-width.command';
@@ -151,6 +152,7 @@ import { SetRangeValuesMutation } from '../commands/mutations/set-range-values.m
import { SetRowDataMutation } from '../commands/mutations/set-row-data.mutation';
import { SetRowHiddenMutation, SetRowVisibleMutation } from '../commands/mutations/set-row-visible.mutation';
import { SetTabColorMutation } from '../commands/mutations/set-tab-color.mutation';
+import { SetWorkbookCalculationSettingsMutation } from '../commands/mutations/set-workbook-calculation-settings.mutation';
import { SetWorkbookNameMutation } from '../commands/mutations/set-workbook-name.mutation';
import { SetWorksheetColWidthMutation } from '../commands/mutations/set-worksheet-col-width.mutation';
import { SetWorksheetColumnCountMutation } from '../commands/mutations/set-worksheet-column-count.mutation';
@@ -211,6 +213,7 @@ export class BasicWorksheetController extends Disposable implements IDisposable
RemoveWorksheetMergeMutation,
RemoveNumfmtMutation,
AddWorksheetMergeMutation,
+ SetWorkbookCalculationSettingsMutation,
SetWorkbookNameMutation,
SetWorksheetNameMutation,
SetNumfmtMutation,
@@ -313,6 +316,7 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetTextRotationCommand,
SetTextWrapCommand,
SetVerticalTextAlignCommand,
+ SetWorkbookCalculationSettingsCommand,
SetWorkbookNameCommand,
SetWorksheetActivateCommand,
SetWorksheetActiveOperation,
diff --git a/packages/sheets/src/facade/f-workbook.ts b/packages/sheets/src/facade/f-workbook.ts
index af907951ab..bfb3bdb260 100644
--- a/packages/sheets/src/facade/f-workbook.ts
+++ b/packages/sheets/src/facade/f-workbook.ts
@@ -21,6 +21,7 @@ import type {
IDisposable,
IRange,
IStyleData,
+ IWorkbookCalculationSettings,
IWorkbookData,
IWorksheetData,
Workbook,
@@ -54,6 +55,7 @@ import {
RemoveSheetCommand,
SetDefinedNameCommand,
SetSelectionsOperation,
+ SetWorkbookCalculationSettingsCommand,
SetWorkbookNameCommand,
SetWorksheetActiveOperation,
SetWorksheetOrderCommand,
@@ -1159,4 +1161,43 @@ export class FWorkbook extends FBaseInitialable {
removeStyles(styleKeys: string[]): void {
this._workbook.removeStyles(styleKeys);
}
+
+ /**
+ * Get the workbook's iterative calculation settings.
+ * Missing or invalid settings use the defaults: iteration disabled, 100 iterations and a maximum change of 0.001.
+ * @returns {IWorkbookCalculationSettings} A copy of the normalized workbook calculation settings.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const settings = fWorkbook.getCalculationSettings();
+ * console.log(settings.iterativeCalculation, settings.maxIterations, settings.maxChange);
+ * ```
+ */
+ getCalculationSettings(): IWorkbookCalculationSettings {
+ return this._workbook.getCalculationSettings();
+ }
+
+ /**
+ * Set iterative calculation settings for the entire workbook through an undoable command.
+ * @param {IWorkbookCalculationSettings} settings The complete calculation settings.
+ * Set `iterativeCalculation` to enable or disable iterative evaluation of circular references.
+ * `maxIterations` must be an integer from 1 to 32767, and `maxChange` must be a finite positive number.
+ * @returns {boolean} Whether the settings command succeeded. Returns false if the workbook cannot be edited or found.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const success = fWorkbook.setCalculationSettings({
+ * iterativeCalculation: true,
+ * maxIterations: 100,
+ * maxChange: 0.001,
+ * });
+ * console.log('Calculation settings updated:', success);
+ * ```
+ */
+ setCalculationSettings(settings: IWorkbookCalculationSettings): boolean {
+ return this._commandService.syncExecuteCommand(SetWorkbookCalculationSettingsCommand.id, {
+ unitId: this.id,
+ settings,
+ });
+ }
}
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index 6b4f7a9cd2..f06e593cad 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -244,6 +244,7 @@ export type {
IStyleTypeValue,
} from './commands/commands/set-style.command';
export { SetTabColorCommand } from './commands/commands/set-tab-color.command';
+export { SetWorkbookCalculationSettingsCommand } from './commands/commands/set-workbook-calculation-settings.command';
export { SetWorkbookNameCommand } from './commands/commands/set-workbook-name.command';
export type { ISetWorkbookNameCommandParams } from './commands/commands/set-workbook-name.command';
export { SetWorksheetActivateCommand } from './commands/commands/set-worksheet-activate.command';
@@ -412,6 +413,8 @@ export type {
} from './commands/mutations/set-row-visible.mutation';
export { SetTabColorMutation } from './commands/mutations/set-tab-color.mutation';
export type { ISetTabColorMutationParams } from './commands/mutations/set-tab-color.mutation';
+export { SetWorkbookCalculationSettingsMutation } from './commands/mutations/set-workbook-calculation-settings.mutation';
+export type { ISetWorkbookCalculationSettingsMutationParams } from './commands/mutations/set-workbook-calculation-settings.mutation';
export { SetWorkbookNameMutation } from './commands/mutations/set-workbook-name.mutation';
export type { ISetWorkbookNameMutationParams } from './commands/mutations/set-workbook-name.mutation';
export {