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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(formula): calculate formula,get locale from user config (#420)
Dushusir80411d25d888
diff --git a/examples/univer-sheet-ts/src/locales.ts b/examples/univer-sheet-ts/src/locales.tsindex 4abbfc57a5..7dc4d4d8c1 100644--- a/examples/univer-sheet-ts/src/locales.ts+++ b/examples/univer-sheet-ts/src/locales.ts@@ -1,6 +1,7 @@import DocPluginZhCN from '@univerjs/base-docs/locale/zh-CN';import SheetPluginZhCN from '@univerjs/base-sheets/locale/zh-CN';import BaseUiZhCN from '@univerjs/base-ui/locale/zh-CN';+import { Tools } from '@univerjs/core';import DeisgnZH from '@univerjs/design/locale/zh-CN';import SheetDebuggerPluginZhCN from '@univerjs/sheets-plugin-debugger/locale/zh-CN';import FindPluginZhCN from '@univerjs/sheets-plugin-find/locale/zh-CN';@@ -10,6 +11,42 @@ import NumberfmtPluginZhCN from '@univerjs/sheets-plugin-numfmt/locale/zh-CN';import DocUIPluginZhCN from '@univerjs/ui-plugin-docs/locale/zh-CN';import SheetUIPluginZhCN from '@univerjs/ui-plugin-sheets/locale/zh-CN';+// TODO@Dushusir: add custom formula info for test, after formula developed, remove this+const customFormulaZhCN = {+ formula: {+ functionList: {+ TANH: {+ description: '返回给定实数的双曲正切值。',+ abstract: '返回给定实数的双曲正切值。',+ functionParameter: {+ value: {+ name: '值',+ detail: '要计算其双曲正切值的实数。',+ },+ },+ },+ },+ },+};+const customFormulaEnUS = {+ formula: {+ functionList: {+ TANH: {+ description: 'Returns the hyperbolic tangent of any real number.',+ abstract: 'Hyperbolic tangent of any real number.',+ functionParameter: {+ value: {+ name: 'value',+ detail: 'Any real value to calculate the hyperbolic tangent of.',+ },+ },+ },+ },+ },+};++const FormulaPluginZhCNMerged = Tools.deepMerge(FormulaPluginZhCN, customFormulaZhCN);+export const locales = {zhCN: {...DocPluginZhCN,@@ -17,11 +54,14 @@ export const locales = {...FindPluginZhCN,...ImportXlsxPluginZhCN,...NumberfmtPluginZhCN,- ...FormulaPluginZhCN,+ ...FormulaPluginZhCNMerged,...DocUIPluginZhCN,...SheetUIPluginZhCN,...SheetDebuggerPluginZhCN,...BaseUiZhCN,...DeisgnZH,},+ enUS: {+ ...customFormulaEnUS,+ },};diff --git a/packages/base-formula-engine/src/index.ts b/packages/base-formula-engine/src/index.tsindex e0cd8acca7..021e015d03 100644--- a/packages/base-formula-engine/src/index.ts+++ b/packages/base-formula-engine/src/index.ts@@ -2,6 +2,7 @@ export type {ArrayFormulaDataType,IFormulaData,IFormulaDataItem,+ IFormulaDatasetConfig,ISheetData,IUnitData,IUnitSheetNameMap,diff --git a/packages/core/src/services/context/context.ts b/packages/core/src/services/context/context.tsindex facba5b624..4dc59d670f 100644--- a/packages/core/src/services/context/context.ts+++ b/packages/core/src/services/context/context.ts@@ -3,4 +3,4 @@ export const FOCUSING_DOC = 'FOCUSING_DOC';export const FOCUSING_SLIDE = 'FOCUSING_SLIDE';export const FOCUSING_EDITOR_BUT_HIDDEN = 'FOCUSING_EDITOR_BUT_HIDDEN';export const FOCUSING_EDITOR = 'FOCUSING_EDITOR';-export const FOCUSING_EDITOR_FORMULA = 'FOCUSING_EDITOR_FORMULA';+export const FOCUSING_EDITOR_INPUT_FORMULA = 'FOCUSING_EDITOR_INPUT_FORMULA';diff --git a/packages/sheets-plugin-formula/package.json b/packages/sheets-plugin-formula/package.jsonindex cb3d386bfc..063eae27e4 100644--- a/packages/sheets-plugin-formula/package.json+++ b/packages/sheets-plugin-formula/package.json@@ -21,6 +21,7 @@"scripts": {},"dependencies": {"@univerjs/base-docs": "workspace:*",+ "@univerjs/base-formula-engine": "workspace:*","@univerjs/base-render": "workspace:*","@univerjs/base-sheets": "workspace:*","@univerjs/base-ui": "workspace:*",diff --git a/packages/sheets-plugin-formula/src/commands/mutations/set-formula-data.mutation.ts b/packages/sheets-plugin-formula/src/commands/mutations/set-formula-data.mutation.tsnew file mode 100644index 0000000000..fcc1558891--- /dev/null+++ b/packages/sheets-plugin-formula/src/commands/mutations/set-formula-data.mutation.ts@@ -0,0 +1,19 @@+import { IFormulaData } from '@univerjs/base-formula-engine';+import { CommandType, IMutation } from '@univerjs/core';+import { IAccessor } from '@wendellhu/redi';++import { FormulaDataModel } from '../../models/formula-data.model';++export interface ISetFormulaDataMutationParams {+ formulaData: IFormulaData;+}++export const SetFormulaDataMutation: IMutation<ISetFormulaDataMutationParams> = {+ id: 'formula.mutation.set-formula-data',+ type: CommandType.MUTATION,+ handler: (accessor: IAccessor, params: ISetFormulaDataMutationParams) => {+ const formulaDataModel = accessor.get(FormulaDataModel);+ formulaDataModel.setFormulaData(params.formulaData);+ return true;+ },+};diff --git a/packages/sheets-plugin-formula/src/commands/operations/editor-formula.operation.ts b/packages/sheets-plugin-formula/src/commands/operations/editor-formula.operation.tsindex 3067da9ad8..c550d7251b 100644--- a/packages/sheets-plugin-formula/src/commands/operations/editor-formula.operation.ts+++ b/packages/sheets-plugin-formula/src/commands/operations/editor-formula.operation.ts@@ -6,13 +6,13 @@ import { CommandType, Direction, IOperation } from '@univerjs/core';import { IFormulaPromptService } from '../../services/prompt.service';-export interface ISetEditorFormulaOperationParam {+export interface ISelectEditorFormulaOperationParam {eventType: DeviceInputEventType;keycode?: KeyCode;}-export const SetEditorFormulaOperation: IOperation<ISetEditorFormulaOperationParam> = {- id: 'formula.operation.set-editor-formula-arrow',+export const SelectEditorFormluaOperation: IOperation<ISelectEditorFormulaOperationParam> = {+ id: 'formula.operation.select-editor-formula',type: CommandType.OPERATION,handler: (accessor, params) => {const { keycode } = params;diff --git a/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts b/packages/sheets-plugin-formula/src/controllers/calculate.controller.tsnew file mode 100644index 0000000000..97ccc2dbe3--- /dev/null+++ b/packages/sheets-plugin-formula/src/controllers/calculate.controller.ts@@ -0,0 +1,216 @@+import { FormulaEngineService, IFormulaData, ISheetData } from '@univerjs/base-formula-engine';+import { ISetRangeValuesMutationParams, SetRangeValuesMutation } from '@univerjs/base-sheets';+import {+ Disposable,+ ICommandInfo,+ ICommandService,+ IRange,+ isFormulaString,+ IUnitRange,+ IUniverInstanceService,+ LifecycleStages,+ Nullable,+ ObjectMatrix,+ OnLifecycle,+ Tools,+} from '@univerjs/core';+import { Inject } from '@wendellhu/redi';++import { ISetFormulaDataMutationParams, SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';+import { FormulaDataModel } from '../models/formula-data.model';++@OnLifecycle(LifecycleStages.Starting, CalculateController)+export class CalculateController extends Disposable {+ constructor(+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._commandExecutedListener();+ }++ private _commandExecutedListener() {+ // TODO@Dushusir: sheet rename+ const updateCommandList = [SetRangeValuesMutation.id];++ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (!updateCommandList.includes(command.id)) {+ return;+ }++ this._calculate(command as ICommandInfo<ISetRangeValuesMutationParams>);+ })+ );+ }++ private _calculate(command: ICommandInfo<ISetRangeValuesMutationParams>) {+ const { params } = command;+ if (!params) return;++ const { range, worksheetId: sheetId, workbookId: unitId, cellValue } = params;+ if (cellValue == null) return;++ const formulaData = Tools.deepClone(this._formulaDataModel.getFormulaData());++ const unitRange: IUnitRange[] = [];+ let isCalculate = false;++ if (!formulaData[unitId]) {+ formulaData[unitId] = {};+ }+ if (!formulaData[unitId][sheetId]) {+ formulaData[unitId][sheetId] = {};+ }++ const cellData = new ObjectMatrix(formulaData[unitId][sheetId]);+ const rangeMatrix = new ObjectMatrix(cellValue);++ let isArrayFormula = false;+ // update formula string,Any modification to cellData will be linked to formulaData+ rangeMatrix.forValue((r, c, cell) => {+ const arrayFormCellRangeData = this._checkArrayFormulaValue(r, c);+ const formulaString = cell?.m;+ if (arrayFormCellRangeData && formulaString === '') {+ isArrayFormula = true;+ isCalculate = true;++ unitRange.push({ unitId, sheetId, range: arrayFormCellRangeData });+ } else if (Tools.isStringNumber(formulaString)) {+ isCalculate = true;++ // if change formula to number, remove formula+ const formulaCell = cellData.getRow(r)?.get(c);+ if (formulaCell) {+ cellData.deleteValue(r, c);+ }+ } else if (isFormulaString(formulaString)) {+ isCalculate = true;+ cellData.setValue(r, c, { f: formulaString as string, si: '' });+ }+ });++ if (!isArrayFormula) {+ unitRange.push({ unitId, sheetId, range: rangeMatrix.getDataRange() });+ }++ if (unitRange.length === 0 || !isCalculate) return;++ this._executeFormula(unitId, formulaData, unitRange);+ }++ private _executeFormula(unitId: string, formulaData: IFormulaData, unitRange: IUnitRange[]) {+ const engine = this._formulaEngineService;+ const { sheetData, sheetNameMap } = this._getSheetData();+ // Add mutation after calculating the formula+ // TODO@Dushusir: use new service after engine refactor+ engine+ .execute(unitId, {+ unitData: {+ [unitId]: sheetData,+ },+ formulaData,+ sheetNameMap: {+ [unitId]: sheetNameMap,+ },+ forceCalculate: true,+ updateRangeList: unitRange,+ })+ .then((data) => {+ const { sheetData, arrayFormulaData } = data;++ if (!sheetData) {+ console.error('No sheetData from Formula Engine!');+ }++ if (arrayFormulaData) {+ // TODO@Dushusir: refresh array formula view+ this._formulaDataModel.setArrayFormulaData(arrayFormulaData);+ }++ const sheetIds = Object.keys(sheetData);++ // 1. Update each calculated value, possibly involving all cells+ const redoMutationsInfo: ICommandInfo[] = [];+ sheetIds.forEach((sheetId) => {+ const cellData = sheetData[sheetId];+ const setRangeValuesMutation: ISetRangeValuesMutationParams = {+ range: [],+ worksheetId: sheetId,+ workbookId: unitId,+ cellValue: cellData.getData(),+ };++ redoMutationsInfo.push({+ id: SetRangeValuesMutation.id,+ params: setRangeValuesMutation,+ });+ });++ // 2. Update formula data+ const setFormulaDataMutation: ISetFormulaDataMutationParams = {+ formulaData,+ };++ redoMutationsInfo.push({+ id: SetFormulaDataMutation.id,+ params: setFormulaDataMutation,+ });++ const result = redoMutationsInfo.every((m) => this._commandService.executeCommand(m.id, m.params));+ return result;+ });+ }++ private _checkArrayFormulaValue(row: number, column: number): Nullable<IRange> {+ let formula: Nullable<IRange>;+ const arrayFormulaData = this._formulaDataModel.getArrayFormulaData();++ if (!arrayFormulaData) return null;++ Object.keys(arrayFormulaData).forEach((sheetId) => {+ const sheetData = arrayFormulaData[sheetId];++ sheetData.forValue((rowIndex: number, columnIndex: number, value: IRange) => {+ const { startRow, startColumn, endRow, endColumn } = value;+ if (row >= startRow && row < endRow && column >= startColumn && column < endColumn) {+ formula = {+ startRow,+ endRow: startRow,+ startColumn,+ endColumn: startColumn,+ };+ return false;+ }+ });+ });++ return formula;+ }++ private _getSheetData() {+ const sheetData: ISheetData = {};+ const sheetNameMap: { [sheetName: string]: string } = {};+ this._currentUniverService+ .getCurrentUniverSheetInstance()+ .getSheets()+ .forEach((sheet) => {+ const sheetConfig = sheet.getConfig();+ sheetData[sheet.getSheetId()] = {+ cellData: new ObjectMatrix(sheetConfig.cellData),+ rowCount: sheetConfig.rowCount,+ columnCount: sheetConfig.columnCount,+ };+ sheetNameMap[sheet.getName()] = sheet.getSheetId();+ });++ return { sheetData, sheetNameMap };+ }+}diff --git a/packages/sheets-plugin-formula/src/controllers/formula.controller.ts b/packages/sheets-plugin-formula/src/controllers/formula.controller.tsindex 9592a83645..9b17435050 100644--- a/packages/sheets-plugin-formula/src/controllers/formula.controller.ts+++ b/packages/sheets-plugin-formula/src/controllers/formula.controller.ts@@ -3,7 +3,8 @@ import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univimport { Inject, Injector } from '@wendellhu/redi';import { connectInjector } from '@wendellhu/redi/react-bindings';-import { SetEditorFormulaOperation } from '../commands/operations/editor-formula.operation';+import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';+import { SelectEditorFormluaOperation } from '../commands/operations/editor-formula.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';@@ -45,7 +46,8 @@ export class FormulaController extends Disposable {MoreFunctionsOperation,SearchFunctionOperation,HelpFunctionOperation,- SetEditorFormulaOperation,+ SelectEditorFormluaOperation,+ SetFormulaDataMutation,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}diff --git a/packages/sheets-plugin-formula/src/controllers/prompt.controller.ts b/packages/sheets-plugin-formula/src/controllers/prompt.controller.tsindex 969d0e1837..2fc9c837b4 100644--- a/packages/sheets-plugin-formula/src/controllers/prompt.controller.ts+++ b/packages/sheets-plugin-formula/src/controllers/prompt.controller.ts@@ -1,20 +1,31 @@import { TextSelectionManagerService } from '@univerjs/base-docs';-import { IDesktopUIController, IMenuService, IUIController } from '@univerjs/base-ui';-import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';-import { Inject, Injector } from '@wendellhu/redi';+import {+ Disposable,+ FOCUSING_EDITOR_INPUT_FORMULA,+ ICommandService,+ IContextService,+ isFormulaString,+ LifecycleStages,+ LocaleService,+ OnLifecycle,+} from '@univerjs/core';+import { EditorBridgeService, IEditorBridgeService } from '@univerjs/ui-plugin-sheets';+import { Inject } from '@wendellhu/redi';import { HelpFunctionOperation } from '../commands/operations/help-function.operation';import { SearchFunctionOperation } from '../commands/operations/search-function.operation';-import { IFormulaPromptService } from '../services/prompt.service';+import { FUNCTION_LIST } from '../services/function-list';+import { IFormulaPromptService, ISearchItem } from '../services/prompt.service';+import { getFunctionName } from './util';@OnLifecycle(LifecycleStages.Starting, PromptController)export class PromptController extends Disposable {constructor(- @Inject(Injector) private readonly _injector: Injector,- @IMenuService private readonly _menuService: IMenuService,@ICommandService private readonly _commandService: ICommandService,- @IUIController private readonly _uiController: IDesktopUIController,+ @Inject(LocaleService) private readonly _localeService: LocaleService,+ @IContextService private readonly _contextService: IContextService,@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,+ @Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,@Inject(IFormulaPromptService) private readonly _formulaPromptService: IFormulaPromptService) {super();@@ -28,26 +39,107 @@ export class PromptController extends Disposable {}private _initialCursorSync() {- this._textSelectionManagerService.textSelectionInfo$.subscribe((text) => {+ this._textSelectionManagerService.textSelectionInfo$.subscribe(() => {+ const currentInputValue = this._getCurrentCellValue();+// TODO@Dushusir: use real text info- // return;- const visible = Math.random() > 0.5;- const searchText = Math.random() > 0.5 ? 'SUMIF' : 'TAN';- // const searchText = 'SUMIF';- const paramIndex = Math.random() > 0.5 ? 0 : 1;+ const input = this._getCellEditInput(currentInputValue || '');+ if (!input) return;++ const { visibleSearch, visibleHelp, searchText, paramIndex, searchList, functionInfo } = input;++ if (visibleSearch) {+ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);+ } else if (visibleHelp) {+ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);+ } else {+ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);+ }- this._commandService.executeCommand(SearchFunctionOperation.id, { visible, searchText });+ this._commandService.executeCommand(SearchFunctionOperation.id, {+ visible: visibleSearch,+ searchText,+ searchList,+ });this._commandService.executeCommand(HelpFunctionOperation.id, {- visible: !visible,- functionName: searchText,+ visible: visibleHelp,paramIndex,+ functionInfo,});});}+ private _getCurrentCellValue() {+ const state = this._editorBridgeService.getState();+ let currentInputValue = state?.documentLayoutObject?.documentModel?.snapshot?.body?.dataStream;++ if (currentInputValue) {+ currentInputValue = currentInputValue.split('\r\n')[0].toLocaleUpperCase();+ }++ return currentInputValue;+ }++ // TODO@Dushusir: remove after use real text info+ private _getCellEditInput(currentInputValue: string) {+ if (isFormulaString(currentInputValue)) {+ const searchText = currentInputValue.substring(1);++ // TODO@Dushusir: remove after use real text info+ const matchList = ['SUMIF', 'TAN', 'TANH'];++ // help function+ if (matchList.includes(searchText)) {+ const paramIndex = Math.random() > 0.5 ? 0 : 1;++ const functionInfo = this._getFunctionInfo(searchText);++ return {+ visibleSearch: false,+ visibleHelp: !!functionInfo,+ searchText,+ paramIndex,+ functionInfo,+ };+ }++ const searchList = this._getSearchList(searchText);+ return {+ visibleSearch: searchList.length > 0,+ visibleHelp: false,+ searchText,+ paramIndex: 0,+ searchList,+ };+ }++ return {+ visibleSearch: false,+ visibleHelp: false,+ searchText: '',+ paramIndex: 0,+ };+ }+private _initAcceptFormula() {this._formulaPromptService.acceptFormulaName$.subscribe((name: string) => {console.log(`TODO: set ${name} to cell editor`);});}++ private _getSearchList(searchText: string) {+ const searchList: ISearchItem[] = [];+ FUNCTION_LIST.forEach((item) => {+ const functionName = getFunctionName(item, this._localeService);+ if (functionName.indexOf(searchText) > -1) {+ searchList.push({ name: functionName, desc: this._localeService.t(item.abstract) as string });+ }+ });++ return searchList;+ }++ private _getFunctionInfo(searchText: string) {+ return FUNCTION_LIST.find((item) => getFunctionName(item, this._localeService) === searchText);+ }}diff --git a/packages/sheets-plugin-formula/src/controllers/shortcuts/prompt.shortcut.ts b/packages/sheets-plugin-formula/src/controllers/shortcuts/prompt.shortcut.tsindex cad78b5596..53c49c06da 100644--- a/packages/sheets-plugin-formula/src/controllers/shortcuts/prompt.shortcut.ts+++ b/packages/sheets-plugin-formula/src/controllers/shortcuts/prompt.shortcut.ts@@ -1,8 +1,8 @@import { DeviceInputEventType } from '@univerjs/base-render';import { IShortcutItem, KeyCode } from '@univerjs/base-ui';+import { whenEditorInputFormulaActivated } from '@univerjs/ui-plugin-sheets';-import { SetEditorFormulaOperation } from '../../commands/operations/editor-formula.operation';-import { whenEditorFormulaActivated } from './utils';+import { SelectEditorFormluaOperation } from '../../commands/operations/editor-formula.operation';export const PROMPT_SELECTION_KEYCODE_LIST = [KeyCode.ARROW_DOWN,@@ -17,9 +17,9 @@ export function promptSelectionShortcutItem() {const shortcutList: IShortcutItem[] = [];for (const keycode of PROMPT_SELECTION_KEYCODE_LIST) {shortcutList.push({- id: SetEditorFormulaOperation.id,+ id: SelectEditorFormluaOperation.id,binding: keycode,- preconditions: (contextService) => whenEditorFormulaActivated(contextService),+ preconditions: (contextService) => whenEditorInputFormulaActivated(contextService),staticParameters: {eventType: DeviceInputEventType.Keyboard,keycode,diff --git a/packages/sheets-plugin-formula/src/controllers/shortcuts/utils.ts b/packages/sheets-plugin-formula/src/controllers/shortcuts/utils.tsdeleted file mode 100644index 7b8e04aba5..0000000000--- a/packages/sheets-plugin-formula/src/controllers/shortcuts/utils.ts+++ /dev/null@@ -1,6 +0,0 @@-import { FOCUSING_EDITOR, FOCUSING_EDITOR_FORMULA, IContextService } from '@univerjs/core';--export function whenEditorFormulaActivated(contextService: IContextService) {- // return contextService.getContextValue(FOCUSING_EDITOR);- return contextService.getContextValue(FOCUSING_EDITOR) && contextService.getContextValue(FOCUSING_EDITOR_FORMULA);-}diff --git a/packages/sheets-plugin-formula/src/controllers/util.ts b/packages/sheets-plugin-formula/src/controllers/util.tsnew file mode 100644index 0000000000..f0a4a7568b--- /dev/null+++ b/packages/sheets-plugin-formula/src/controllers/util.ts@@ -0,0 +1,18 @@+import { LocaleService } from '@univerjs/core';++import { IFunctionInfo } from '../services/function-list';++export function getFunctionName(item: IFunctionInfo, localeService: LocaleService) {+ let functionName = '';+ if (item.aliasFunctionName) {+ functionName = localeService.t(item.aliasFunctionName) as string;++ if (functionName === item.aliasFunctionName) {+ functionName = item.functionName;+ }+ } else {+ functionName = item.functionName;+ }++ return functionName;+}diff --git a/packages/sheets-plugin-formula/src/formula-plugin.ts b/packages/sheets-plugin-formula/src/formula-plugin.tsindex 640be02ed8..2f2c3edc94 100644--- a/packages/sheets-plugin-formula/src/formula-plugin.ts+++ b/packages/sheets-plugin-formula/src/formula-plugin.ts@@ -2,9 +2,11 @@ import { IUniverInstanceService, LocaleService, Plugin, PluginType } from '@univimport { Dependency, Inject, Injector } from '@wendellhu/redi';import { FORMULA_PLUGIN_NAME } from './common/plugin-name';+import { CalculateController } from './controllers/calculate.controller';import { FormulaController } from './controllers/formula.controller';import { PromptController } from './controllers/prompt.controller';import { enUS } from './locale';+import { FormulaDataModel, IFormulaConfig } from './models/formula-data.model';import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';export class FormulaPlugin extends Plugin {@@ -13,7 +15,7 @@ export class FormulaPlugin extends Plugin {private _formulaController!: FormulaController;constructor(- config: undefined,+ private _config: IFormulaConfig,@Inject(Injector) override readonly _injector: Injector,@Inject(LocaleService) private readonly _localeService: LocaleService,@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService@@ -27,11 +29,14 @@ export class FormulaPlugin extends Plugin {});const dependencies: Dependency[] = [+ // models+ [FormulaDataModel, { useFactory: () => this._injector.createInstance(FormulaDataModel, this._config) }],// services[IFormulaPromptService, { useClass: FormulaPromptService }],// controllers[FormulaController],[PromptController],+ [CalculateController],];dependencies.forEach((dependency) => this._injector.add(dependency));diff --git a/packages/sheets-plugin-formula/src/locale/en-US.ts b/packages/sheets-plugin-formula/src/locale/en-US.tsindex 2a1ad88658..32f9d77594 100644--- a/packages/sheets-plugin-formula/src/locale/en-US.ts+++ b/packages/sheets-plugin-formula/src/locale/en-US.ts@@ -11,9 +11,9 @@ export default {},functionList: {SUMIF: {- d: 'Returns a conditional sum across a range.',- a: 'A conditional sum across a range.',- p: {+ description: 'Returns a conditional sum across a range.',+ abstract: 'A conditional sum across a range.',+ functionParameter: {range: {name: 'range',detail: 'The range which is tested against `criterion`.',@@ -29,25 +29,25 @@ export default {},},TAN: {- d: 'Returns the tangent of an angle provided in radians.',- a: 'Tangent of an angle provided in radians.',- p: {+ description: 'Returns the tangent of an angle provided in radians.',+ abstract: 'Tangent of an angle provided in radians.',+ functionParameter: {angle: {name: 'angle',detail: 'The angle to find the tangent of, in radians.',},},},- TANH: {- d: 'Returns the hyperbolic tangent of any real number.',- a: 'Hyperbolic tangent of any real number.',- p: {- value: {- name: 'value',- detail: 'Any real value to calculate the hyperbolic tangent of.',- },- },- },+ // TANH: {+ // description: 'Returns the hyperbolic tangent of any real number.',+ // abstract: 'Hyperbolic tangent of any real number.',+ // functionParameter: {+ // value: {+ // name: 'value',+ // detail: 'Any real value to calculate the hyperbolic tangent of.',+ // },+ // },+ // },},formulaMore: {diff --git a/packages/sheets-plugin-formula/src/locale/zh-CN.ts b/packages/sheets-plugin-formula/src/locale/zh-CN.tsindex ccb0697304..b7abccee4c 100644--- a/packages/sheets-plugin-formula/src/locale/zh-CN.ts+++ b/packages/sheets-plugin-formula/src/locale/zh-CN.ts@@ -12,9 +12,9 @@ export default {functionList: {SUMIF: {- d: '对范围中符合指定条件的值求和。',- a: '对范围中符合指定条件的值求和。',- p: {+ description: '对范围中符合指定条件的值求和。',+ abstract: '对范围中符合指定条件的值求和。',+ functionParameter: {range: {name: '范围',detail: '要根据条件进行检测的范围。',@@ -30,25 +30,25 @@ export default {},},TAN: {- d: '返回已知角度的正切值。',- a: '返回已知角度的正切值。',- p: {+ description: '返回已知角度的正切值。',+ abstract: '返回已知角度的正切值。',+ functionParameter: {angle: {name: '角度',detail: '要求其正切值的角度,以弧度表示。',},},},- TANH: {- d: '返回给定实数的双曲正切值。',- a: '返回给定实数的双曲正切值。',- p: {- value: {- name: '值',- detail: '要计算其双曲正切值的实数。',- },- },- },+ // TANH: {+ // description: '返回给定实数的双曲正切值。',+ // abstract: '返回给定实数的双曲正切值。',+ // functionParameter: {+ // value: {+ // name: '值',+ // detail: '要计算其双曲正切值的实数。',+ // },+ // },+ // },},formulaMore: {diff --git a/packages/sheets-plugin-formula/src/models/formula-data.model.ts b/packages/sheets-plugin-formula/src/models/formula-data.model.tsnew file mode 100644index 0000000000..6aa42dc996--- /dev/null+++ b/packages/sheets-plugin-formula/src/models/formula-data.model.ts@@ -0,0 +1,44 @@+import { ArrayFormulaDataType, IFormulaData } from '@univerjs/base-formula-engine';+import { Disposable, ObjectMatrix } from '@univerjs/core';++export interface IFormulaConfig {+ formulaData: IFormulaData;+}++export class FormulaDataModel extends Disposable {+ private _formulaData: IFormulaData = {};++ private _arrayFormulaData: ArrayFormulaDataType = {};++ constructor(config?: IFormulaConfig) {+ super();++ if (config?.formulaData) {+ this._formulaData = config.formulaData;+ }+ }++ getFormulaData() {+ return this._formulaData;+ }++ setFormulaData(value: IFormulaData) {+ this._formulaData = value;+ }++ getArrayFormulaData(): ArrayFormulaDataType {+ return this._arrayFormulaData;+ }++ setArrayFormulaData(value: ArrayFormulaDataType) {+ Object.keys(value).forEach((sheetId) => {+ const arrayFormula = value[sheetId];+ if (!this._arrayFormulaData[sheetId]) {+ this._arrayFormulaData[sheetId] = new ObjectMatrix();+ }+ arrayFormula.forValue((r, c, v) => {+ this._arrayFormulaData[sheetId].setValue(r, c, v);+ });+ });+ }+}diff --git a/packages/sheets-plugin-formula/src/services/function-list.ts b/packages/sheets-plugin-formula/src/services/function-list.tsindex cea1437304..c043dd7a29 100644--- a/packages/sheets-plugin-formula/src/services/function-list.ts+++ b/packages/sheets-plugin-formula/src/services/function-list.ts@@ -63,62 +63,74 @@ export interface IFunctionInfo {/*** Function name*/- n: string;+ functionName: string;++ /**+ * Alias Function name+ */+ aliasFunctionName?: string;/*** Function type*/- t: FunctionType;+ functionType: FunctionType;/*** Detailed description*/- d: string;+ description: string;/**- * Concise description+ * Concise abstract*/- a: string;+ abstract: string;/*** [Minimum number of parameters, maximum number of parameters]* Detected before each calculation of the function*/- m: [min: number, max: number];+ parameterRange: [min: number, max: number];/*** Function params*/- p: IFunctionParam[];+ functionParameter: IFunctionParam[];+}++// TODO@Dushusir: register custom function+// TODO@Dushusir: register custom locale file+export interface IFunctionDescription {+ [functionName: string]: IFunctionInfo;}export const FUNCTION_LIST: IFunctionInfo[] = [{- n: 'SUMIF',- t: 0,- d: 'formula.functionList.SUMIF.d',- a: 'formula.functionList.SUMIF.a',- m: [2, 3],- p: [+ functionName: 'SUMIF',+ aliasFunctionName: 'formula.functionList.SUMIF.aliasFunctionName',+ functionType: 0,+ description: 'formula.functionList.SUMIF.description',+ abstract: 'formula.functionList.SUMIF.abstract',+ parameterRange: [2, 3],+ functionParameter: [{- name: 'formula.functionList.SUMIF.p.range.name',- detail: 'formula.functionList.SUMIF.p.range.detail',+ name: 'formula.functionList.SUMIF.functionParameter.range.name',+ detail: 'formula.functionList.SUMIF.functionParameter.range.detail',example: 'A1:A10',require: 1,repeat: 0,type: 'range',},{- name: 'formula.functionList.SUMIF.p.criterion.name',- detail: 'formula.functionList.SUMIF.p.criterion.detail',+ name: 'formula.functionList.SUMIF.functionParameter.criterion.name',+ detail: 'formula.functionList.SUMIF.functionParameter.criterion.detail',example: '">20"',require: 1,repeat: 0,type: 'rangeall',},{- name: 'formula.functionList.SUMIF.p.sum_range.name',- detail: 'formula.functionList.SUMIF.p.sum_range.detail',+ name: 'formula.functionList.SUMIF.functionParameter.sum_range.name',+ detail: 'formula.functionList.SUMIF.functionParameter.sum_range.detail',example: 'B1:B10',require: 0,repeat: 0,@@ -127,15 +139,16 @@ export const FUNCTION_LIST: IFunctionInfo[] = [],},{- n: 'TAN',- t: 0,- d: 'formula.functionList.TAN.d',- a: 'formula.functionList.TAN.a',- m: [1, 1],- p: [+ functionName: 'TAN',+ aliasFunctionName: 'formula.functionList.TAN.aliasFunctionName',+ functionType: 0,+ description: 'formula.functionList.TAN.description',+ abstract: 'formula.functionList.TAN.abstract',+ parameterRange: [1, 1],+ functionParameter: [{- name: 'formula.functionList.TAN.p.angle.name',- detail: 'formula.functionList.TAN.p.angle.detail',+ name: 'formula.functionList.TAN.functionParameter.angle.name',+ detail: 'formula.functionList.TAN.functionParameter.angle.detail',example: '45*PI()/180',require: 1,repeat: 0,@@ -144,15 +157,15 @@ export const FUNCTION_LIST: IFunctionInfo[] = [],},{- n: 'TANH',- t: 0,- d: 'formula.functionList.TANH.d',- a: 'formula.functionList.TANH.a',- m: [1, 1],- p: [+ functionName: 'TANH',+ functionType: 0,+ description: 'formula.functionList.TANH.description',+ abstract: 'formula.functionList.TANH.abstract',+ parameterRange: [1, 1],+ functionParameter: [{- name: 'formula.functionList.TANH.p.value.name',- detail: 'formula.functionList.TANH.p.value.detail',+ name: 'formula.functionList.TANH.functionParameter.value.name',+ detail: 'formula.functionList.TANH.functionParameter.value.detail',example: 'A2',require: 1,repeat: 0,diff --git a/packages/sheets-plugin-formula/src/services/prompt.service.ts b/packages/sheets-plugin-formula/src/services/prompt.service.tsindex ff6f4460d8..e324e8b5f2 100644--- a/packages/sheets-plugin-formula/src/services/prompt.service.ts+++ b/packages/sheets-plugin-formula/src/services/prompt.service.ts@@ -1,3 +1,4 @@+import { IFunctionInfo } from '@univerjs/base-formula-engine';import { Direction } from '@univerjs/core';import { createIdentifier, IDisposable } from '@wendellhu/redi';import { Observable, Subject } from 'rxjs';@@ -17,6 +18,11 @@ export interface ISearchFunctionParams {* function search text*/searchText: string;++ /**+ * function list+ */+ searchList: ISearchItem[];}export interface IHelpFunctionCommandParams {@@ -26,14 +32,14 @@ export interface IHelpFunctionCommandParams {visible: boolean;/**- * function name+ * function param index*/- functionName: string;+ paramIndex: number;/**- * function param index+ * function info*/- paramIndex: number;+ functionInfo: IFunctionInfo;}export interface INavigateParam {diff --git a/packages/sheets-plugin-formula/src/views/prompt/help-function/HelpFunction.tsx b/packages/sheets-plugin-formula/src/views/prompt/help-function/HelpFunction.tsxindex 94dcf009b9..6140fcea95 100644--- a/packages/sheets-plugin-formula/src/views/prompt/help-function/HelpFunction.tsx+++ b/packages/sheets-plugin-formula/src/views/prompt/help-function/HelpFunction.tsx@@ -5,7 +5,7 @@ import { ICellEditorManagerService } from '@univerjs/ui-plugin-sheets';import { useDependency } from '@wendellhu/redi/react-bindings';import React, { useEffect, useState } from 'react';-import { FUNCTION_LIST, IFunctionInfo, IFunctionParam } from '../../../services/function-list';+import { IFunctionInfo, IFunctionParam } from '../../../services/function-list';import { IFormulaPromptService, IHelpFunctionCommandParams } from '../../../services/prompt.service';import styles from './index.module.less';@@ -26,17 +26,19 @@ export function HelpFunction() {const selection = cellEditorManagerService.getState();if (!selection) return;- const { visible, functionName, paramIndex } = params;- const info = FUNCTION_LIST.find((item) => item.n === functionName);- if (!info) return;+ const { visible, paramIndex, functionInfo } = params;+ if (!visible) {+ setVisible(visible);+ return;+ }const localeInfo: IFunctionInfo = {- n: info.n as string,- t: info.t,- d: localeService.t(info.d) as string,- a: localeService.t(info.a) as string,- m: info.m,- p: info.p.map((item) => ({+ functionName: functionInfo.functionName as string,+ functionType: functionInfo.functionType,+ description: localeService.t(functionInfo.description) as string,+ abstract: localeService.t(functionInfo.abstract) as string,+ parameterRange: functionInfo.parameterRange,+ functionParameter: functionInfo.functionParameter.map((item) => ({name: localeService.t(item.name) as string,detail: localeService.t(item.detail) as string,example: item.example,@@ -49,8 +51,8 @@ export function HelpFunction() {setOffset([startX, endY]);setParamIndex(paramIndex);setFunctionInfo(localeInfo);- setVisible(visible);setDecoratorPosition({ left: startX, top: startY });+ setVisible(visible);});return () => {@@ -73,8 +75,8 @@ export function HelpFunction() {<div className={styles.formulaHelpFunction}><div className={styles.formulaHelpFunctionTitle}><Help- title={functionInfo.n}- value={functionInfo.p}+ title={functionInfo.functionName}+ value={functionInfo.functionParameter}type="name"active={paramIndex}onClick={handleSwitchActive}@@ -103,17 +105,17 @@ export function HelpFunction() {<div className={styles.formulaHelpFunctionContentInner}><Paramstitle={localeService.t('formula.formulaMore.helpExample') as string}- value={`${functionInfo.n}(${functionInfo.p+ value={`${functionInfo.functionName}(${functionInfo.functionParameter.map((item) => item.example).join(',')})`}/><Paramstitle={localeService.t('formula.formulaMore.helpAbstract') as string}- value={functionInfo.d}+ value={functionInfo.description}/>{functionInfo &&- functionInfo.p &&- functionInfo.p.map((item: IFunctionParam, i: number) => (+ functionInfo.functionParameter &&+ functionInfo.functionParameter.map((item: IFunctionParam, i: number) => (<Paramskey={i}className={paramIndex === i ? styles.formulaHelpFunctionActive : ''}@@ -132,7 +134,7 @@ export function HelpFunction() {><span></span></Dropdown>- ) : (+ ) : visible ? (<divclassName={styles.formulaHelpDecorator}onClick={() => setHelpVisible(!helpVisible)}@@ -140,6 +142,8 @@ export function HelpFunction() {><DetailsSingle /></div>+ ) : (+ <></>)}</>);diff --git a/packages/sheets-plugin-formula/src/views/prompt/search-function/SearchFunction.tsx b/packages/sheets-plugin-formula/src/views/prompt/search-function/SearchFunction.tsxindex fd1be383e4..20e4eb78d6 100644--- a/packages/sheets-plugin-formula/src/views/prompt/search-function/SearchFunction.tsx+++ b/packages/sheets-plugin-formula/src/views/prompt/search-function/SearchFunction.tsx@@ -1,10 +1,9 @@-import { Direction, LocaleService } from '@univerjs/core';+import { Direction } from '@univerjs/core';import { Dropdown } from '@univerjs/design';import { ICellEditorManagerService } from '@univerjs/ui-plugin-sheets';import { useDependency } from '@wendellhu/redi/react-bindings';import React, { useEffect, useState } from 'react';-import { FUNCTION_LIST } from '../../../services/function-list';import {IFormulaPromptService,INavigateParam,@@ -21,7 +20,6 @@ export function SearchFunction() {const [searchText, setSearchText] = useState<string>('');const promptService = useDependency(IFormulaPromptService);const cellEditorManagerService = useDependency(ICellEditorManagerService);- const localeService = useDependency(LocaleService);useEffect(() => {// TODO@Dushusir: How to get updated values in subscribe callback better@@ -31,19 +29,17 @@ export function SearchFunction() {const selection = cellEditorManagerService.getState();if (!selection) return;- const { visible, searchText } = params;- const { startX = 0, endY = 0 } = selection;+ const { visible, searchText, searchList } = params;+ if (!visible) {+ setVisible(visible);+ return;+ }- const result: ISearchItem[] = [];- FUNCTION_LIST.forEach((item) => {- if (item.n.indexOf(searchText) > -1) {- result.push({ name: item.n, desc: localeService.t(item.a) as string });- }- });+ const { startX = 0, endY = 0 } = selection;setSearchText(searchText);- setSearchList(result);- updatedSearchList = result;+ setSearchList(searchList);+ updatedSearchList = searchList;setOffset([startX, endY]);setVisible(visible);setActive(0); // Reset active statediff --git a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.tsindex 1c5c7b1633..c7662ce425 100644--- a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts+++ b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts@@ -15,7 +15,7 @@ import {DocumentModel,FOCUSING_EDITOR,FOCUSING_EDITOR_BUT_HIDDEN,- FOCUSING_EDITOR_FORMULA,+ FOCUSING_EDITOR_INPUT_FORMULA,ICellData,ICommandInfo,ICommandService,@@ -180,7 +180,7 @@ export class EndEditController extends Disposable {}private _exitInput(param: IEditorBridgeServiceVisibleParam) {- this._contextService.setContextValue(FOCUSING_EDITOR_FORMULA, false);+ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);this._contextService.setContextValue(FOCUSING_EDITOR, false);this._contextService.setContextValue(FOCUSING_EDITOR_BUT_HIDDEN, false);this._cellEditorManagerService.setState({diff --git a/packages/ui-plugin-sheets/src/controllers/shortcuts/editor.shortcut.ts b/packages/ui-plugin-sheets/src/controllers/shortcuts/editor.shortcut.tsindex 174d6fc382..5e72c5ddbe 100644--- a/packages/ui-plugin-sheets/src/controllers/shortcuts/editor.shortcut.ts+++ b/packages/ui-plugin-sheets/src/controllers/shortcuts/editor.shortcut.ts@@ -7,7 +7,7 @@ import {SetCellEditVisibleArrowOperation,SetCellEditVisibleOperation,} from '../../commands/operations/cell-edit.operation';-import { whenEditorActivatedIsVisible, whenEditorFocusIsHidden } from './utils';+import { whenEditorActivatedIsVisible, whenEditorDidNotInputFormulaActivated, whenEditorFocusIsHidden } from './utils';export const ARROW_SELECTION_KEYCODE_LIST = [KeyCode.ARROW_DOWN,@@ -24,7 +24,7 @@ export function generateArrowSelectionShortCuItem() {shortcutList.push({id: SetCellEditVisibleArrowOperation.id,binding: keycode,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_EDITOR),+ preconditions: (contextService) => whenEditorDidNotInputFormulaActivated(contextService),staticParameters: {visible: false,eventType: DeviceInputEventType.Keyboard,@@ -38,7 +38,7 @@ export function generateArrowSelectionShortCuItem() {export const EditorCursorEnterShortcut: IShortcutItem = {id: SetCellEditVisibleOperation.id,binding: KeyCode.ENTER,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_EDITOR),+ preconditions: (contextService) => whenEditorDidNotInputFormulaActivated(contextService),staticParameters: {visible: false,eventType: DeviceInputEventType.Keyboard,@@ -49,7 +49,7 @@ export const EditorCursorEnterShortcut: IShortcutItem = {export const EditorCursorTabShortcut: IShortcutItem = {id: SetCellEditVisibleOperation.id,binding: KeyCode.TAB,- preconditions: (contextService) => contextService.getContextValue(FOCUSING_EDITOR),+ preconditions: (contextService) => whenEditorDidNotInputFormulaActivated(contextService),staticParameters: {visible: false,eventType: DeviceInputEventType.Keyboard,diff --git a/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts b/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.tsindex 3a8c7acd4e..0f3eafc2f5 100644--- a/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts+++ b/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts@@ -1,4 +1,10 @@-import { FOCUSING_EDITOR, FOCUSING_EDITOR_BUT_HIDDEN, FOCUSING_SHEET, IContextService } from '@univerjs/core';+import {+ FOCUSING_EDITOR,+ FOCUSING_EDITOR_BUT_HIDDEN,+ FOCUSING_EDITOR_INPUT_FORMULA,+ FOCUSING_SHEET,+ IContextService,+} from '@univerjs/core';export function whenEditorNotActivated(contextService: IContextService) {return contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_EDITOR);@@ -15,3 +21,16 @@ export function whenEditorActivatedIsVisible(contextService: IContextService) {contextService.getContextValue(FOCUSING_EDITOR) && contextService.getContextValue(FOCUSING_EDITOR_BUT_HIDDEN));}++export function whenEditorInputFormulaActivated(contextService: IContextService) {+ return (+ contextService.getContextValue(FOCUSING_EDITOR) && contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA)+ );+}++export function whenEditorDidNotInputFormulaActivated(contextService: IContextService) {+ return (+ contextService.getContextValue(FOCUSING_EDITOR) &&+ !contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA)+ );+}diff --git a/packages/ui-plugin-sheets/src/index.ts b/packages/ui-plugin-sheets/src/index.tsindex 46e0edddba..be037aa962 100644--- a/packages/ui-plugin-sheets/src/index.ts+++ b/packages/ui-plugin-sheets/src/index.ts@@ -1,5 +1,6 @@export * from './basics';export { SetCellEditVisibleArrowOperation } from './commands/operations/cell-edit.operation';+export { whenEditorInputFormulaActivated } from './controllers/shortcuts/utils';export {getCoordByCell,getCoordByOffset,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1f18a4dce6..57e82d9ee2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -920,6 +920,9 @@ importers:'@univerjs/base-docs':specifier: workspace:*version: link:../base-docs+ '@univerjs/base-formula-engine':+ specifier: workspace:*+ version: link:../base-formula-engine'@univerjs/base-render':specifier: workspace:*version: link:../base-render