Skip to content

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

feat(formula): report formula error message, check params number by minParams and maxParams (#1876)

Dushusir88f517be0411
diff --git a/packages/engine-formula/src/engine/ast-node/function-node.ts b/packages/engine-formula/src/engine/ast-node/function-node.ts
index 408f6c75a0..2d8ff084fd 100644
--- a/packages/engine-formula/src/engine/ast-node/function-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/function-node.ts
@@ -31,7 +31,7 @@ import type {
NodeValueType,
} from '../reference-object/base-reference-object';
import { ArrayValueObject, transformToValueObject, ValueObjectFactory } from '../value-object/array-value-object';
-import type { BaseValueObject } from '../value-object/base-value-object';
+import { type BaseValueObject, ErrorValueObject } from '../value-object/base-value-object';
import { prefixHandler } from '../utils/prefixHandler';
import { IDefinedNamesService } from '../../services/defined-names.service';
import { BaseAstNode, ErrorNode } from './base-ast-node';
@@ -178,6 +178,12 @@ export class FunctionNode extends BaseAstNode {
}
private _calculate(variants: BaseValueObject[]) {
+ // Check the number of parameters
+ const { minParams, maxParams } = this._functionExecutor;
+ if (minParams !== -1 && maxParams !== -1 && (variants.length < minParams || variants.length > maxParams)) {
+ return ErrorValueObject.create(ErrorType.NA);
+ }
+
let resultVariant: NodeValueType;
this._setRefInfo();
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 02fb99006c..ed46bb298b 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -154,6 +154,13 @@ export class FormulaDependencyGenerator extends Disposable {
const treeList: FormulaDependencyTree[] = [];
+ // Recalculation can only be triggered after clearing the cache. For example, if a calculation error is reported for a non-existent formula and a custom formula is registered later, all formulas need to be calculated forcibly.
+ const forceCalculate = this._currentConfigService.isForceCalculate();
+ if (forceCalculate) {
+ this._dependencyManagerService.reset();
+ FormulaASTCache.clear();
+ }
+
this._registerFormulas(formulaDataKeys, formulaData, unitData, treeList);
diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.ts
index b9b870eb82..f86eaba9fe 100644
--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts
+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts
@@ -391,14 +391,15 @@ export const NumberValueObjectCache = new FormulaAstLRU<NumberValueObject>(NUMBE
export class NumberValueObject extends BaseValueObject {
private _value: number = 0;
- static create(value: number, pattern: string = '') {
- const key = `${value}-${pattern}`;
+ static create(value: number) {
+ const key = `${value}`;
const cached = NumberValueObjectCache.get(key);
if (cached) {
+ // The NumberValueObject may be cached with a number format, but the next time the cache is retrieved, the number format is not required.
+ cached.setPattern('');
return cached;
}
const instance = new NumberValueObject(value);
- instance.setPattern(pattern);
NumberValueObjectCache.set(key, instance);
return instance;
}
diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.ts
index a5a819e718..d9b556a2ce 100644
--- a/packages/engine-formula/src/functions/base-function.ts
+++ b/packages/engine-formula/src/functions/base-function.ts
@@ -53,6 +53,16 @@ export class BaseFunction extends Disposable {
*/
needsReferenceObject: boolean = false;
+ /**
+ * Minimum number of parameters
+ */
+ minParams: number = -1;
+
+ /**
+ * Maximum number of parameters
+ */
+ maxParams: number = -1;
+
constructor(private _name: IFunctionNames) {
super();
}
diff --git a/packages/engine-formula/src/functions/math/sumif/index.ts b/packages/engine-formula/src/functions/math/sumif/index.ts
index 66df1355d0..b4e79fa7c6 100644
--- a/packages/engine-formula/src/functions/math/sumif/index.ts
+++ b/packages/engine-formula/src/functions/math/sumif/index.ts
@@ -21,11 +21,11 @@ import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-ob
import { BaseFunction } from '../../base-function';
export class Sumif extends BaseFunction {
- override calculate(range: BaseValueObject, criteria: BaseValueObject, sumRange?: BaseValueObject) {
- if (range == null || criteria == null) {
- return ErrorValueObject.create(ErrorType.NA);
- }
+ override minParams = 2;
+ override maxParams = 3;
+
+ override calculate(range: BaseValueObject, criteria: BaseValueObject, sumRange?: BaseValueObject) {
if (range.isError() || criteria.isError() || sumRange?.isError()) {
return ErrorValueObject.create(ErrorType.NA);
}
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index 7c52a7dc2f..bd789181b0 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -50,6 +50,8 @@ export class FormulaDataModel extends Disposable {
@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder
) {
super();
+
+ this.initFormulaData();
}
clearPreviousArrayFormulaCellData(clearArrayFormulaCellData: IRuntimeUnitDataType) {
@@ -255,6 +257,10 @@ export class FormulaDataModel extends Disposable {
}
}
+ /**
+ * Cache all formulas on the snapshot to the formula model
+ * @returns
+ */
initFormulaData() {
// Load formula data from workbook config data.
const allSheets = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
diff --git a/packages/engine-formula/src/services/function.service.ts b/packages/engine-formula/src/services/function.service.ts
index 3f53436873..804cfd959b 100644
--- a/packages/engine-formula/src/services/function.service.ts
+++ b/packages/engine-formula/src/services/function.service.ts
@@ -15,7 +15,8 @@
*/
import type { Nullable } from '@univerjs/core';
-import { Disposable } from '@univerjs/core';
+import { Disposable, toDisposable } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier } from '@wendellhu/redi';
import type { IFunctionInfo, IFunctionNames } from '../basics/function';
@@ -45,7 +46,7 @@ export interface IFunctionService {
unregisterExecutors(...functionTokens: IFunctionNames[]): void;
- registerDescriptions(...functions: IFunctionInfo[]): void;
+ registerDescriptions(...functions: IFunctionInfo[]): IDisposable;
getDescriptions(): Map<IFunctionNames, IFunctionInfo>;
@@ -92,11 +93,18 @@ export class FunctionService extends Disposable implements IFunctionService {
}
}
- registerDescriptions(...descriptions: IFunctionInfo[]) {
+ registerDescriptions(...descriptions: IFunctionInfo[]): IDisposable {
for (let i = 0; i < descriptions.length; i++) {
const description = descriptions[i];
this._functionDescriptions.set(description.functionName, description);
}
+
+ return toDisposable(() => {
+ for (let i = 0; i < descriptions.length; i++) {
+ const description = descriptions[i];
+ this._functionDescriptions.delete(description.functionName);
+ }
+ });
}
getDescriptions() {
diff --git a/packages/facade/src/apis/__tests__/facade.spec.ts b/packages/facade/src/apis/__tests__/facade.spec.ts
index e164199f96..e6f2821eb0 100644
--- a/packages/facade/src/apis/__tests__/facade.spec.ts
+++ b/packages/facade/src/apis/__tests__/facade.spec.ts
@@ -23,6 +23,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { RenderComponentType, SheetComponent } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import { SHEET_VIEW_KEY } from '@univerjs/sheets-ui';
+import { RegisterFunctionMutation, SetFormulaCalculationStartMutation, UnregisterFunctionMutation } from '@univerjs/engine-formula';
+import { IDescriptionService } from '@univerjs/sheets-formula';
import type { FUniver } from '../facade';
import { createTestBed } from './create-test-bed';
import { COLUMN_UNIQUE_KEY, ColumnHeaderCustomExtension, MAIN_UNIQUE_KEY, MainCustomExtension, ROW_UNIQUE_KEY, RowHeaderCustomExtension } from './utils/sheet-extension-util';
@@ -54,7 +56,10 @@ describe('Test FUniver', () => {
commandService = get(ICommandService);
commandService.registerCommand(SetRangeValuesCommand);
commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(RegisterFunctionMutation);
+ commandService.registerCommand(UnregisterFunctionMutation);
commandService.registerCommand(SetStyleCommand);
+ commandService.registerCommand(SetFormulaCalculationStartMutation);
getValueByPosition = (
startRow: number,
@@ -162,6 +167,34 @@ describe('Test FUniver', () => {
expect(() => univerAPI.createSocket('URL')).toThrowError();
});
+ it('Function registerFunction', () => {
+ const funcionName = 'CUSTOMSUM';
+ const functionsDisposable = univerAPI.registerFunction({
+ calculate: [
+ [function (...variants) {
+ let sum = 0;
+
+ for (const variant of variants) {
+ sum += Number(variant) || 0;
+ }
+
+ return sum;
+ }, funcionName, 'Custom sum function'],
+ ],
+ });
+
+ const descriptionService = get(IDescriptionService);
+
+ const functionInfo = descriptionService.getFunctionInfo(funcionName);
+
+ expect(functionInfo?.functionName).toBe(funcionName);
+
+ functionsDisposable.dispose();
+
+ const functionInfoAfterDispose = descriptionService.getFunctionInfo(funcionName);
+
+ expect(functionInfoAfterDispose).toBeUndefined();
+ });
it('Function registerSheetRowHeaderExtension and unregisterSheetRowHeaderExtension', () => {
const rowHeader = univerAPI.registerSheetRowHeaderExtension('test', new RowHeaderCustomExtension());
diff --git a/packages/facade/src/apis/facade.ts b/packages/facade/src/apis/facade.ts
index 4064c8d5fb..b423d4b889 100644
--- a/packages/facade/src/apis/facade.ts
+++ b/packages/facade/src/apis/facade.ts
@@ -19,6 +19,7 @@ import type { CommandListener, DocumentDataModel, IDocumentData, IExecutionOptio
Workbook } from '@univerjs/core';
import {
BorderStyleTypes,
+ debounce,
ICommandService,
IUniverInstanceService,
toDisposable,
@@ -28,7 +29,7 @@ import {
WrapStrategy,
} from '@univerjs/core';
import { ISocketService, WebSocketService } from '@univerjs/network';
-import type { IRegisterFunctionParams, IUnregisterFunctionParams } from '@univerjs/sheets-formula';
+import type { IRegisterFunctionParams } from '@univerjs/sheets-formula';
import { IRegisterFunctionService, RegisterFunctionService } from '@univerjs/sheets-formula';
import type { IDisposable } from '@wendellhu/redi';
import { Inject, Injector, Quantity } from '@wendellhu/redi';
@@ -36,6 +37,7 @@ import { Inject, Injector, Quantity } from '@wendellhu/redi';
import type { RenderComponentType, SheetComponent, SheetExtension } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import { SHEET_VIEW_KEY } from '@univerjs/sheets-ui';
+import { SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import { FDocument } from './docs/f-document';
import { FWorkbook } from './sheets/f-workbook';
@@ -57,13 +59,20 @@ export class FUniver {
static BorderStyle = BorderStyleTypes;
static WrapStrategy = WrapStrategy;
+ /**
+ * registerFunction may be executed multiple times, triggering multiple formula forced refreshes
+ */
+ private _debouncedFormulaCalculation: () => void;
+
constructor(
@Inject(Injector) private readonly _injector: Injector,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@ISocketService private readonly _ws: ISocketService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService
- ) {}
+ ) {
+ this._initialize();
+ }
/**
* Create a new spreadsheet and get the API handler of that spreadsheet.
@@ -143,7 +152,7 @@ export class FUniver {
* Register a function to the spreadsheet.
* @param config
*/
- registerFunction(config: IRegisterFunctionParams) {
+ registerFunction(config: IRegisterFunctionParams): IDisposable {
let registerFunctionService = this._injector.get(IRegisterFunctionService);
if (!registerFunctionService) {
@@ -151,24 +160,14 @@ export class FUniver {
registerFunctionService = this._injector.get(IRegisterFunctionService);
}
- registerFunctionService.registerFunctions(config);
- }
-
- /**
- * Unregister a function from the spreadsheet.
- *
- * TODO@Dushusir: remove unregister,use IDisposable
- * @param config
- */
- unregisterFunction(config: IUnregisterFunctionParams) {
- let registerFunctionService = this._injector.get(IRegisterFunctionService);
+ const functionsDisposable = registerFunctionService.registerFunctions(config);
- if (!registerFunctionService) {
- this._injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);
- registerFunctionService = this._injector.get(IRegisterFunctionService);
- }
+ // When the initialization workbook data already contains custom formulas, and then register the formula, you need to trigger a forced calculation to refresh the calculation results
+ this._debouncedFormulaCalculation();
- registerFunctionService.unregisterFunctions(config);
+ return toDisposable(() => {
+ functionsDisposable.dispose();
+ });
}
/**
@@ -318,5 +317,20 @@ export class FUniver {
return renderComponent;
}
+ private _initialize(): void {
+ this._debouncedFormulaCalculation = debounce(() => {
+ this._commandService.executeCommand(
+ SetFormulaCalculationStartMutation.id,
+ {
+ commands: [],
+ forceCalculation: true,
+ },
+ {
+ onlyLocal: true,
+ }
+ );
+ }, 10);
+ }
+
// @endregion
}
diff --git a/packages/sheets-formula/README-zh.md b/packages/sheets-formula/README-zh.md
index 068569c2fd..151e815163 100644
--- a/packages/sheets-formula/README-zh.md
+++ b/packages/sheets-formula/README-zh.md
@@ -25,778 +25,10 @@ npm install @univerjs/sheets-formula
pnpm add @univerjs/sheets-formula
```
-### 添加公式前置条件
+### 如何自定义公式
如果官方提供的公式不满足您的需求,可以自己扩展公式。根据不同的需求,我们提供了多种方式来支持注册一个或多个自定义公式。
-您需要先准备好公式提示所需要的国际化文案和算法,然后参考我们的[贡献指南](https://github.com/dream-num/univer/blob/dev/CONTRIBUTING.md)运行 Univer 项目,再开始添加公式。
+- [使用 Facade API 注册公式](https://univer.ai/zh-cn/guides/facade/general/#注册公式)
+- [自定义公式](https://univer.ai/zh-cn/guides/customization/formula/)
-### 如何使用 Uniscript 添加公式
-
-使用 Uniscript 脚本,可以方便快速的在当前 Univer 实例中注册自定义公式。
-
-如下案例所示,使用 `registerFunction` 将一个 `CUSTOMSUM` 公式所需要的算法、名称、描述一次性注册到公式插件,执行之后就可以使用公式了。在任一空白单元格输入 `=CUSTOMSUM` 可以看到提示。
-
-```js
-univerAPI.registerFunction({
- calculate: [
- [function (...variants) {
- let sum = 0;
-
- for(const variant of variants){
- sum += Number(variant) || 0;
- }
-
- return sum;
- }, 'CUSTOMSUM', '求参数的和'],
- // ... 更多公式
- ]
-})
-```
-
-使用 `unregisterFunction` 方法能快速卸载自定义公式
-
-```ts
-univerAPI.unregisterFunction({
- functionNames: ['CUSTOMSUM']
-})
-```
-
-如果想要提供更完善的国际化内容和描述,还可以配置 `locales` 和 `description` 字段。如下所示。
-
-```js
-const FUNCTION_NAMES_USER = {
- CUSTOMSUM: 'CUSTOMSUM'
-}
-univerAPI.registerFunction({
- locales:{
- 'zhCN': {
- formulaCustom: {
- CUSTOMSUM: {
- description: '将单个值、单元格引用或是区域相加,或者将三者的组合相加。',
- abstract: '求参数的和',
- links: [
- {
- title: '教学',
- url: 'https://support.microsoft.com/zh-cn/office/sum-%E5%87%BD%E6%95%B0-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: '数值1',
- detail: '要相加的第一个数字。 该数字可以是 4 之类的数字,B6 之类的单元格引用或 B2:B8 之类的单元格范围。',
- },
- number2: {
- name: '数值2',
- detail: '这是要相加的第二个数字。 可以按照这种方式最多指定 255 个数字。',
- },
- },
- },
- // ... 更多公式
- },
- },
- 'enUS':{
- formulaCustom:{
- CUSTOMSUM: {
- description: `You can add individual values, cell references or ranges or a mix of all three.`,
- abstract: `Adds its arguments`,
- links: [
- {
- title: 'Instruction',
- url: 'https://support.microsoft.com/en-us/office/sum-function-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: 'number1',
- detail: 'The first number you want to add. The number can be like 4, a cell reference like B6, or a cell range like B2:B8.',
- },
- number2: {
- name: 'number2',
- detail: 'This is the second number you want to add. You can specify up to 255 numbers in this way.',
- },
- },
- },
- }
- }
- },
- description:[
- {
- functionName: FUNCTION_NAMES_USER.CUSTOMSUM,
- aliasFunctionName: 'formulaCustom.CUSTOMSUM.aliasFunctionName',
- functionType: 15,
- description: 'formulaCustom.CUSTOMSUM.description',
- abstract: 'formulaCustom.CUSTOMSUM.abstract',
- functionParameter: [
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number1.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number2.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number2.detail',
- example: 'B2:B10',
- require: 0,
- repeat: 1,
- },
- ],
- },
- // ... 更多公式
- ],
- calculate: [
- [function (...variants) {
- let sum = 0;
-
- for(const variant of variants){
- sum += Number(variant) || 0;
- }
-
- return sum;
- }, FUNCTION_NAMES_USER.CUSTOMSUM],
- // ... 更多公式
- ]
-})
-```
-
-说明
-
-- `locales` 下可以设置多种语言,命名规则参考 [LocaleType](/api/core/enums/LocaleType.html)。可以在 `functionList` 下添加多个公式的翻译。详细的字段说明请参考[如何在 UniverFormulaEnginePlugin 中添加公式](./#如何在-univerformulaengineplugin-中添加公式)的部分。
-- `description` 设置自定义公式的描述。
-- `calculate` 编写计算公式的具体算法和名称映射。入参为使用公式时用户输入的内容,可能为数字、字符串、布尔值,或者一个范围,也是返回同样的格式。
-
-同样的, 如果使用 `unregisterFunction` 方法,推荐你把国际化文件也移除。下方示例是将中文和英文的 `formulaCustom` 节点移除。
-
-```ts
-univerAPI.unregisterFunction({
- localeKeys: {
- 'zhCN': ['formulaCustom'],
- 'enUS': ['formulaCustom'],
- },
- functionNames: ['CUSTOMSUM']
-})
-```
-
-Uniscript 底层使用了 `@univerjs/facade`,你也可以直接在项目中使用类似 Uniscript 的 API,请参考 [注册公式](/guides/facade/register-function)。
-
-### 如何在初始化 Univer 时添加公式
-
-按照以下步骤来实现一个自定义公式 `CUSTOMSUM`。
-
-你可以新建一个 `custom-function.ts` 文件来专门放置自定义公式相关模块,或者直接写在 `univer` 初始化之前。
-
-1. 定义公式名称
-
- 首先为公式起一个名称,我们要求不能同已有公式名称重复,已有公式主要是从 [Office Excel](https://support.microsoft.com/zh-cn/office/excel-%E5%87%BD%E6%95%B0-%E6%8C%89%E7%B1%BB%E5%88%AB%E5%88%97%E5%87%BA-5f91f4e9-7b42-46d2-9bd1-63f26a86c0eb) 参考。
-
- 我们把多个自定义公式搜集在一个枚举中。
-
- ```ts
- /**
- * function name
- */
- export enum FUNCTION_NAMES_USER {
- CUSTOMSUM = "CUSTOMSUM",
- }
- ```
-
-2. 定义国际化
-
- 定义你所需要的国际化内容,详细的字段说明请参考[如何在 UniverFormulaEnginePlugin 中添加公式](./#如何在-univerformulaengineplugin-中添加公式)的部分。同样的,多个公式就用公式名称作为 `key` 值区分。
-
- ```ts
- /**
- * i18n
- */
- export const functionEnUS = {
- formulaCustom: {
- CUSTOMSUM: {
- description: `You can add individual values, cell references or ranges or a mix of all three.`,
- abstract: `Adds its arguments`,
- links: [
- {
- title: 'Instruction',
- url: 'https://support.microsoft.com/en-us/office/sum-function-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: 'number1',
- detail: 'The first number you want to add. The number can be like 4, a cell reference like B6, or a cell range like B2:B8.',
- },
- number2: {
- name: 'number2',
- detail: 'This is the second number you want to add. You can specify up to 255 numbers in this way.',
- },
- },
- },
- },
- };
-
- export const functionZhCN = {
- formulaCustom: {
- CUSTOMSUM: {
- description: '将单个值、单元格引用或是区域相加,或者将三者的组合相加。',
- abstract: '求参数的和',
- links: [
- {
- title: '教学',
- url: 'https://support.microsoft.com/zh-cn/office/sum-%E5%87%BD%E6%95%B0-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: '数值1',
- detail: '要相加的第一个数字。 该数字可以是 4 之类的数字,B6 之类的单元格引用或 B2:B8 之类的单元格范围。',
- },
- number2: {
- name: '数值2',
- detail: '这是要相加的第二个数字。 可以按照这种方式最多指定 255 个数字。',
- },
- },
- },
- },
- };
- ```
-
-3. 注册国际化
-
- 在原有的国际化对象中扩展你定义的国际化内容。
-
- ```ts
- export const locales = {
- [LocaleType.EN_US]: {
- ...UniverSheetsEnUS,
- ...UniverDocsUIEnUS,
- ...UniverSheetsUIEnUS,
- ...UniverUiEnUS,
- ...UniverDesignEnUS,
- ...functionEnUS,
- },
- [LocaleType.ZH_CN]: {
- ...functionZhCN,
- },
- };
- ```
-
-4. 定义描述
-
- 公式的描述中主要是配置国际化字段,用于公式搜索提示、详情面板等。
-
- ```ts
- import type { IFunctionInfo } from '@univerjs/engine-formula';
- import { FunctionType } from '@univerjs/engine-formula';
-
- /**
- * description
- */
- export const FUNCTION_LIST_USER: IFunctionInfo[] = [
- {
- functionName: FUNCTION_NAMES_USER.CUSTOMSUM,
- aliasFunctionName: 'formulaCustom.CUSTOMSUM.aliasFunctionName',
- functionType: FunctionType.User,
- description: 'formulaCustom.CUSTOMSUM.description',
- abstract: 'formulaCustom.CUSTOMSUM.abstract',
- functionParameter: [
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number1.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number2.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number2.detail',
- example: 'B2:B10',
- require: 0,
- repeat: 1,
- },
- ],
- },
- ];
- ```
-
-5. 注册描述
-
- 注册公式插件时传入你定义的描述对象。
-
- ```ts
- // univer
- univer.registerPlugin(UniverSheetsFormulaPlugin, {
- description: FUNCTION_LIST_USER,
- });
- ```
-
-6. 定义公式算法
-
- 编写具体的公式计算逻辑,并将算法和公式名称映射起来。
-
- ```ts
- import type { ArrayValueObject, BaseValueObject, IFunctionInfo } from '@univerjs/engine-formula';
- import { BaseFunction, FunctionType, NumberValueObject } from '@univerjs/engine-formula';
-
- /**
- * Function algorithm
- */
- export class Customsum extends BaseFunction {
- override calculate(...variants: BaseValueObject[]) {
- let accumulatorAll: BaseValueObject = NumberValueObject.create(0);
- for (let i = 0; i < variants.length; i++) {
- let variant = variants[i];
-
- if (variant.isError()) {
- return variant;
- }
-
- if (accumulatorAll.isError()) {
- return accumulatorAll;
- }
-
- if (variant.isArray()) {
- variant = (variant as ArrayValueObject).sum();
- }
-
- accumulatorAll = accumulatorAll.plus(variant as BaseValueObject);
- }
-
- return accumulatorAll;
- }
- }
-
- // Mapping of algorithms and names
- export const functionUser = [[Customsum, FUNCTION_NAMES_USER.CUSTOMSUM]];
- ```
-
-7. 注册公式算法
-
- 在 `UniverFormulaEnginePlugin` 传入你定义的公式算法对象。
-
- ```ts
- univer.registerPlugin(UniverFormulaEnginePlugin, {
- function: functionUser,
- });
- ```
-
- 请注意:如果 `UniverFormulaEnginePlugin` 在 `worker` 中有实例化,则需要在 `worker` 中的 `UniverFormulaEnginePlugin` 注册公式算法,否则无法获取执行自定义公式。
-
-8. 测试
-
- 到这里就完成了自定义公式的开发,现在可以测试一下。任一空白单元格输入 `=CUSTOMSUM` 预期能得到公式提示。这里提供一个[自定义公式 Demo](/playground?title=Custom%20Function),供参考。
-
-### 如何在第三方插件中添加公式
-
-如果你正在开发一个 Univer 插件,你可以直接在这个插件中新增自定义公式,方便代码在一个插件仓库中管理。
-
-我们内部的 `UniverFormulaEnginePlugin` 插件提供了一个 `function.service`,专门用来注册公式的描述和算法。
-
-首先参考 [自定义插件](https://univer.ai/zh-cn/guides/customization/write-a-plugin/),新建一个插件,然后就可以开始添加自定义公式。
-
-1. `common` 文件内新建 `custom-function.ts` 文件,将公式所需要的基础模块全部写好。
-
- ```ts
- import type { ArrayValueObject, BaseValueObject, IFunctionInfo } from '@univerjs/engine-formula';
- import { BaseFunction, FunctionType, NumberValueObject } from '@univerjs/engine-formula';
-
- /**
- * function name
- */
- export enum FUNCTION_NAMES_USER {
- CUSTOMSUM = 'CUSTOMSUM',
- }
-
- /**
- * i18n
- */
- export const functionEnUS = {
- formulaCustom: {
- CUSTOMSUM: {
- description: `You can add individual values, cell references or ranges or a mix of all three.`,
- abstract: `Adds its arguments`,
- links: [
- {
- title: 'Instruction',
- url: 'https://support.microsoft.com/en-us/office/sum-function-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: 'number1',
- detail: 'The first number you want to add. The number can be like 4, a cell reference like B6, or a cell range like B2:B8.',
- },
- number2: {
- name: 'number2',
- detail: 'This is the second number you want to add. You can specify up to 255 numbers in this way.',
- },
- },
- },
- },
- };
-
- export const functionZhCN = {
- formulaCustom: {
- CUSTOMSUM: {
- description: '将单个值、单元格引用或是区域相加,或者将三者的组合相加。',
- abstract: '求参数的和',
- links: [
- {
- title: '教学',
- url: 'https://support.microsoft.com/zh-cn/office/sum-%E5%87%BD%E6%95%B0-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: '数值1',
- detail: '要相加的第一个数字。 该数字可以是 4 之类的数字,B6 之类的单元格引用或 B2:B8 之类的单元格范围。',
- },
- number2: {
- name: '数值2',
- detail: '这是要相加的第二个数字。 可以按照这种方式最多指定 255 个数字。',
- },
- },
- },
- },
- };
-
- /**
- * description
- */
- export const FUNCTION_LIST_USER: IFunctionInfo[] = [
- {
- functionName: FUNCTION_NAMES_USER.CUSTOMSUM,
- aliasFunctionName: 'formulaCustom.CUSTOMSUM.aliasFunctionName',
- functionType: FunctionType.User,
- description: 'formulaCustom.CUSTOMSUM.description',
- abstract: 'formulaCustom.CUSTOMSUM.abstract',
- functionParameter: [
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number1.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number2.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number2.detail',
- example: 'B2:B10',
- require: 0,
- repeat: 1,
- },
- ],
- },
- ];
-
- /**
- * Function algorithm
- */
- export class Customsum extends BaseFunction {
- override calculate(...variants: BaseValueObject[]) {
- let accumulatorAll: BaseValueObject = NumberValueObject.create(0);
- for (let i = 0; i < variants.length; i++) {
- let variant = variants[i];
-
- if (variant.isError()) {
- return variant;
- }
-
- if (accumulatorAll.isError()) {
- return accumulatorAll;
- }
-
- if (variant.isArray()) {
- variant = (variant as ArrayValueObject).sum();
- }
-
- accumulatorAll = accumulatorAll.plus(variant as BaseValueObject);
- }
-
- return accumulatorAll;
- }
- }
-
- export const functionUser = [[Customsum, FUNCTION_NAMES_USER.CUSTOMSUM]];
- ```
-
-2. `controllers` 文件夹下新建 `custom-description.controller.ts` 用于注册公式国际化内容和描述。
-
- ```ts
- import { Disposable, LifecycleStages, LocaleService, OnLifecycle } from '@univerjs/core';
- import { Inject } from '@wendellhu/redi';
-
- import { FUNCTION_LIST_USER, functionEnUS, functionZhCN } from '../common/custom-function';
- import { IDescriptionService } from '../services/description.service';
-
- @OnLifecycle(LifecycleStages.Ready, CustomDescriptionController)
- export class CustomDescriptionController extends Disposable {
- constructor(
- @IDescriptionService private readonly _descriptionService: IDescriptionService,
- @Inject(LocaleService) private readonly _localeService: LocaleService
- ) {
- super();
-
- this._initialize();
- }
-
- private _initialize(): void {
- this._registerLocales();
- this._registerCustomDescriptions();
- }
-
- private _registerLocales() {
- this._localeService.load({
- zhCN: functionZhCN,
- enUS: functionEnUS,
- });
- }
-
- private _registerCustomDescriptions() {
- this._descriptionService.registerDescription(FUNCTION_LIST_USER);
- }
- }
- ```
-
-3. `controllers` 文件夹下新建 `custom-function.controller.ts` 用于注册公式算法。
-
- ```ts
- import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';
- import type { BaseFunction, IFunctionNames } from '@univerjs/engine-formula';
- import { IFunctionService } from '@univerjs/engine-formula';
- import { type Ctor } from '@wendellhu/redi';
-
- import { functionUser } from '../common/custom-function';
-
- @OnLifecycle(LifecycleStages.Ready, CustomFunctionController)
- export class CustomFunctionController extends Disposable {
- constructor(@IFunctionService private readonly _functionService: IFunctionService) {
- super();
-
- this._initialize();
- }
-
- private _initialize(): void {
- this._registerCustomFunctions();
- }
-
- private _registerCustomFunctions() {
- const functions: BaseFunction[] = [...functionUser].map((registerObject) => {
- const Func = registerObject[0] as Ctor<BaseFunction>;
- const name = registerObject[1] as IFunctionNames;
-
- return new Func(name);
- });
-
- this._functionService.registerExecutors(...functions);
- }
- }
- ```
-
-4. 在插件入口文件 `plugin.ts` 中,将 `custom-description.controller.ts` 和 `custom-function.controller.ts` 注册到 DI 系统中。
-
- ```ts
- initialize(): void {
- // ... 其它逻辑
-
- const dependencies: Dependency[] = [
- // ... 其它模块
- [CustomFunctionController],
- [CustomDescriptionController],
- ];
-
- dependencies.forEach((dependency) => this._injector.add(dependency));
- }
- ```
-
- 启动 Univer,任一空白单元格输入 `=CUSTOMSUM` 即可测试这个新添加的公式。
-
-请注意:如果 `UniverFormulaEnginePlugin` 在 `worker` 中有实例化,则需要在 `worker`中注册公式算法,否则无法获取执行自定义公式。
-除了通过 `UniverFormulaEnginePlugin` 配置的形式来注册,还可以将公式算法模块单独包装成一个插件来注册。
-
-首先 `plugin.ts` 中就不需要注册 `CustomFunctionController` 了,同级目录新建一个 `custom-function-plugin.ts`,专门用于注册 `CustomFunctionController`。
-
-```ts
-import { Plugin, UniverInstanceType } from '@univerjs/core';
-import type { Dependency } from '@wendellhu/redi';
-import { Inject, Injector } from '@wendellhu/redi';
-
-import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
-import { CustomFunctionController } from './controllers/custom-function.controller';
-
-export class UniverSheetsCustomFunctionPlugin extends Plugin {
- static override pluginName = FORMULA_UI_PLUGIN_NAME
- static override type = UniverInstanceType.UNIVER_SHEET;
-
- constructor(@Inject(Injector) override readonly _injector: Injector) {
- super();
- }
-
- initialize(): void {
- const dependencies: Dependency[] = [[CustomFunctionController]];
-
- dependencies.forEach((dependency) => this._injector.add(dependency));
- }
-
- override onReady(): void {
- this.initialize();
- }
-}
-```
-
-然后在 `index.ts` 中导出
-
-```ts
-export { UniverSheetsFormulaPlugin } from './formula-ui-plugin';
-```
-
-最后你的 `worker` 入口初始化这个插件。
-
-```ts
-import { UniverSheetsCustomFunctionPlugin } from '@univerjs/sheets-formula';
-
-// ... 初始化其他插件
-univer.registerPlugin(UniverSheetsCustomFunctionPlugin);
-```
-
-这样就可以在 `worker` 中注册公式了。
-
-### 如何在 UniverFormulaEnginePlugin 中添加公式
-
-#### 参考文档
-
-[Office Excel 函数(按类别列出)](https://support.microsoft.com/zh-cn/office/excel-%E5%87%BD%E6%95%B0-%E6%8C%89%E7%B1%BB%E5%88%AB%E5%88%97%E5%87%BA-5f91f4e9-7b42-46d2-9bd1-63f26a86c0eb)
-
-#### 类别
-
-详细 API 参考 [FunctionType](/api/engine-formula/enums/FunctionType.html)
-
-- Financial
-- Date
-- Math
-- Statistical
-- Lookup
-- Database
-- Text
-- Logical
-- Information
-- Engineering
-- Cube
-- Compatibility
-- Web
-- Array
-- Univer
-- User
-
-#### 要求
-
-要实现一个公式,需要添加公式描述、国际化和公式算法,以 `SUMIF` 函数的写法为例作为参考
-
-1. 添加函数名称
-
- 位置在 [packages/engine-formula/src/functions/math/function-names.ts](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/functions/math/function-names.ts)。
-
- 每个分类都有一个文件夹,包含一个 `function-names` 文件用于统一管理这个分类的所有函数名。我们先添加上函数名称,在 `sheets-formula` 插件中会用到。
-
- 注意,Excel 中一个函数可能属于多个分类,比如 `FLOOR` 在兼容性和数学函数中出现,我们将它归类到数学分类下。其他函数也是这样处理,以确切的分类为依据。
-
- > 大多数 Excel 函数已经写好了函数名。新的函数可以在末尾添加
-
-2. 国际化文件
-
- 位置在 [packages/sheets-formula/src/locale/function-list/math/en-US.ts](https://github.com/dream-num/univer/blob/dev/packages/sheets-formula/src/locale/function-list/math/en-US.ts)。
-
- 国际化也是一个分类一个文件。简介从 Office 函数分类页参考。
- ![office excel](./assets/office-excel-zh.png)
-
- 函数描述和参数描述从 Office 函数详情页参考
- ![sumif](./assets/sumif-zh.png)
-
- 大部分的函数名称我们已经写好了基础的描述、简介、链接、参数结构,推荐您在此基础上进行修改,如果没有的函数需要自己加在末尾。
-
- 要求:
-
- - 函数翻译的参数 `key` 使用这个函数的每个参数英文名称,比如 `SUMIF`,除非有错误,一般不用改动
- - `description` 参数需要综合下内容进行提取,因为有的 Excel 描述很长,需要简化
- - `abstract` 和 `links` 基本上不需要做改动
- - `aliasFunctionName` 是可选参数,大部分公式不需要填写(也可以只设置某个国家的别名),暂时还未找到有公式别名文档来参考。目前找到一个函数翻译插件可能提供类似功能 [Excel 函数翻译工具](https://support.microsoft.com/zh-cn/office/excel-%E5%87%BD%E6%95%B0%E7%BF%BB%E8%AF%91%E5%B7%A5%E5%85%B7-f262d0c0-991c-485b-89b6-32cc8d326889)
- - `functionParameter` 中需要为每个参数设定一个名称,我们推荐根据参数的含义进行变化,比如数值类型的 `key` 为 `number`(仅有一个数值参数的时候)或者 `number1`、`number2`(有多个数值参数的时候),范围为 `range`,条件为 `criteria`,求和范围为 `sumRange`,采用驼峰式命名法。对于具体的参数内容, `name` 英文格式就使用带下划线的格式 `sum_range`,其他语言采用翻译的文本, `detail` 全部采用翻译。
- - Office 函数文档中文翻译猜测用的机翻,部分翻译不容易理解,需要自己修改,一部分专用名词如下。
- - 单元格参考 => 单元格引用
- - 数字类型的参数统一翻译为:数值
- - `abstract` 结尾不要加句号(用在用户输入单元格时的搜索列表中,但是部分国家的语言有加句号的习惯,比如日本语,参照 Excel 的简介信息即可),`description` 和 `detail` 结尾加句号(用在描述中)
- - 英文句子的首字母大写
- - 注意所有的现有的国际化文件都需要填写,目前只有中英日(Excel 介绍页底部可以切换语言)
-
-3. 公式描述
-
- `SUMIF` 属于 `math` 分类,描述信息在 [packages/sheets-formula/src/services/function-list/math.ts](https://github.com/dream-num/univer/blob/dev/packages/sheets-formula/src/services/function-list/math.ts),这个文件负责整个 `math` 分类所有函数。
-
- 大部分的函数名称我们已经写好了基础的描述结构,推荐您在此基础上进行修改,如果没有的函数需要自己加在末尾。
-
- 要求:
-
- - 在 `FUNCTION_LIST_MATH` 数组中增加公式,我们建议保持和国际化文件中的顺序一致,便于管理和查找
- - `functionName` 需要引用之前定义的 `FUNCTION_NAMES_MATH` 枚举
- - `aliasFunctionName` 也是可选的,如果国际化文件中没有别名,这里也不用添加
- - 国际化字段注意对应好函数名和参数名
- - 注意修改函数参数的信息, `example` 参数示例(比如范围写 `"A1:A20"`,条件写 `">5"` ),`require` 是否必需(1 必需,0 可选) ,`repeat` 是否允许重复(1 允许重复,0 不允许重复),详细说明参考文件内的接口 [IFunctionParam](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/basics/function.ts)
-
-4. 公式算法
-
- 位置在 [packages/engine-formula/src/functions/math/sumif/index.ts](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/functions/math/sumif/index.ts)。
-
- 在当前公式的分类文件夹下新建公式文件夹,文件夹名称与公式相同,采用短横线命名,一个公式一个文件夹。然后新建 `index.ts` 文件来写公式算法,公式 `class` 的名称采用帕斯卡命名法(又叫大驼峰),认为公式是一个单词,带 `_` 或者 `.` 的公式认为是两个单词,比如
-
- - `SUMIF` => 文件夹 `sumif`, 类 `Sumif`
- - `NETWORKDAYS.INTL` => 文件夹 `networkdays-intl`, 类 `NetworkdaysIntl`
- - `ARRAY_CONSTRAIN` => 文件夹 `array-constrain`, 类 `ArrayConstrain`
-
- 同级新建 `__tests__` 来写编写单元测试。写完之后,记得在分类目录下的 `function-map` 文件中添加公式算法和函数名映射用于注册这个函数算法。
-
- 位置在 [packages/engine-formula/src/functions/math/function-map.ts](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/functions/math/function-map.ts)。
-
-5. 单元测试
-
- 位置在 [packages/engine-formula/src/functions/math/sumif/\_\_tests\_\_/index.spec.ts](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/functions/math/sumif/__tests__/index.spec.ts)
-
- 注意:
-
- - 补充 `sheetData`, 根据公式计算的需要构建好 `cellData`, 确定 `rowCount`、`columnCount`
- - 手动初始化公式 `new Sumif(FUNCTION_NAMES_MATH.SUMIF)`
- - 每个测试中手动构建好公式入参,最后 `calculate` 执行即可
- - 单个公式的测试一般用于当前单个公式的算法,如果需要测试多个公式的嵌套,可以手动嵌套,或者到 `/packages/engine-formula/src/functions/__tests__` 目录下执行嵌套的复杂公式
-
-6. 功能测试
-
- 启动 Univer 开发模式,在界面上测试公式,预先构造好数据,
-
- - 在任一空白单元格输入 `=sumif`,预期会有搜索提示列表弹出
- - 确认选择 `SUMIF` 或者 输入 `=sumif(` 之后,触发公式详细介绍弹窗,仔细检查介绍页内容是否完整
- - 选择数据范围,确认之后触发计算,检查公式计算结果是否正确
-
-### 公式实现注意事项
-
-- 大部分的公式规则请参考最新版本的 Excel,如果有不合理的地方,再参考 Google Sheets。
-- 任何公式的入参和出参都可以是 `A1`、`A1:B10`,单元格内容也可能是数字、字符串、布尔值、空单元格、错误值、数组等,虽然公式教程中说明了识别固定的数据类型,但是程序上实现是需要都兼容的,调研 Excel 的时候需要把所有情况考虑到,比如 `=SIN(A1:B10)`,会展开一个正弦计算后的范围。
-
- - 例如 `XLOOKUP` 函数,要求两个入参的行或列至少又一个大小相等,这样才能进行矩阵计算。
- - 例如 `SUMIF` 函数,大家以为是求和,但是它是可以根据第二个参数进行展开的
- ![sumif array](./assets/sumif-array-zh.png)
- ![sumif array result](./assets/sumif-array-result-zh.png)
- - Excel 的公式计算,越来越像 numpy,比如
- ![numpy](./assets/numpy-zh.png)
-
-- 公式的数值计算,需要使用内置的方法,尽量不要获取值自行计算。因为公式的参数可以是值、数组、引用。可以参考已有的 `sum`、`minus` 函数。
-- 精度问题,公式引入了 `big.js`,使用内置方法会调用该库,但是相比原生计算会慢接近 100 倍,所以像 `sin` 等 `js` 方法,尽量用原生实现。
-- 需要自定义计算,使用 `product` 函数,适合两个入参的计算,调用 `map` 对值自身进行迭代计算,适合对一个入参本身的值进行改变。
-- 公式算法支持两种配置 `needsExpandParams` 和 `needsReferenceObject`
- - `needsExpandParams`: 函数是否需要扩展参数,主要处理类似 `LOOKUP` 函数需要处理不同大小向量的情况
- - `needsReferenceObject`:函数是否需要传入引用对象,设置之后 `BaseReferenceObject` 不会转化为 `ArrayValueObject` 而是直接传入公式算法,比如 `OFFSET` 函数
-- 公式计算错误会返回固定类型的错误,比如 `#NAME?`、`#VALUE!`,需要对齐 Excel,因为有判断报错类型的函数 `ISERR`、`ISNA`等,类型指定不对,结果就可能不一样。
-- 公式算法中,即使是必选参数,也需要拦截为 `null` 的情况并返回错误 `#N/A`,因为用户有可能不输入任何参数。这个行为在 Excel 中会被拦截,在 Google Sheets 中返回 `#N/A`,我们参照 Google Sheets。
-
-### 公式基础工具
-
-1. `ValueObjectFactory` 用来自动识别参数格式创建一个参数实例,范围类型的数据用 `RangeReferenceObject` 来创建参数实例
-2. 数组 `toArrayValueObject` 可以与值直接运算,得到新的数组
diff --git a/packages/sheets-formula/README.md b/packages/sheets-formula/README.md
index ba16b9fdab..1d1d6b78a7 100644
--- a/packages/sheets-formula/README.md
+++ b/packages/sheets-formula/README.md
@@ -25,774 +25,9 @@ npm install @univerjs/sheets-formula
pnpm add @univerjs/sheets-formula
```
-### Add formula preconditions
+### How To Customize Formulas
If the officially provided formula does not meet your needs, you can expand the formula yourself. Depending on different needs, we provide multiple ways to support registering one or more custom formulas.
-You need to first prepare the international copywriting and algorithms required for formula prompts, and then refer to our [Contribution Guide](https://github.com/dream-num/univer/blob/dev/CONTRIBUTING.md) to run the Univer project , and then start adding formulas.
-
-### How to add formulas using Uniscript
-
-Using Uniscript scripts, you can quickly and easily register custom formulas in the current Univer instance.
-
-As shown in the following case, use `registerFunction` to register the algorithm, name, and description required by a `CUSTOMSUM` formula into the formula plug-in at one time. After execution, the formula can be used. Enter `=CUSTOMSUM` in any blank cell to see the prompt.
-
-```js
-univerAPI.registerFunction({
- calculate: [
- [function (...variants) {
- let sum = 0;
-
- for(const variant of variants){
- sum += Number(variant) || 0;
- }
-
- return sum;
- }, 'CUSTOMSUM', 'Adds its arguments'],
- // ... more formulas
- ]
-})
-```
-
-Use the `unregisterFunction` method to quickly unregister custom formulas
-
-```ts
-univerAPI.unregisterFunction({
- functionNames: ['CUSTOMSUM']
-})
-```
-
-If you want to provide more complete international content and description, you can also configure the `locales` and `description` fields. As follows.
-
-```js
-const FUNCTION_NAMES_USER = {
- CUSTOMSUM: 'CUSTOMSUM'
-}
-univerAPI.registerFunction({
- locales:{
- 'zhCN': {
- formulaCustom: {
- CUSTOMSUM: {
- description: '将单个值、单元格引用或是区域相加,或者将三者的组合相加。',
- abstract: '求参数的和',
- links: [
- {
- title: '教学',
- url: 'https://support.microsoft.com/zh-cn/office/sum-%E5%87%BD%E6%95%B0-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: '数值1',
- detail: '要相加的第一个数字。 该数字可以是 4 之类的数字,B6 之类的单元格引用或 B2:B8 之类的单元格范围。',
- },
- number2: {
- name: '数值2',
- detail: '这是要相加的第二个数字。 可以按照这种方式最多指定 255 个数字。',
- },
- },
- },
- // ... more formulas
- },
- },
- 'enUS':{
- formulaCustom:{
- CUSTOMSUM: {
- description: `You can add individual values, cell references or ranges or a mix of all three.`,
- abstract: `Adds its arguments`,
- links: [
- {
- title: 'Instruction',
- url: 'https://support.microsoft.com/en-us/office/sum-function-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: 'number1',
- detail: 'The first number you want to add. The number can be like 4, a cell reference like B6, or a cell range like B2:B8.',
- },
- number2: {
- name: 'number2',
- detail: 'This is the second number you want to add. You can specify up to 255 numbers in this way.',
- },
- },
- },
- }
- }
- },
- description:[
- {
- functionName: FUNCTION_NAMES_USER.CUSTOMSUM,
- aliasFunctionName: 'formulaCustom.CUSTOMSUM.aliasFunctionName',
- functionType: 15,
- description: 'formulaCustom.CUSTOMSUM.description',
- abstract: 'formulaCustom.CUSTOMSUM.abstract',
- functionParameter: [
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number1.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number2.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number2.detail',
- example: 'B2:B10',
- require: 0,
- repeat: 1,
- },
- ],
- },
- // ... more formulas
- ],
- calculate: [
- [function (...variants) {
- let sum = 0;
-
- for(const variant of variants){
- sum += Number(variant) || 0;
- }
-
- return sum;
- }, FUNCTION_NAMES_USER.CUSTOMSUM],
- // ... more formulas
- ]
-})
-```
-
-Note
-
-- Multiple languages can be set under `locales`. For naming rules, please refer to [LocaleType](/api/core/enums/LocaleType.html). Translations for multiple formulas can be added under `functionList`. For detailed field descriptions, please refer to the [How to add formulas in UniverFormulaEnginePlugin](./#how-to-add-formulas-in-univerformulaengineplugin) section.
-- `description` sets the description of the custom formula.
-- `calculate` writes the specific algorithm and name mapping of the calculation formula. The input parameter is the content entered by the user when using the formula, which may be a number, a string, a Boolean value, or a range, and the same format is returned.
-
-Likewise, if using the `unregisterFunction` method, it is recommended that you remove the internationalization files as well. The example below removes the Chinese and English `formulaCustom` nodes.
-
-```ts
-univerAPI.unregisterFunction({
- localeKeys: {
- 'zhCN': ['formulaCustom'],
- 'enUS': ['formulaCustom'],
- },
- functionNames: ['CUSTOMSUM']
-})
-```
-
-Uniscript uses `@univerjs/facade` under the hood. You can also use Uniscript-like APIs directly in your project. Please refer to [Registering Function](/en-us/guides/facade/register-function).
-
-### How to add formulas when initializing Univer
-
-Follow the steps below to implement a custom formula `CUSTOMSUM`.
-
-You can create a new `custom-function.ts` file to specifically place custom formula-related modules, or write it directly before `univer` is initialized.
-
-1. Define formula name
-
- First, give the formula a name. We require that it cannot be repeated with the name of the existing formula. The existing formula is mainly from [Office Excel](https://support.microsoft.com/en-us/office/excel-functions-by-category-5f91f4e9-7b42-46d2-9bd1-63f26a86c0eb) refer to.
-
- We collect multiple custom formulas in an enumeration.
-
- ```ts
- /**
- * function name
- */
- export enum FUNCTION_NAMES_USER {
- CUSTOMSUM = "CUSTOMSUM",
- }
- ```
-
-2. Define internationalization
-
- Define the international content you need. For detailed field descriptions, please refer to the [How to add formulas in UniverFormulaEnginePlugin](./#how-to-add-formulas-in-univerformulaengineplugin) section. Similarly, multiple formulas are distinguished by using the formula name as the `key` value.
-
- ```ts
- /**
- *i18n
- */
- export const functionEnUS = {
- formulaCustom: {
- CUSTOMSUM: {
- description: `You can add individual values, cell references or ranges or a mix of all three.`,
- abstract: `Adds its arguments`,
- links: [
- {
- title: 'Instruction',
- url: 'https://support.microsoft.com/en-us/office/sum-function-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: 'number1',
- detail: 'The first number you want to add. The number can be like 4, a cell reference like B6, or a cell range like B2:B8.',
- },
- number2: {
- name: 'number2',
- detail: 'This is the second number you want to add. You can specify up to 255 numbers in this way.',
- },
- },
- },
- },
- };
-
- export const functionZhCN = {
- formulaCustom: {
- CUSTOMSUM: {
- description: '将单个值、单元格引用或是区域相加,或者将三者的组合相加。',
- abstract: '求参数的和',
- links: [
- {
- title: '教学',
- url: 'https://support.microsoft.com/zh-cn/office/sum-%E5%87%BD%E6%95%B0-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: '数值1',
- detail: '要相加的第一个数字。 该数字可以是 4 之类的数字,B6 之类的单元格引用或 B2:B8 之类的单元格范围。',
- },
- number2: {
- name: '数值2',
- detail: '这是要相加的第二个数字。 可以按照这种方式最多指定 255 个数字。',
- },
- },
- },
- },
- };
- ```
-
-3. Registration internationalization
-
- Expand the internationalization content you defined in the original internationalization object.
-
- ```ts
- export const locales = {
- [LocaleType.EN_US]: {
- ...UniverSheetsEnUS,
- ...UniverDocsUIEnUS,
- ...UniverSheetsUIEnUS,
- ...UniverUiEnUS,
- ...UniverDesignEnUS,
- ...functionEnUS,
- },
- [LocaleType.ZH_CN]: {
- ...functionZhCN,
- },
- };
- ```
-
-4. Definition description
-
- The description of the formula mainly configures internationalized fields, which are used for formula search prompts, details panels, etc.
-
- ```ts
- import type { IFunctionInfo } from '@univerjs/engine-formula';
- import { FunctionType } from '@univerjs/engine-formula';
-
- /**
- * description
- */
- export const FUNCTION_LIST_USER: IFunctionInfo[] = [
- {
- functionName: FUNCTION_NAMES_USER.CUSTOMSUM,
- aliasFunctionName: 'formulaCustom.CUSTOMSUM.aliasFunctionName',
- functionType: FunctionType.User,
- description: 'formulaCustom.CUSTOMSUM.description',
- abstract: 'formulaCustom.CUSTOMSUM.abstract',
- functionParameter: [
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number1.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number2.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number2.detail',
- example: 'B2:B10',
- require: 0,
- repeat: 1,
- },
- ],
- },
- ];
- ```
-
-5. Registration description
-
- Pass in the description object you defined when registering the formula plug-in.
-
- ```ts
- // universal
- univer.registerPlugin(UniverSheetsFormulaPlugin, {
- description: FUNCTION_LIST_USER,
- });
- ```
-
-6. Define formula algorithm
-
- Write specific formula calculation logic, map algorithms and formula names.
-
- ```ts
- import type { ArrayValueObject, BaseValueObject, IFunctionInfo } from '@univerjs/engine-formula';
- import { BaseFunction, FunctionType, NumberValueObject } from '@univerjs/engine-formula';
-
- /**
- * Function algorithm
- */
- export class Customsum extends BaseFunction {
- override calculate(...variants: BaseValueObject[]) {
- let accumulatorAll: BaseValueObject = NumberValueObject.create(0);
- for (let i = 0; i < variants.length; i++) {
- let variant = variants[i];
-
- if (variant.isError()) {
- return variant;
- }
-
- if (accumulatorAll.isError()) {
- return accumulatorAll;
- }
-
- if (variant.isArray()) {
- variant = (variant as ArrayValueObject).sum();
- }
-
- accumulatorAll = accumulatorAll.plus(variant as BaseValueObject);
- }
-
- return accumulatorAll;
- }
- }
-
- // Mapping of algorithms and names
- export const functionUser = [[Customsum, FUNCTION_NAMES_USER.CUSTOMSUM]];
- ```
-
-7. Registration formula algorithm
-
- Pass in the formula algorithm object you defined in `UniverFormulaEnginePlugin`.
-
- ```ts
- univer.registerPlugin(UniverFormulaEnginePlugin, {
- function: functionUser,
- });
- ```
-
- Please note: If `UniverFormulaEnginePlugin` is instantiated in `worker`, you need to register the formula algorithm in `UniverFormulaEnginePlugin` in `worker`, otherwise the custom formula cannot be executed.
-
-8. Test
-
- At this point, the development of the custom formula is completed, and now it is time to test it. Enter `=CUSTOMSUM` in any blank cell and expect to get a formula prompt. Here is a [Custom Formula Demo](/playground?title=Custom%20Function) for reference.
-
-### How to add formulas in third-party plug-ins
-
-If you are developing a Univer plug-in, you can add custom formulas directly to the plug-in to facilitate code management in a plug-in repository.
-
-Our internal `UniverFormulaEnginePlugin` plug-in provides a `function.service` specifically for registering formula descriptions and algorithms.
-
-First refer to [Custom Plugin](https://univer.ai/guides/customization/write-a-plugin/) to create a new plug-in, and then you can start adding custom formulas.
-
-1. Create a new `custom-function.ts` file in the `common` file and write all the basic modules required for the formula.
-
- ```ts
- import type { ArrayValueObject, BaseValueObject, IFunctionInfo } from '@univerjs/engine-formula';
- import { BaseFunction, FunctionType, NumberValueObject } from '@univerjs/engine-formula';
-
- /**
- * function name
- */
- export enum FUNCTION_NAMES_USER {
- CUSTOMSUM = 'CUSTOMSUM',
- }
-
- /**
- *i18n
- */
- export const functionEnUS = {
- formulaCustom: {
- CUSTOMSUM: {
- description: `You can add individual values, cell references or ranges or a mix of all three.`,
- abstract: `Adds its arguments`,
- links: [
- {
- title: 'Instruction',
- url: 'https://support.microsoft.com/en-us/office/sum-function-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: 'number1',
- detail: 'The first number you want to add. The number can be like 4, a cell reference like B6, or a cell range like B2:B8.',
- },
- number2: {
- name: 'number2',
- detail: 'This is the second number you want to add. You can specify up to 255 numbers in this way.',
- },
- },
- },
- },
- };
-
- export const functionZhCN = {
- formulaCustom: {
- CUSTOMSUM: {
- description: '将单个值、单元格引用或是区域相加,或者将三者的组合相加。',
- abstract: '求参数的和',
- links: [
- {
- title: '教学',
- url: 'https://support.microsoft.com/zh-cn/office/sum-%E5%87%BD%E6%95%B0-043e1c7d-7726-4e80-8f32-07b23e057f89',
- },
- ],
- functionParameter: {
- number1: {
- name: '数值1',
- detail: '要相加的第一个数字。 该数字可以是 4 之类的数字,B6 之类的单元格引用或 B2:B8 之类的单元格范围。',
- },
- number2: {
- name: '数值2',
- detail: '这是要相加的第二个数字。 可以按照这种方式最多指定 255 个数字。',
- },
- },
- },
- },
- };
-
- /**
- * description
- */
- export const FUNCTION_LIST_USER: IFunctionInfo[] = [
- {
- functionName: FUNCTION_NAMES_USER.CUSTOMSUM,
- aliasFunctionName: 'formulaCustom.CUSTOMSUM.aliasFunctionName',
- functionType: FunctionType.User,
- description: 'formulaCustom.CUSTOMSUM.description',
- abstract: 'formulaCustom.CUSTOMSUM.abstract',
- functionParameter: [
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number1.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formulaCustom.CUSTOMSUM.functionParameter.number2.name',
- detail: 'formulaCustom.CUSTOMSUM.functionParameter.number2.detail',
- example: 'B2:B10',
- require: 0,
- repeat: 1,
- },
- ],
- },
- ];
-
- /**
- * Function algorithm
- */
- export class Customsum extends BaseFunction {
- override calculate(...variants: BaseValueObject[]) {
- let accumulatorAll: BaseValueObject = NumberValueObject.create(0);
- for (let i = 0; i < variants.length; i++) {
- let variant = variants[i];
-
- if (variant.isError()) {
- return variant;
- }
-
- if (accumulatorAll.isError()) {
- return accumulatorAll;
- }
-
- if (variant.isArray()) {
- variant = (variant as ArrayValueObject).sum();
- }
-
- accumulatorAll = accumulatorAll.plus(variant as BaseValueObject);
- }
-
- return accumulatorAll;
- }
- }
-
- export const functionUser = [[Customsum, FUNCTION_NAMES_USER.CUSTOMSUM]];
- ```
-
-2. Create a new `custom-description.controller.ts` under the `controllers` folder to register formula internationalization content and description.
-
- ```ts
- import { Disposable, LifecycleStages, LocaleService, OnLifecycle } from '@univerjs/core';
- import { Inject } from '@wendellhu/redi';
-
- import { FUNCTION_LIST_USER, functionEnUS, functionZhCN } from '../common/custom-function';
- import { IDescriptionService } from '../services/description.service';
-
- @OnLifecycle(LifecycleStages.Ready, CustomDescriptionController)
- export class CustomDescriptionController extends Disposable {
- constructor(
- @IDescriptionService private readonly _descriptionService: IDescriptionService,
- @Inject(LocaleService) private readonly _localeService: LocaleService
- ) {
- super();
-
- this._initialize();
- }
-
- private _initialize(): void {
- this._registerLocales();
- this._registerCustomDescriptions();
- }
-
- private _registerLocales() {
- this._localeService.load({
- zhCN: functionZhCN,
- enUS: functionEnUS,
- });
- }
-
- private _registerCustomDescriptions() {
- this._descriptionService.registerDescription(FUNCTION_LIST_USER);
- }
- }
- ```
-
-3. Create a new `custom-function.controller.ts` under the `controllers` folder to register formula algorithms.
-
- ```ts
- import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';
- import type { BaseFunction, IFunctionNames } from '@univerjs/engine-formula';
- import { IFunctionService } from '@univerjs/engine-formula';
- import { type Ctor } from '@wendellhu/redi';
-
- import { functionUser } from '../common/custom-function';
-
- @OnLifecycle(LifecycleStages.Ready, CustomFunctionController)
- export class CustomFunctionController extends Disposable {
- constructor(@IFunctionService private readonly _functionService: IFunctionService) {
- super();
-
- this._initialize();
- }
-
- private _initialize(): void {
- this._registerCustomFunctions();
- }
-
- private _registerCustomFunctions() {
- const functions: BaseFunction[] = [...functionUser].map((registerObject) => {
- const Func = registerObject[0] as Ctor<BaseFunction>;
- const name = registerObject[1] as IFunctionNames;
-
- return new Func(name);
- });
-
- this._functionService.registerExecutors(...functions);
- }
- }
- ```
-
-4. In the plug-in entry file `plugin.ts`, register `custom-description.controller.ts` and `custom-function.controller.ts` into the DI system.
-
- ```ts
- initialize(): void {
- // ... other logic
-
- const dependencies: Dependency[] = [
- // ... other modules
- [CustomFunctionController],
- [CustomDescriptionController],
- ];
-
- dependencies.forEach((dependency) => this._injector.add(dependency));
- }
- ```
-
- Start Univer and enter `=CUSTOMSUM` in any blank cell to test this newly added formula.
-
-Please note: If `UniverFormulaEnginePlugin` is instantiated in `worker`, you need to register the formula algorithm in `worker`, otherwise the custom formula cannot be executed.
-In addition to registering through the `UniverFormulaEnginePlugin` configuration, the formula algorithm module can also be separately packaged as a plug-in for registration.
-
-First of all, there is no need to register `CustomFunctionController` in `plugin.ts`. Create a new `custom-function-plugin.ts` in the same directory, specifically for registering `CustomFunctionController`.
-
-```ts
-import { Plugin, UniverInstanceType } from '@univerjs/core';
-import type { Dependency } from '@wendellhu/redi';
-import { Inject, Injector } from '@wendellhu/redi';
-
-import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
-import { CustomFunctionController } from './controllers/custom-function.controller';
-
-export class UniverSheetsCustomFunctionPlugin extends Plugin {
- static override pluginName = FORMULA_UI_PLUGIN_NAME
- static override type = UniverInstanceType.UNIVER_SHEET;
-
- constructor(@Inject(Injector) override readonly _injector: Injector) {
- super();
- }
-
- initialize(): void {
- const dependencies: Dependency[] = [[CustomFunctionController]];
-
- dependencies.forEach((dependency) => this._injector.add(dependency));
- }
-
- override onReady(): void {
- this.initialize();
- }
-}
-```
-
-Then export it in `index.ts`
-
-```ts
-export { UniverSheetsFormulaPlugin } from './formula-ui-plugin';
-```
-
-Finally, your `worker` entry initializes the plugin.
-
-```ts
-import { UniverSheetsCustomFunctionPlugin } from '@univerjs/sheets-formula';
-
-// ...initialize other plugins
-univer.registerPlugin(UniverSheetsCustomFunctionPlugin);
-```
-
-This way you can register the formula in `worker`.
-
-### How to add formulas in UniverFormulaEnginePlugin
-
-#### Reference Documentation
-
-[Office Excel functions (by category)](https://support.microsoft.com/en-us/office/excel-functions-by-category-5f91f4e9-7b42-46d2-9bd1-63f26a86c0eb)
-
-#### Categories
-
-Detailed API reference [FunctionType](/api/engine-formula/enums/FunctionType.html)
-
-- Financial
-- Date
-- Math
-- Statistical
-- Lookup
-- Database
-- Text
-- Logical
-- Information
-- Engineering
-- Cube
-- Compatibility
-- Web
-- Array
-- Univer
-- User
-
-#### Requirements
-
-To implement a formula, you need to add formula description, internationalization, and formula algorithm. Take the `SUMIF` function as an example for reference.
-
-1. Add Function Name
-
- Location: [packages/engine-formula/src/functions/math/function-names.ts](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/functions/math/function-names.ts).
-
- Each category has a folder containing a `function-names` file to manage all function names in that category. Add the function name, which will be used in the `sheets-formula` plugin.
-
- Note that a function in Excel may belong to multiple categories. For example, `FLOOR` appears in Compatibility and Math Functions, and we classify it under the Math category. Other functions are treated similarly, based on the exact classification.
-
- > Most Excel functions have already written function names. New functions can be added at the end
-
-2. Internationalization Files
-
- Location: [packages/sheets-formula/src/locale/function-list/math/en-US.ts](https://github.com/dream-num/univer/blob/dev/packages/sheets-formula/src/locale/function-list/math/en-US.ts).
-
- Internationalization is organized by category, with a file for each category. Refer to the Office function category page for a brief overview.
- ![office excel](./assets/office-excel.png)
-
- Refer to the Office function details page for function descriptions and parameter descriptions.
- ![sumif](./assets/sumif.png)
-
- Most function names already have basic description, abstract, links, and parameter structures. It is recommended to modify them based on this foundation. If a function is not present, add it to the end.
-
- Requirements:
-
- - Use the English names of function parameters as the `key` for translation, e.g., `SUMIF`. Generally, do not modify unless there is an error.
- - Extract the `description` from the content, as some Excel descriptions are lengthy and need simplification.
- - `abstract` and `links` generally do not need modification.
- - `aliasFunctionName` is optional; most formulas do not need to be filled (or can be set for aliases in specific countries). Currently, there is no documentation for formula aliases. Currently I have found a function translation plug-in that may provide similar functions [Excel Functions Translator](https://support.microsoft.com/en-us/office/excel-functions-translator-f262d0c0-991c-485b-89b6-32cc8d326889)
- - `functionParameter` needs a name for each parameter. We recommend varying names based on the parameter's meaning, e.g., use `number` for a numeric parameter (if there is only one) or `number1`, `number2` for multiple numeric parameters. Use `range` for a range, `criteria` for conditions, and `sumRange` for the sum range, use `camelCase`. For specific parameter content, the English format of `name` uses the underlined format `sum_range`, other languages use the translated text, and `detail` uses all translations.
- - Some Chinese translations in the Office function documentation are machine-translated and may be unclear. Modify as needed. For example, `单元格参考` (Cell Reference) should be translated as `单元格引用`. Numeric type parameters are uniformly translated as: `数值`.
- - Do not end `abstract` with a period (used in the search list when users input cells), but end `description` and `detail` with a period (used in descriptions).
- - Capitalize the first letter of English sentences.
- - Ensure that all existing internationalization files are filled. Currently, there are only Chinese, English, and Japanese translations (languages can be switched at the bottom of the Excel introduction page).
-
-3. Formula Descriptions
-
- `SUMIF` belongs to the `math` category, and the description is in [packages/sheets-formula/src/services/function-list/math.ts](https://github.com/dream-num/univer/blob/dev/packages/sheets-formula/src/services/function-list/math.ts), which manages all functions in the `math` category.
-
- Most function names already have basic description structure. It is recommended to modify them based on this foundation. If a function is not present, add it to the end.
-
- Requirements:
-
- - Add the formula to the `FUNCTION_LIST_MATH` array. It is recommended to keep the order consistent with the internationalization file for easy management and retrieval.
- - Reference the previously defined `FUNCTION_NAMES_MATH` enum for the `functionName`.
- - `aliasFunctionName` is also optional; if there are no aliases in the internationalization file, you do not need to add them here.
- - Pay attention to the correspondence between internationalization fields and function and parameter names.
- - Modify function parameter information, including the `example` parameter example (e.g., for a range, use `"A1:A20"`; for conditions, use `">5"`), the `require` parameter (1 for required, 0 for optional), and the `repeat` parameter (1 for allowed, 0 for not allowed). For detailed information, refer to the interface [IFunctionParam](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/basics/function.ts).
-
-4. Formula Algorithm
-
- Location: [packages/engine-formula/src/functions/math/sumif/index.ts](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/functions/math/sumif/index.ts).
-
- Create a new formula folder under the classification folder of the current formula. The folder name is the same as the formula, named with `kebab-case`, one folder for each formula. Then create a new `index.ts` file to write the formula algorithm. The name of the formula `class` adopts `PascalCase`. The formula is considered to be one word, and the formula with `_` or `.` is considered to be two words such as
-
- - `SUMIF` => folder `sumif`, class `Sumif`
- - `NETWORKDAYS.INTL` => folder `networkdays-intl`, class `NetworkdaysIntl`
- - `ARRAY_CONSTRAIN` => folder `array-constrain`, class `ArrayConstrain`
-
- Create a `__tests__` folder at the same level to write unit tests. After writing, remember to add the formula algorithm and function name mapping in the `function-map` file in the category directory to register the formula algorithm.
-
- Location: [packages/engine-formula/src/functions/math/function-map.ts](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/functions/math/function-map.ts).
-
-5. Unit Tests
-
- Location: [packages/engine-formula/src/functions/math/sumif/\_\_tests\_\_/index.spec.ts](https://github.com/dream-num/univer/blob/dev/packages/engine-formula/src/functions/math/sumif/__tests__/index.spec.ts)
-
- Note:
-
- - Supplement `sheetData` according to the formula's calculation needs, construct `cellData` based on the calculated data, and determine `rowCount` and `columnCount`.
- - Manually initialize the formula with `new Sumif(FUNCTION_NAMES_MATH.SUMIF)`.
- - Manually build the formula parameters for each test, and execute `calculate` at the end.
- - Single formula tests are generally used for testing the algorithm of the current formula. If testing nested formulas with multiple formulas is needed, manually nest them or go to the `/packages/engine-formula/src/functions/__tests__` directory to execute complex nested formulas.
-
-6. Functional Tests
-
- Start Univer in development mode, test formulas on the interface, and preconstruct data.
-
- - In any blank cell, enter `=sumif`. Expect a search prompt list to appear.
- - After selecting `SUMIF` or entering `=sumif(`, trigger the formula details popup and carefully check the contents.
- - Select the data range, trigger the calculation, and check if the formula calculation result is correct.
-
-### Considerations for Formula Implementation
-
-- For most formula rules, please refer to the latest version of Excel. If there are any unreasonable rules, please refer to Google Sheets.
-- The input and output parameters of any formula can be `A1`, `A1:B10`, and the cell content may also be numbers, strings, Boolean values, empty cells, error values, arrays, etc., although the formula tutorial explains In order to identify fixed data types, the program implementation needs to be compatible. When researching Excel, consider all cases, such as `=SIN(A1:B10)`, which expands to the calculated range.
- - For example, the `XLOOKUP` function requires at least one of the rows or columns of its two inputs to be of equal size for matrix calculation.
- - For example, the `SUMIF` function, although commonly used for summation, can expand based on the second parameter.
- ![sumif array](./assets/sumif-array.png)
- ![sumif array result](./assets/sumif-array-result.png)
- - Excel formula calculation is becoming more like numpy, for example:
- ![numpy](./assets/numpy.png)
-- For numerical calculations in formulas, use built-in methods and try to avoid obtaining values for manual calculation. Because formula parameters can be values, arrays, or references. You can refer to existing `sum` and `minus` functions.
-- Precision issues: The formula introduces `big.js`, and using built-in methods will call this library. However, it is nearly 100 times slower than native calculations. Therefore, for methods like `sin`, it is advisable to use native implementations.
-- For custom calculations, use the `product` function, suitable for calculating two input parameters. Call `map` to iterate over the values for changes to a parameter's own values.
-- Formula algorithm supports two configurations `needsExpandParams` and `needsReferenceObject`
- - `needsExpandParams`: Whether the function needs to expand parameters, mainly handles situations where the `LOOKUP` function needs to handle vectors of different sizes
- - `needsReferenceObject`: Whether the function needs to pass in a reference object. After setting, `BaseReferenceObject` will not be converted into `ArrayValueObject` but will be passed directly into the formula algorithm, such as the `OFFSET` function
-- Formula calculation errors will return fixed types of errors, such as `#NAME?`, `#VALUE!`, which need to be aligned with Excel, because there are functions `ISERR`, `ISNA`, etc. that determine the error type. If the type is not specified correctly, the result will be It may be different.
-- In the formula algorithm, even if it is a required parameter, it is necessary to intercept the case of `null` and return the error `#N/A`, because the user may not enter any parameters. This behavior will be intercepted in Excel and `#N/A` will be returned in Google Sheets. We refer to Google Sheets.
-
-### Formula Basic Tools
-
-1. `ValueObjectFactory` is used to automatically recognize parameter formats and create a parameter instance. Use `RangeReferenceObject` to create parameter instances for range-type data.
-2. The array `toArrayValueObject` can be operated directly with values to get a new array.
+- [Register formula using Facade API](https://univer.ai/guides/facade/general/#register-formula)
+- [Custom Formula](https://univer.ai/guides/customization/formula/)
diff --git a/packages/sheets-formula/src/controllers/formula-alert.controller.ts b/packages/sheets-formula/src/controllers/formula-alert.controller.ts
new file mode 100644
index 0000000000..18387436c3
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/formula-alert.controller.ts
@@ -0,0 +1,99 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { Disposable, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, UniverInstanceType } from '@univerjs/core';
+import { ErrorType } from '@univerjs/engine-formula';
+import { CellAlertManagerService, CellAlertType, HoverManagerService } from '@univerjs/sheets-ui';
+import { Inject } from '@wendellhu/redi';
+import { extractFormulaError } from './utils/utils';
+
+const ALERT_KEY = 'SHEET_FORMULA_ALERT';
+
+const ErrorTypeToMessageMap = {
+ [ErrorType.DIV_BY_ZERO]: 'divByZero',
+ [ErrorType.NAME]: 'name',
+ [ErrorType.VALUE]: 'value',
+ [ErrorType.NUM]: 'num',
+ [ErrorType.NA]: 'na',
+ [ErrorType.CYCLE]: 'cycle',
+ [ErrorType.REF]: 'ref',
+ [ErrorType.SPILL]: 'spill',
+ [ErrorType.CALC]: 'calc',
+ [ErrorType.ERROR]: 'error',
+ [ErrorType.CONNECT]: 'connect',
+ [ErrorType.NULL]: 'null',
+};
+
+@OnLifecycle(LifecycleStages.Rendered, FormulaAlertController)
+export class FormulaAlertController extends Disposable {
+ constructor(
+ @Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,
+ @Inject(CellAlertManagerService) private readonly _cellAlertManagerService: CellAlertManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+ this._init();
+ }
+
+ private _init() {
+ this._initCellAlertPopup();
+ }
+
+ private _initCellAlertPopup() {
+ this.disposeWithMe(this._hoverManagerService.currentCell$.subscribe((cellPos) => {
+ if (cellPos) {
+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const worksheet = workbook.getActiveSheet();
+ const cellData = worksheet.getCell(cellPos.location.row, cellPos.location.col);
+
+ if (cellData) {
+ const errorType = extractFormulaError(cellData);
+
+ if (!errorType) {
+ return;
+ }
+
+ 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
+ ) {
+ return;
+ }
+
+ this._cellAlertManagerService.showAlert({
+ type: CellAlertType.ERROR,
+ title: this._localeService.t('formula.error.title'),
+ message: this._localeService.t(`formula.error.${ErrorTypeToMessageMap[errorType]}`),
+ location: cellPos.location,
+ width: 200,
+ height: 74,
+ key: ALERT_KEY,
+ });
+ return;
+ }
+ }
+
+ this._cellAlertManagerService.removeAlert(ALERT_KEY);
+ }));
+ }
+}
diff --git a/packages/sheets-formula/src/controllers/formula-render.controller.ts b/packages/sheets-formula/src/controllers/formula-render.controller.ts
new file mode 100644
index 0000000000..0b3620b8ff
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/formula-render.controller.ts
@@ -0,0 +1,72 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
+import { extractFormulaError } from './utils/utils';
+
+@OnLifecycle(LifecycleStages.Rendered, FormulaRenderController)
+export class FormulaRenderController extends RxDisposable {
+ constructor(
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService) {
+ super();
+ this._init();
+ }
+
+ private _init() {
+ this._initViewModelIntercept();
+ }
+
+ private _initViewModelIntercept() {
+ const FORMULA_ERROR_MARK = {
+ tl: {
+ size: 6,
+ color: '#409f11',
+ },
+ };
+
+ this.disposeWithMe(
+ this._sheetInterceptorService.intercept(
+ INTERCEPTOR_POINT.CELL_CONTENT,
+ {
+ handler: (cell, pos, next) => {
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
+ if (!skeleton) {
+ return next(cell);
+ }
+
+ const errorType = extractFormulaError(cell);
+
+ if (!errorType) {
+ return next(cell);
+ }
+
+ return next({
+ ...cell,
+ markers: {
+ ...cell?.markers,
+ ...FORMULA_ERROR_MARK,
+ },
+ });
+ },
+ }
+ )
+ );
+ }
+}
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index bf8911d2dc..a9b35a8642 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -226,7 +226,8 @@ export class TriggerCalculationController extends Disposable {
* Assignment operation after formula calculation.
*/
const debouncedPushTask = throttle(this._pushTask.bind(this), 300);
- let startDependencyTimer: NodeJS.Timeout | null;
+ let startDependencyTimer: NodeJS.Timeout | null = null;
+ let needStartProgress = false;
let formulaInsertTaskCount = false;
let arrayFormulaInsertTaskCount = false;
@@ -248,22 +249,29 @@ export class TriggerCalculationController extends Disposable {
} = params.stageInfo;
if (stage === FormulaExecuteStageType.START_DEPENDENCY) {
+ // Clear any existing timer to prevent duplicate executions
+ if (startDependencyTimer !== null) {
+ clearTimeout(startDependencyTimer);
+ startDependencyTimer = null;
+ }
+
// If the total calculation time exceeds 1s, a progress bar is displayed. The first progress shows 5%
startDependencyTimer = setTimeout(() => {
// Ignore progress deviations, and finally the complete method ensures the correct completion of the progress
this._progressService.insertTaskCount(100);
this._progressService.pushTask({ count: 5 });
+ needStartProgress = true;
startDependencyTimer = null;
}, 1000);
} else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING) {
- if (!formulaInsertTaskCount && !startDependencyTimer) {
+ if (!formulaInsertTaskCount && needStartProgress) {
formulaInsertTaskCount = true;
this._progressService.insertTaskCount(totalFormulasToCalculate);
}
debouncedPushTask(completedFormulasCount);
} else if (stage === FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA) {
- if (!arrayFormulaInsertTaskCount && !startDependencyTimer) {
+ if (!arrayFormulaInsertTaskCount && needStartProgress) {
arrayFormulaInsertTaskCount = true;
this._progressService.insertTaskCount(totalArrayFormulasToCalculate);
}
@@ -319,6 +327,7 @@ export class TriggerCalculationController extends Disposable {
formulaInsertTaskCount = false;
arrayFormulaInsertTaskCount = false;
+ needStartProgress = false;
this._formulaCalculationDoneCount = 0;
}
diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..4bed0a5645
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/utils/__tests__/utils.spec.ts
@@ -0,0 +1,46 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { describe, expect, it } from 'vitest';
+
+import { ErrorType } from '@univerjs/engine-formula';
+import { extractFormulaError } from '../utils';
+
+describe('Test utils', () => {
+ it('Function extractFormulaError', () => {
+ expect(extractFormulaError({ v: ErrorType.DIV_BY_ZERO })).toBe(ErrorType.DIV_BY_ZERO);
+ expect(extractFormulaError({ v: ErrorType.NAME })).toBe(ErrorType.NAME);
+ expect(extractFormulaError({ v: ErrorType.VALUE })).toBe(ErrorType.VALUE);
+ expect(extractFormulaError({ v: ErrorType.NUM })).toBe(ErrorType.NUM);
+ expect(extractFormulaError({ v: ErrorType.NA })).toBe(ErrorType.NA);
+ expect(extractFormulaError({ v: ErrorType.CYCLE })).toBe(ErrorType.CYCLE);
+ expect(extractFormulaError({ v: ErrorType.REF })).toBe(ErrorType.REF);
+ expect(extractFormulaError({ v: ErrorType.SPILL })).toBe(ErrorType.SPILL);
+ expect(extractFormulaError({ v: ErrorType.CALC })).toBe(ErrorType.CALC);
+ expect(extractFormulaError({ v: ErrorType.ERROR })).toBe(ErrorType.ERROR);
+ expect(extractFormulaError({ v: ErrorType.CONNECT })).toBe(ErrorType.CONNECT);
+ expect(extractFormulaError({ v: ErrorType.NULL })).toBe(ErrorType.NULL);
+
+ expect(extractFormulaError({ f: '=SUM(1)' })).toBeNull();
+ expect(extractFormulaError({ si: 'id1' })).toBeNull();
+ expect(extractFormulaError({ p: null })).toBeNull();
+ expect(extractFormulaError({ v: 'test' })).toBeNull();
+ expect(extractFormulaError({ v: 1 })).toBeNull();
+ expect(extractFormulaError({})).toBeNull();
+ expect(extractFormulaError(null)).toBeNull();
+ expect(extractFormulaError(undefined)).toBeNull();
+ });
+});
diff --git a/packages/sheets-formula/src/controllers/utils/utils.ts b/packages/sheets-formula/src/controllers/utils/utils.ts
index 16173cb841..9878071af6 100644
--- a/packages/sheets-formula/src/controllers/utils/utils.ts
+++ b/packages/sheets-formula/src/controllers/utils/utils.ts
@@ -14,8 +14,10 @@
* limitations under the License.
*/
-import type { IContextService } from '@univerjs/core';
+import type { ICellData, IContextService, Nullable } from '@univerjs/core';
import { FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE } from '@univerjs/core';
+import type { ErrorType } from '@univerjs/engine-formula';
+import { ERROR_TYPE_SET } from '@univerjs/engine-formula';
export function whenEditorStandalone(contextService: IContextService) {
return (
@@ -24,3 +26,16 @@ export function whenEditorStandalone(contextService: IContextService) {
contextService.getContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)
);
}
+
+/**
+ * Extract the formula error from the cell
+ * @param cell
+ * @returns
+ */
+export function extractFormulaError(cell: Nullable<ICellData>) {
+ if (typeof cell?.v === 'string' && ERROR_TYPE_SET.has(cell.v as ErrorType)) {
+ return cell.v as ErrorType;
+ }
+
+ return null;
+}
diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.ts
index c19103d5ab..e96bc23c0b 100644
--- a/packages/sheets-formula/src/formula-ui-plugin.ts
+++ b/packages/sheets-formula/src/formula-ui-plugin.ts
@@ -41,6 +41,8 @@ import { IRegisterFunctionService, RegisterFunctionService } from './services/re
import { DefinedNameController } from './controllers/defined-name.controller';
import { FormulaRefRangeService } from './services/formula-ref-range.service';
import { RegisterOtherFormulaService } from './services/register-other-formula.service';
+import { FormulaAlertController } from './controllers/formula-alert.controller';
+import { FormulaRenderController } from './controllers/formula-render.controller';
/**
* The configuration of the formula UI plugin.
@@ -92,6 +94,8 @@ export class UniverSheetsFormulaPlugin extends Plugin {
[FormulaEditorShowController],
[ActiveDirtyController],
[DefinedNameController],
+ [FormulaRenderController],
+ [FormulaAlertController],
];
dependencies.forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/sheets-formula/src/locale/en-US.ts b/packages/sheets-formula/src/locale/en-US.ts
index 48b4b6e9c0..6e7c0a9201 100644
--- a/packages/sheets-formula/src/locale/en-US.ts
+++ b/packages/sheets-formula/src/locale/en-US.ts
@@ -64,6 +64,22 @@ export default {
required: 'Required.',
optional: 'Optional.',
},
+ error: {
+ title: 'Error',
+ divByZero: 'Divide by zero error',
+ name: 'Invalid name error',
+ value: 'Error in value',
+ num: 'Number error',
+ na: 'Value not available error',
+ cycle: 'Circular reference error',
+ ref: 'Invalid cell reference error',
+ spill: "Spill range isn't blank",
+ calc: 'Calculation error',
+ error: 'Error',
+ connect: 'Getting data',
+ null: 'Null Error',
+ },
+
functionType: {
financial: 'Financial',
date: 'Date & Time',
diff --git a/packages/sheets-formula/src/locale/zh-CN.ts b/packages/sheets-formula/src/locale/zh-CN.ts
index 8ef466ed79..bdf45f40ad 100644
--- a/packages/sheets-formula/src/locale/zh-CN.ts
+++ b/packages/sheets-formula/src/locale/zh-CN.ts
@@ -66,6 +66,22 @@ export default {
optional: '可选。',
},
+ error: {
+ title: '错误',
+ divByZero: '除数为零',
+ name: '无效名称',
+ value: '值中的错误',
+ num: '数值错误',
+ na: '值不可用',
+ cycle: '循环引用',
+ ref: '无效的单元格引用',
+ spill: '溢出区域不是空白区域',
+ calc: '计算错误',
+ error: '错误',
+ connect: '正在连接中',
+ null: '空值错误',
+ },
+
functionType: {
financial: '财务',
date: '日期与时间',
diff --git a/packages/sheets-formula/src/services/description.service.ts b/packages/sheets-formula/src/services/description.service.ts
index a26ca285c9..bcd7115213 100644
--- a/packages/sheets-formula/src/services/description.service.ts
+++ b/packages/sheets-formula/src/services/description.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { LocaleService } from '@univerjs/core';
+import { LocaleService, toDisposable } from '@univerjs/core';
import type { IFunctionInfo, IFunctionNames } from '@univerjs/engine-formula';
import {
functionArray,
@@ -87,7 +87,7 @@ export interface IDescriptionService {
* register descriptions
* @param functionList
*/
- registerDescriptions(functionList: IFunctionInfo[]): void;
+ registerDescriptions(functionList: IFunctionInfo[]): IDisposable;
/**
* unregister descriptions
@@ -186,9 +186,14 @@ export class DescriptionService implements IDescriptionService, IDisposable {
return searchList;
}
- registerDescriptions(description: IFunctionInfo[]) {
+ registerDescriptions(description: IFunctionInfo[]): IDisposable {
this._descriptions = this._descriptions.concat(description);
this._registerDescriptions();
+
+ return toDisposable(() => {
+ const functionNames = description.map((item) => item.functionName);
+ this.unregisterDescriptions(functionNames);
+ });
}
unregisterDescriptions(functionNames: string[]) {
diff --git a/packages/sheets-formula/src/services/formula-custom-function.service.ts b/packages/sheets-formula/src/services/formula-custom-function.service.ts
index c38ec57740..570903cb9b 100644
--- a/packages/sheets-formula/src/services/formula-custom-function.service.ts
+++ b/packages/sheets-formula/src/services/formula-custom-function.service.ts
@@ -14,15 +14,17 @@
* limitations under the License.
*/
-import { Disposable, ICommandService } from '@univerjs/core';
+import { Disposable, ICommandService, toDisposable } from '@univerjs/core';
import type { PrimitiveValueType } from '@univerjs/engine-formula';
import { RegisterFunctionMutation, UnregisterFunctionMutation } from '@univerjs/engine-formula';
+import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier } from '@wendellhu/redi';
export type IRegisterFunction = (
...arg: Array<PrimitiveValueType | PrimitiveValueType[][]>
) => PrimitiveValueType | PrimitiveValueType[][];
+// [[Function, FunctionName, Description]]
export type IRegisterFunctionList = [[IRegisterFunction, string, string?]];
export interface IFormulaCustomFunctionService {
@@ -30,9 +32,7 @@ export interface IFormulaCustomFunctionService {
* register descriptions
* @param functionList
*/
- registerFunctions(functionList: IRegisterFunctionList): void;
-
- unregisterFunctions(functionList: string[]): void;
+ registerFunctions(functionList: IRegisterFunctionList): IDisposable;
}
export const IFormulaCustomFunctionService = createIdentifier<IFormulaCustomFunctionService>(
@@ -44,8 +44,12 @@ export class FormulaCustomFunctionService extends Disposable implements IFormula
super();
}
- registerFunctions(functionList: IRegisterFunctionList) {
- const functions = functionList.map((func) => [func[0].toString(), func[1]]);
+ registerFunctions(functionList: IRegisterFunctionList): IDisposable {
+ const functionNameList: string[] = []; // used to unregister functions
+ const functions = functionList.map((func) => {
+ functionNameList.push(func[1]);
+ return [func[0].toString(), func[1]];
+ });
// Synchronous to worker
this._commandService.executeCommand(
@@ -57,18 +61,17 @@ export class FormulaCustomFunctionService extends Disposable implements IFormula
local: true,
}
);
- }
- unregisterFunctions(functionList: string[]) {
- // Synchronous to worker
- this._commandService.executeCommand(
- UnregisterFunctionMutation.id,
- {
- functions: functionList,
- },
- {
- local: true,
- }
- );
+ return toDisposable(() => {
+ this._commandService.executeCommand(
+ UnregisterFunctionMutation.id,
+ {
+ functions: functionNameList,
+ },
+ {
+ local: true,
+ }
+ );
+ });
}
}
diff --git a/packages/sheets-formula/src/services/register-function.service.ts b/packages/sheets-formula/src/services/register-function.service.ts
index 0191adcc87..21df441278 100644
--- a/packages/sheets-formula/src/services/register-function.service.ts
+++ b/packages/sheets-formula/src/services/register-function.service.ts
@@ -15,9 +15,10 @@
*/
import type { ILocales } from '@univerjs/core';
-import { Disposable, LocaleService } from '@univerjs/core';
+import { Disposable, LocaleService, toDisposable } from '@univerjs/core';
import type { IFunctionInfo } from '@univerjs/engine-formula';
import { FunctionType, IFunctionService } from '@univerjs/engine-formula';
+import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject } from '@wendellhu/redi';
import { IDescriptionService } from './description.service';
@@ -64,9 +65,7 @@ export interface IRegisterFunctionService {
* register descriptions
* @param functionList
*/
- registerFunctions(params: IRegisterFunctionParams): void;
-
- unregisterFunctions(params: IUnregisterFunctionParams): void;
+ registerFunctions(params: IRegisterFunctionParams): IDisposable;
}
export const IRegisterFunctionService = createIdentifier<IRegisterFunctionService>(
@@ -84,17 +83,19 @@ export class RegisterFunctionService extends Disposable implements IRegisterFunc
super();
}
- registerFunctions(params: IRegisterFunctionParams) {
+ registerFunctions(params: IRegisterFunctionParams): IDisposable {
const { locales, description, calculate } = params;
// i18n
if (locales) {
+ // dispose is not supported yet
this._localeService.load(locales);
}
+ let descriptionDisposable: IDisposable;
// description
if (description) {
- this._descriptionService.registerDescriptions(description);
+ descriptionDisposable = this._descriptionService.registerDescriptions(description);
} else {
const descriptionList: IFunctionInfo[] = calculate.map(([func, functionName, functionIntroduction]) => {
return {
@@ -106,21 +107,15 @@ export class RegisterFunctionService extends Disposable implements IRegisterFunc
};
});
- this._functionService.registerDescriptions(...descriptionList);
+ descriptionDisposable = this._functionService.registerDescriptions(...descriptionList);
}
// calculation
- this._formulaCustomFunctionService.registerFunctions(calculate);
- }
-
- unregisterFunctions(params: IUnregisterFunctionParams) {
- const { localeKeys, functionNames } = params;
-
- // remove i18n, @Dushusir: after localeService has remove method
- // localeKeys && this._localeService.remove(localeKeys);
-
- this._descriptionService.unregisterDescriptions(functionNames);
+ const functionsDisposable = this._formulaCustomFunctionService.registerFunctions(calculate);
- this._formulaCustomFunctionService.unregisterFunctions(functionNames);
+ return toDisposable(() => {
+ functionsDisposable.dispose();
+ descriptionDisposable.dispose();
+ });
}
}
diff --git a/packages/sheets-ui/src/controllers/force-string-render.controller.ts b/packages/sheets-ui/src/controllers/force-string-render.controller.ts
index fdee39451a..a1c2216dd8 100644
--- a/packages/sheets-ui/src/controllers/force-string-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/force-string-render.controller.ts
@@ -15,7 +15,7 @@
*/
-import { CellValueType, isRealNum, LifecycleStages, OnLifecycle, RxDisposable, ThemeService } from '@univerjs/core';
+import { CellValueType, isRealNum, LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
@@ -27,9 +27,7 @@ import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.
export class ForceStringRenderController extends RxDisposable {
constructor(
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
- @Inject(ThemeService) private readonly _themeService: ThemeService
- ) {
+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService) {
super();
this._init();
}
@@ -40,11 +38,10 @@ export class ForceStringRenderController extends RxDisposable {
private _initViewModelIntercept() {
- const color = this._themeService.getCurrentTheme().errorColor;
const FORCE_STRING_MARK = {
- tr: {
+ tl: {
size: 6,
- color,
+ color: '#409f11',
},
};